Help on scope/namespace

Jp Calderone exarkun at intarweb.us
Sun Feb 2 13:06:04 EST 2003


On Sun, Feb 02, 2003 at 03:48:12AM +0000, Byron Morgan wrote:
> [snip]
> 
> 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 ?

  There's a way, but you don't want to use it.

  The problem you're seeing is that code runs in the scope it was *defined*
in, not the scope it is invoked in.  Functions defined in module Y and
called from module X don't see module X's globals - they see module Y's
globals.  The easiest, least painful, and cleanest way around this is to
somehow make module X's globals into parameters passed to module Y's
functions.  You can do this directly, by simply adding a parameter or two to
each function in Y, or create a class that takes each of the globals as an
__init__ argument, then keeps references to them that the now-member
functions can examine.

  Jp

-- 
A sad spectacle.  If they be inhabited, what a scope for misery 
and folly.  If they be not inhabited, what a waste of space.
                -- Thomas Carlyle, looking at the stars
-- 
 up 48 days, 21:50, 4 users, load average: 0.27, 0.16, 0.06
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030202/b737e398/attachment.sig>


More information about the Python-list mailing list