How Does Import Keyword In Python Actually Work?
Solution 1:
I guess it's a problem of scoping, if you import a module in your constructor you can only use it in your constructor, after the import statement.
Solution 2:
According to the Python documentation,
Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs).
So the problem is that even though module a
has been imported, the name a
has only been bound in the scope of the b.__init__
method, not the entire scope of b.py
. So in the b.test
method, there is no such name a
, and so you get a NameError
.
You might want to read this article on importing Python modules, as it helps to explain best practices for working with import
s.
Solution 3:
In your case, a is in sys.modules.. but not everything in sys.modules is in b's scope. If you want to use re, you'd have to import that as well.
Conditional importing is occasionally acceptable, but this isn't one of those occasions. For one thing, the circular dependency between a and b in this case is unfortunate, and should be avoided (lots of patterns for doing so in Fowler's Refactoring).. That said, there's no need to conditionally import here.
b ought to simply import a. What were you trying to avoid by not importing it directly at the top of the file?
Solution 4:
It is bad style to conditionally import code modules based on program logic. A name should always mean the same thing everywhere in your code. Think about how confusing this would be to debug:
if (something)
from office import desk
elsefrom home import desk
... somewhere later in the code...
desk()
Even if you don't have scoping issues (which you most likely will have), it's still confusing.
Put all your import statements at the top of your file. That's where other coders will look for them.
As far as whether to use "from foo import bar" verses just "import foo", the tradeoff is more typing (having to type "foo.bar()" or just type "bar()") verses clearness and specificity. If you want your code to be really readable and unambiguous, just say "import foo" and fully specify the call everywhere. Remember, it's much harder to read code than it is to write it.
Post a Comment for "How Does Import Keyword In Python Actually Work?"