Reputation: 35136
I'm sure this is trivial to do, but I can't figure it out.
Directory structure:
mylib/__init__.py
mylib/MyClass.py
init.py reads:
import MyClass
__all__ = [MyClass]
MyClass.py:
class MyClass(object):
def __init__(self):
pass
I have to create instances of MyClass using mylib.MyClass.MyClass(), when I want it to be mylib.MyClass()
I thought that to get this to work I have to put all = [MyClass.MyClass], but that didn't work.
How do you get this to work?
NB. I understand what is happening here; the file itself is a namespace and you could for example say, have multiple classes in a single file. However, I only have one class in each .py file, so I don't want that level of detail.
ie. I have this:
>>> import mylib
>>> tmp = mylib.MyClass.MyClass()
I want this:
>>> import mylib
>>> tmp = mylib.MyClass()
Upvotes: 3
Views: 335
Reputation: 184191
In your __init__.py
, nstead of import MyClass
try from MyClass import MyClass
.
The former command imports the module's name into your namespace; the second imports a symbol from the module (in this case, the name of a class) into your namespace.
Also, __all__
should be a list of names, i.e., strings, not references.
Generally, there is not any advantage in Python to dividing up your classes one to a file, and some mild disadvantages to doing so. Usually all your classes would be in a single file, and users would already be able to access your class as mylib.MyClass
.
Upvotes: 8