I know that there have been a number of questions concerning importing modules in python, but my question seems to be somewhat different.
I'm trying to understand when you have to import a whole module as opposed to when you have to import a specific entry in the module. It seems that only one of the two ways work.
For example if I want to use basename, importing os.path doesn't do the trick.
>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined
Instead I need to import basename from os.path as in
>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'
Going the other way, if I want to use shutil.copyfile, importing copyfile from shutil doesn't work
>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined
Instead I must import shutil as in
>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>
The only way I have been able to get this right is through experimentation. Are there some guidelines to avoid experimentation?
2 Answers 2
If you import
import os.path
then you have to use full namespace os.path
os.path.basename()
If you import with from
from shutil import copyfile
then you don't have to use full namespace shutil
copyfile(...)
That's all.
If you use as
import os.path as xxx
then you have to use xxx instead of os.path
xxx.basename()
If you use from and as
from os.path import basename as xxx
then you have to use xxx instead of basename
xxx()
1 Comment
xxx.basename()you could use form module import *
from time import *
sleep(2)
which allow you to call its submodules, instead of:
from time import sleep
sleep(2)
or:
import time
time.sleep(2)
this imports every sub-module of the package https://docs.python.org/2/tutorial/modules.html#importing-from-a-package
2 Comments
from ... import * makes a mess of your namespace and is bad style.
importstatement, thusimport a.b; a.b.c()is valid and so isfrom a.b import c; c(), but these two are invalid:import a.b; c()(You're treating it like a global object),from a.b import c; c()(The module is 'forgotten' by Python).#includeworks in C. In Python, you're not copy-pasting the module. The interpreter opens it, reads it and interprets it, then creates a 'variable' pointing at the module and its contents.from a.b import c; a.b.c().