Scipio
Scipio

Reputation: 313

Best practice to bundle .py files

I am relatively new to python programming, I'm used to C++; I guess this is answered before, but I cannot find it. I use Python(x,y), which runs on Spyder.

I have a couple of related long functions in separated .py files. The functions rely on the same modules. I would like the user to be able to call these functions from the IPython console. Preferably, the user can run a single command to make all functions available. What is the most common way to do this? I can put a whole bunch of 'import' commands in the main of a file, but this seems not very elegant. Creating a project (or a module) may work, but I can't find any good documentation and it seems a bit overkill.

Thank you for your suggestions!

Upvotes: 0

Views: 110

Answers (2)

Dan D.
Dan D.

Reputation: 74645

If you want the user to be able to import your functions like:

import your_module

and then access your functions as your_module.function_a and your_module.function_b, even if function_a lives in one file and function_b lives in another.

Use a directory module which is a directory with a __init__.py file. Like this:

- your_module
  |- __init__.py
  |- function_a.py
  \- function_b.py

In that file __init__.py you can include import statements such as:

from function_a import function_a
from function_b import function_b

Note that this would also support doing from your_module import * but I would recommended using import your_module as short_name instead where possible.

Upvotes: 2

m.wasowski
m.wasowski

Reputation: 6387

Module is exactly what you need, and it is not hard at all, see:

http://docs.python.org/2/tutorial/modules.html

Upvotes: 2

Related Questions