3

I've got a package called elements that contains some stuff like button, trifader, poster. In the Button class, I am doing from elements import *

This executes OK, and when I try to print(poster), also works OK and functions as expected. However, when I do print(trifader), NameError: name 'trifader' is not defined. Even though trifader and poster are in the same package, poster is defined, but trifader isn't? How weird. Is there any explanation for this?

The directory structure of the elements package is this:

Elements:
  __init__.py
  trifader.py
  button.py
  poster.py

Also, some other stuff that isn't really relevant.

Each .py file contains a class with the name of the .py, for example, trifader.py has a class called TriFader.

Name McChange
  • 2,750
  • 5
  • 27
  • 46

2 Answers2

2

If your __init__.py doesn't have __all__ defined (thus restricting what is imported using from X import *), then you probably have a circular import somewhere which is causing a module to be referenced before its' definitions have been evaluated.

Nick Bastin
  • 30,415
  • 7
  • 59
  • 78
0

Check for circular imports. Circular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd. Secondly, if the import is called inside the function by the time the import is called, the first module will have finished initializing, and the second module can do its import.

Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • Circular imports aren't necessarily fine when both use the non-star `import` form - if you have class definitions in both modules which require names from the other module you will also have a problem. The only case in which is a circular import is "fine" is when names don't need to be resolved until runtime (when both modules are already instantiated), as opposed to compile time (when their members are used in the instantiation of another definition). – Nick Bastin Nov 08 '12 at 02:11