0% found this document useful (0 votes)
18 views1 page

Importing Objects From Modules Into The Main Namespace: Python Scientific Lecture Notes, Release 2012.3 (Euroscipy 2012)

The document discusses Python module loading and reuse. It shows how to import specific functions from a module into the main namespace. It also demonstrates that modifying an imported module will not update the cached version unless reloaded. The document further explains that code in a file is only executed when run as the main file and not when imported, using the __name__ == '__main__' check.

Uploaded by

claudyane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

Importing Objects From Modules Into The Main Namespace: Python Scientific Lecture Notes, Release 2012.3 (Euroscipy 2012)

The document discusses Python module loading and reuse. It shows how to import specific functions from a module into the main namespace. It also demonstrates that modifying an imported module will not update the cached version unless reloaded. The document further explains that code in a file is only executed when run as the main file and not when imported, using the __name__ == '__main__' check.

Uploaded by

claudyane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Scientific lecture notes, Release 2012.

3 (EuroScipy 2012)

In [8]: demo.
demo.__builtins__ demo.__init__ demo.__str__
demo.__class__ demo.__name__ demo.__subclasshook__
demo.__delattr__ demo.__new__ demo.c
demo.__dict__ demo.__package__ demo.d
demo.__doc__ demo.__reduce__ demo.print_a
demo.__file__ demo.__reduce_ex__ demo.print_b
demo.__format__ demo.__repr__ demo.py
demo.__getattribute__ demo.__setattr__ demo.pyc
demo.__hash__ demo.__sizeof__

Importing objects from modules into the main namespace


In [9]: from demo import print_a, print_b

In [10]: whos
Variable Type Data/Info
--------------------------------
demo module <module ’demo’ from ’demo.py’>
print_a function <function print_a at 0xb7421534>
print_b function <function print_b at 0xb74214c4>

In [11]: print_a()
a

Warning: Module caching


Modules are cached: if you modify demo.py and re-import it in the old session, you will get the
old one.
Solution:

In [10]: reload(demo)

2.6.4 ‘__main__’ and module loading

File demo2.py:
import sys

def print_a():
"Prints a."
print ’a’

print sys.argv

if __name__ == ’__main__’:
print_a()

Importing it:
In [11]: import demo2
b

In [12]: import demo2

Running it:
In [13]: %run demo2
b
a

2.6. Reusing code: scripts and modules 28

You might also like