Help on scope/namespace
Erik Max Francis
max at alcyone.com
Sat Feb 1 23:12:25 EST 2003
Byron Morgan wrote:
> I have nearly 100 functions that I'd like to import, rather than
> maintaining
> them in the main script. I tried putting them into their own file, but
> they
> couldn't see the objects (dictionaries & lists) that were loaded from
> the
> first file. So I tried putting them in the same file, but this didn't
> work
> either. So I made a class with all the functions inside, still no go.
Put the functions in a file called something.py, and place the file
somewhere where your Python interpreter can find it (that is, somewhere
in the current directory or in one of the directories in sys.path).
Then type
import something
Access the functions contains in there by
something.thisFunction()
something.thatFunction()
something.theOtherFunction()
and so on.
> Is there some way I can import functions from a file, and have them
> behave
> just as though they are contained in the main script ?
You can use the syntax
from something import *
which will import all (with some qualifiers; you can control which
functions it is by manipulating an __all__ variable, and it won't import
names starting with an underscore) the names in the something module
into the current scope, but this is generally (again, with some
qualifiers; in some cases it's considered idiomatic) not a good idea due
to namespace pollution: When you have lots of interacting modules,
doing this to excess almost guarantees a name collision, and in fact
defeats the purpose of separating everything into modules in the first
place.
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ Conversation is the enemy of good wine and food.
\__/ Alfred Hitchcock
The laws list / http://www.alcyone.com/max/physics/laws/
Laws, rules, principles, effects, paradoxes, etc. in physics.
More information about the Python-list
mailing list