Python handles globals badly.

Ian Kelly ian.g.kelly at gmail.com
Fri Sep 4 15:52:22 EDT 2015


On Fri, Sep 4, 2015 at 1:48 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Fri, Sep 4, 2015 at 1:11 PM,  <tdev at freenet.de> wrote:
>> 6- "include" script statement (extending namespace to another script, like PHP)
>
> def include(filename):
>     exec(open(filename).read())

Sorry, that doesn't work because it takes locals from the include
function. You probably need something more like this:

def include(filename, globals):
    exec(open(filename).read(), globals)

To be called like:

include("foo.py", globals())

If you want to get fancy you could probably have include inspect the
stack to pull the globals from the parent stack frame instead of
explicitly passing them in.



More information about the Python-list mailing list