1

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.

asked Aug 20, 2012 at 18:50

1 Answer 1

1

To import the class you must import the class, somewhere. When you do from foolib import *, because of your __init__.py this imports the module bar. It doesn't allow you to access anything inside that module.

If you want to automatically access everything in bar from the foolib package without having to import bar, you could put this in __init__.py:

from bar import *

This makes everything in bar available directly in foolib.

answered Aug 20, 2012 at 18:55
Sign up to request clarification or add additional context in comments.

3 Comments

That works fine, but it is still calling the module explicitly. Is there another way? I feel like this will not scale very well for multiple modules.
Are you saying you want to automatically import everything from all modules in the package? You can do that, but you will have to do it manually, by looking for all the files in the directory and importing them programmatically. It's also unlikely to be a good idea, as it will lead to namespace collisions if any of the modules define the same names. Because of this, Python doesn't provide any easy way to do it. The right way is to explicitly import the modules you are going to use.
Yeah, that's what I was looking for. I figured it would be something like that. Thanks. I will just stick with importing them explicitly.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.