henrebotha henrebotha - 5 months ago 14
Python Question

Python: access objects from another module

I'm a very inexperienced programmer creating a game (using Python 3.3) as a learning exercise. I currently have a main module and a combat module.

The people in the game are represented by instances of class "Person", and are created in the main module. However, the combat module obviously needs access to those objects. Furthermore, I'm probably going to create more modules later that will also need access to those objects.

How do I allow other modules to access the Persons from main.py?

As things stand, main.py has

import combat


at the top; adding

import main


to combat.py doesn't seem to help.

Should I instantiate my objects in a separate module (common.py?) and import them to every module that needs to access them?

Answer

Yes, you should definitely factor this out. What you tried is circular imports between your modules, and that can be very problematic. If combat imports main and main imports combat, then you may get an exception because main will not have finished executing when combat starts executing for the import. Assuming main is your start up script, it should probably do nothing more than instantiate a class or call a method from another module. Avoid global variables, too. Even if it doesn't seem like they'll be a problem now, that can bite you in the behind later on.

That said, you can reference members of a module like so:

import common
x = common.some_method_in_common()
y = common.SomeClass()

or

from common import SomeClass
y = SomeClass()

Personally, I generally avoid referencing a method from another module without qualifying it with the module name, but this is also legal:

from common import some_method_in_common
x = some_method_in_common()

An alternate syntax of which is discouraged is

from common import *
y = SomeClass()

This will import every member of common into the current scope that does not start with an underscore (_). I believe the reason this is discouraged is because of what happens when you have 2 imports.

from common import *
from some_other_module import *
y = SomeClass()

Which module does SomeClass come from? There's no way to tell other than to go look at the two modules. Worse, what if both modules define SomeClass or SomeClass is later added to some_other_module?

Comments