I have the following files in my directory:
foo/
foo.py
foolib/
__init__.py
bar.py
Within __init__.py:
__all__ = ["bar"]
Within bar.py:
class Bar:
def __init__(self):
None
def hello(self):
print("Hello World")
return
def hi():
print("Hi World")
Now if I have the following code within foo.py:
from foolib import *
bar.hi()
foobar = Bar()
foobar.hello()
“Hi World” prints, but I get a NameError for Bar(). If I explicitly import the module:
from foolib.bar import *
I get the expected output “Hello World”.
Is there a way for me to import classes from the modules, without explicitly calling them? I feel like I am missing something in the __init__ file. Either that or I am flagrantly violating some Python best practice.
To import the class you must import the class, somewhere. When you do
from foolib import *, because of your__init__.pythis imports the modulebar. It doesn’t allow you to access anything inside that module.If you want to automatically access everything in
barfrom thefoolibpackage without having to importbar, you could put this in__init__.py:This makes everything in
baravailable directly infoolib.