I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.
What is so special about ldap.modlist that I have to explicitly import it? Importing ldap is not enough:
>>> import ldap
>>> ldap.modlist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'modlist'
But if I explicitly import it, then all is well:
>>> import ldap
>>> import ldap.modlist
>>> ldap.modlist
<module 'ldap.modlist' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/modlist.pyc'>
Why? Other modules don't behave like this:
>>> import os
>>> os.path
<module 'posixpath' from '/opt/rh/python27/root/usr/lib64/python2.7/posixpath.pyc'>
>>> import ldap
>>> ldap.dn
<module 'ldap.dn' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/dn.pyc'>
The difference between the modules ldap.dn and ldap.modlist is this:
The module ldap.dn is loaded during the initialization of the ldap package and is therefore already present as an attribute in the ldap package (see The Import System: Submodules for a description about submodules):
# ldap/__init__.py, line 89 of python-ldap version 2.4.27
from ldap.dn import explode_dn,explode_rdn,str2dn,dn2str
The module ldap.modlist on the other hand is not loaded during the initalization of the ldap package.
Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale
CashAMDSale.AMDSale()
and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *
def AMDSale():
AMDInstance = DataFunctions.GetValidAMD()
And here is GetValidAMD
import pyodbc
def ValidAMD(GetValidAMD):
(short method talking to a database)
My error comes up on the line that has AMDInstance = DataFunctions.GetValidAMD()
I get the error AttributeError: 'module' object has no attribute 'GetValidAMD'
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks!
DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD
or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]
then you can import * from the package and everything listen in __all__ will be imported
When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
print 'foo'
>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo
When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
print 'bar'
>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar
When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo
Now, assuming your project structure is:
main.py
DataFunctions/
__init__.py
CashAMDSale.py
def AMDSale(): ...
GetValidAMD.py
def ValidAMD(GetValidAMD): ...
your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().
Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD()
I want to get the path and source code of the __builtin__ module, where can I get it?
Latest (trunk) C sources of __builtin__ module: http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup
The __builtin__ module is built-in, there is no Python source for it. It's coded in C and included as part of the Python interpreter executable.
You can't. it is built-in to the interpreter.
>>> # os is from '/usr/lib/python2.7/os.pyc'
>>> import os
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> # PyQt4 is from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'
>>> import PyQt4
>>> PyQt4
<module 'PyQt4' from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'>
>>> # __builtin__ is built-in
>>> import __builtin__
>>> __builtin__
<module '__builtin__' (built-in)>
In a program, you could use the __file__ attribute, but built-in modules do not have it.
>>> os.__file__
'/usr/lib/python2.7/os.pyc'
>>> PyQt4.__file__
'/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'
>>> __builtin__.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
In Python, once I have imported a module X in an interpreter session using import X, and the module changes on the outside, I can reload the module with reload(X). The changes then become available in my interpreter session.
I am wondering if this also possible when I import a component Y from module X using from X import Y.
The statement reload Y does not work, since Y is not a module itself, but only a component (in this case a class) inside of a module.
Is it possible at all to reload individual components of a module without leaving the interpreter session (or importing the entire module)?
EDIT:
For clarification, the question is about importing a class or function Y from a module X and reloading on a change, not a module Y from a package X.
Answer
From my tests, the marked answer, which suggests a simple reload(X), does not work.
From what I can tell the correct answer is:
from importlib import reload # python 2.7 does not require this
import X
reload( X )
from X import Y
Test
My test was the following (Python 2.6.5 + bpython 0.9.5.2)
X.py:
def Y():
print "Test 1"
bpython:
>>> from X import Y
>>> print Y()
Test 1
>>> # Edit X.py to say "Test 2"
>>> print Y()
Test 1
>>> reload( X ) # doesn't work because X not imported yet
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'X' is not defined
>>> import X
>>> print Y()
Test 1
>>> print X.Y()
Test 1
>>> reload( X ) # No effect on previous "from" statements
>>> print Y()
Test 1
>>> print X.Y() # first one that indicates refresh
Test 2
>>> from X import Y
>>> print Y()
Test 2
>>> # Finally get what we were after
If Y is a module (and X a package) reload(Y) will be fine -- otherwise, you'll see why good Python style guides (such as my employer's) say to never import anything except a module (this is one out of many great reasons -- yet people still keep importing functions and classes directly, no matter how much I explain that it's not a good idea;-).
from modulename import func
import importlib, sys
importlib.reload(sys.modules['modulename'])
from modulename import func
First off, you shouldn't be using reload at all, if you can avoid it. But let's assume you have your reasons (i.e. debugging inside IDLE).
Reloading the library won't get the names back into the module's namespace. To do this, just reassign the variables:
f = open('zoo.py', 'w')
f.write("snakes = ['viper','anaconda']\n")
f.close()
from zoo import snakes
print snakes
f = open('zoo.py', 'w')
f.write("snakes = ['black-adder','boa constrictor']\n")
f.close()
import zoo
reload(zoo)
snakes = zoo.snakes # the variable 'snakes' is now reloaded
print snakes
You could do this a few other ways. You could automate the process by searching through the local namespace, and reassigning anything that was from the module in question, but I think we are being evil enough.
If you want to do this:
from mymodule import myobject
Do this instead:
import mymodule
myobject=mymodule.myobject
You can now use myobject in the same way as you were planning (without the tiresome unreadable mymodule references everywhere).
If you're working interactively and want to reload myobject from mymodule you now can using:
reload(mymodule)
myobject=mymodule.myobject
If you're working in a jupyter environment, and you already have from module import function can use the magic function, autoreload by
%load_ext autoreload
%autoreload
from module import function
The introduction of the autoreload in IPython is given here.
assuming you used from X import Y, you have two options:
reload(sys.modules['X'])
reload(sys.modules[__name__]) # or explicitly name your module
or
Y=reload(sys.modules['X']).Y
few considerations:
A. if the import scope is not module-wide (e,g: import in a function) - you must use the second version.
B. if Y is imported into X from another module (Z) - you must reload Z, than reload X and than reload your module, even reloading all your modules (e,g: using [ reload(mod) for mod in sys.modules.values() if type(mod) == type(sys) ]) might reload X before reloading Z - and than not refresh the value of Y.
reload() module X,
reload() module importing Y from X.
Note that reloading won't change already created objects bound in other namespaces (even if you follow style guide from Alex).
Just to follow up on AlexMartelli's and Catskul's answers, there are some really simple but nasty cases that appear to confound reload, at least in Python 2.
Suppose I have the following source tree:
- foo
- __init__.py
- bar.py
with the following content:
init.py:
from bar import Bar, Quux
bar.py:
print "Loading bar"
class Bar(object):
#property
def x(self):
return 42
class Quux(Bar):
object_count = 0
def __init__(self):
self.count = self.object_count
self.__class__.object_count += 1
#property
def x(self):
return super(Quux,self).x + 1
def __repr__(self):
return 'Quux[%d, x=%d]' % (self.count, self.x)
This works just fine without using reload:
>>> from foo import Quux
Loading bar
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> Quux()
Quux[2, x=43]
But try to reload and it either has no effect or corrupts things:
>>> import foo
Loading bar
>>> from foo import Quux
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> reload(foo)
<module 'foo' from 'foo\__init__.pyc'>
>>> Quux()
Quux[2, x=43]
>>> from foo import Quux
>>> Quux()
Quux[3, x=43]
>>> reload(foo.bar)
Loading bar
<module 'foo.bar' from 'foo\bar.pyc'>
>>> Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> Quux().count
5
>>> Quux().count
6
>>> Quux = foo.bar.Quux
>>> Quux()
Quux[0, x=43]
>>> foo.Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> foo.Quux().count
8
The only way I could ensure the bar submodule was reloaded was to reload(foo.bar); the only way I access the reloaded Quux class is to reach in and grab it from the reloaded sub module; but the foo module itself kept holding onto the original Quux class object, presumably because it uses from bar import Bar, Quux (rather than import bar followed by Quux = bar.Quux); furthermore the Quux class got out of sync with itself, which is just bizarre.