py files includings each others

Andrew Clover and-google at doxdesk.com
Wed Mar 24 15:42:34 EST 2004


Nicolas Bouillon <bouil at bouil.org.invalid> wrote:

> a.py:

> from b import Father
> class Person: ...

> b.py:

> from a import Person
> class Father(Person): ...

Person must be defined first, as Father is a subclass of it. You can't
import Father from b.py before its subclass has been defined. Moving the
import statement below the class definition for Person makes it all right.

Person can refer to 'Father' in a method def before that class gets
defined because the name won't actually be looked up until the method is
executed, long after the import stage.

Putting an import at the bottom of a file is not the norm, but it would
work in this case.

> I have more than twenty classes, with one py file per class (more clear 
> & clean)

Ah, a Java programmer! This isn't necessarily always the best thing in
Python, it's more a matter of style and compromise. In this example
grouping the dependant-classes Person and Father in the same module (in
that order) might make sense and would certainly cut down on import issues.

Another tip (that isn't relevant to this exact case) is to try to import
modules rather than members when there may be interdependency. Modules can
always be imported and their members will appear later, hopefully by the
time you need them. Directly imported members, on the other hand, must
exist at import-time. For example:

  a.py:

  import b
  c= 'frog'
  b.printC()

  b.py:

  import a
  def printC():
    print a.c

Here, the getting-c-from-a operation doesn't happen until the call to
b.printC(), after the importing stage is over, so c is in place and
'frog' is printed. On the other hand, if you wrote:

  from a import c

then the get-c-from-a operation happens before 'a' has all its members
defined, and fails.

Hope that makes some sense.

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/



More information about the Python-list mailing list