socrates socrates - 3 months ago 7
Python Question

Sharing code between python files

Lets say I have the following files:

-- classes.py
-- main.py
-- commands.py
-- output.py


main.py
is the master file which uses the code from
classes
,
commands
, and
output
.
commands
takes objects defined in
classes
as functional inputs and accesses methods/attributes of these objects. Both
commands
and
classes
use functions defined in
output
.

The question: do I need to import each of these modules in each of the files that depend on them?
i.e.: do I need to import
output
in both
classes
,
commands
, and
main
? Or would the fact that
classes
,
output
, and
commands
are all imported into
main
mean that they don't need to be imported individually?

What is the best practice for handling multiple files with inter-dependencies?

Answer

The question: do I need to import each of these modules in each of the files that depend on them? i.e.: do I need to import output in both classes, commands, and main?

Yes, this is the way to go.

Or would the fact that classes, output, and commands are all imported into main mean that they don't need to be imported individually?

No.

Python files are modules. A python module has a symbol table. Every function, class and variable specified in the module are in this table. A module can only use things which are in this table plus Python builtins.

So for example classes.py:

def function(): pass
class Class(object): pass

Has symbol table:

{
    'function': function,
    'Class': Class
}

You can only use function and Class within classes.py (plus mentioned builtins). You cannot access anything outside of this module implicitly, Python does not have any concept of namespace like C# and Java have. If you need anything from a different file (module), you must explicitly import it.

Now what really happens when you "import"?

Something quite straightforward - the imported module "becomes" part of the module itself!

In the next example we have output.py:

def output_function(): pass

with symbol table:

{
    'output_function': output_function
}

and classes.py:

import output
from output import output_function

def function(): pass
class Class(object): pass

with symbol table:

{
    'Class': Class,
    'function': function,
    'output': {
        'output_function': output_function
    }
    'output_function': output_function
}

where value of 'output' is actually the symbol table of 'output' (the very same object)!

You can even do in a different module:

import classes

classes.output.output_function()

But don't, be explicit about your imports.

It might sound a little bit weird, but this is how Python works. Note there are more things involved, for example when you import a module for the first time it's executed and so on...

Comments