[Tutor] function location and importing modules

Daniel Ehrenberg littledanehren at yahoo.com
Thu Jan 15 11:20:22 EST 2004


> I.
> I have a simple login script that I am trying to
> simplify more by
> putting some code into functions.  I'm finding that
> the functions can
> only be called if they are placed BEFORE the call in
> the script.  Is
> this really true?  Is there a different way to do
> it?  It is just that
> it is more aesthetically pleasing to have the main
> function code
> first.

You can have functions or classes refer to things that
don't exist yet, and as long as you don't actually
execute the function until those variables are
initialized, it's ok.

The reason for Python initializing functions when they
are created has to do with its dynamic nature.
Consider the following code:

def hi():
    print 'hi'
hi()
def greeting():
    print 'hello, how are you'
hi = greeting
hi()

That's perfectly legal python code, and it would print
what is expected:

hi
hello, how are you

> 
> II.
> What is the proper way to be able to import custom
> modules.  This is
> for my login script mentioned previously and python
> is not installed
> on the server, just the workstations.  The script
> must live on the
> server and I'd like to keep the support modules on
> yet another server.
> Is it just a question of modifying PYTHONPATH on the
> fly each time the
> script is run?

Unless you need to run the script in a namespace, you
can use execfile(filename) to run a file. If you need
a namespace, you should modify sys.path (not
PYTHONPATH) by appending the directory that the custom
module is in. sys.path is more cross-platform and much
easier to manipulate than PYTHONPATH because it's in a
list.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus



More information about the Tutor mailing list