0

I have a python package main and other_python_files which are like:

main/
    __init__.py
    lib.py
    other_python_files/
        __init__.py
        test.py

Let lib.py contain a class called MyClass. When I do from main import lib.py and use MyClass inside test.py I get the error that MyClass is not defined.

I tried doing from main import MyClass inside the init file in the main directory but I still get the same error. What should I do to achieve importing a specific class from the lib.py file ?

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • Your package example is inclear. Why is "other python files" in there twice? Please fix it and indent things to make clear what is nested inside what. – BrenBarn Mar 28 '13 at 17:49
  • The other one was actually showing the contents of other python files. I edited to show this – Cemre Mengü Mar 28 '13 at 17:51
  • 1
    I have edited your post to show what I understand you as meaning. Please correct it if I did it wrong. It's better to just show the entire directory tree with indentation to indicate nesting, instead of showing each directory separately. – BrenBarn Mar 28 '13 at 17:58
  • Thanks @BrenBarn the way you did is much better – Cemre Mengü Mar 28 '13 at 18:00

1 Answers1

2

You either have to import that class out of lib:

from main.lib import MyClass

Or use lib.MyClass in place of MyClass.

You can also import MyClass inside of the __init__.py file that's in main, which lets you import it the way you originally tried:

__all__ = ['MyClass']

from lib import MyClass

You can read about __all__ here: Can someone explain __all__ in Python?

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496