How to organize Python files in a (relatively) big project

Claudio Grondi claudio.grondi at freenet.de
Wed Oct 19 07:19:21 EDT 2005


Maybe looking at the todays thread  ["dynamical" importing] can be helpful
also here.

Claudio
P.S. Below a copy of one of the responses:
:
Joerg Schuster wrote:

> I need to import modules from user defined paths. I.e. I want to do
> something like:
>
> module_dir = sys.argv[1]
>
> my_path = os.path.join(module_dir, 'bin', 'my_module')
>
> from my_path import my_object
>
> Obviously, it doesn't work this way. How would it work?

some alternatives:

- if you want the modules to remain imported:

    try:
        sys.path.insert(0, os.path.join(module_dir, "bin"))
        module = __import__("my_module")
    finally:
        del sys.path[0]
    object = module.my_object

- if you're only interested in the object:

    namespace = {}
    execfile(os.path.join(module_dir, "bin", "my_module" + ".py"),
namespace)
    object = namespace["my_object"]

</F>


"TokiDoki" <neuromancer at wanadoo.fr> schrieb im Newsbeitrag
news:dj492l$3hf$1 at apollon.grec.isp.9tel.net...
> Hello there,
>
> I have been programming python for a little while, now. But as I am
> beginning to do more complex stuff, I am running into small organization
> problems.
> It is possible that what I want to obtain is not possible, but I would
> like the advice of more experienced python programmers.
>
> I am writing a relatively complex program in python that has now around
> 40 files.
> At first, I had all of my files in one single directory, but now, with
> the increasing number of files, it is becoming hard to browse my
directory.
> So, I would want to be able to divide the files between 8 directory,
> according to their purpose. The problem is that it breaks the 'import's
>    between my files. And besides,AFAIK, there is no easy way to import a
> file that is not in a subdirectory of the current file (I suppose I
> could adjust the os.path in every file, but that seems not very elegant
> to me).
> I thought about turning the whole into a package. But I have to change
> every 'import module_name' into
> 'from package_name.sub_directory_name import module_name'
> which is a little bit time consuming and not very flexible (if I change
> my mind about the subdirectory a file belongs to, I will have to track
> again every import to correct them)
>
> So, basically, here is the point: is there an 'elegant' way to keep my
> files in separate directory and still be able to import between them
> with simple 'import filename'?
>
> And if not, what would be the standard way to organize numerous python
> files belonging to the same project?
>
> Thank you,
>
> TokiDoki





More information about the Python-list mailing list