Richard Gostanian
Richard Gostanian

Reputation: 163

guidelines for importing modules in python

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?

Upvotes: 0

Views: 1261

Answers (2)

furas
furas

Reputation: 143097

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()

Upvotes: 4

Shailyn Ortiz
Shailyn Ortiz

Reputation: 766

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

Upvotes: -1

Related Questions