globals: a dirty little secret?

Donald Beaudry donb at init.com
Thu Apr 20 10:26:49 EDT 2000


"Michal Wallace (sabren)" <sabren at manifestation.com> wrote,
> 
> 
> Globals have come up a couple times recently.. If someone posted the
> following approach, I missed it...
> 
> 
> ### step 1: globals.py #######################
> 
> import __builtin__
> 
> def setGlobal(key, value):
>    __builtin__.__dict__[key] = value
> 
> __builtin__.setGlobal = setGlobal # makes the above function global

*If* I found that functionality useful, I'd prefer

    def setGlobal(**d):
        __builtin__.__dict__.update(d)

so that it could be called like:

    setGlobal(x=5)

which fits better with my sense of aesthetics.

Sure it works, but what good does it do you?  It only provides
"convenient" read-only access to your globals.  To write a global, you
must use the setGlobal() function.  Instead, consider this module:

    #
    # globals.py
    #

    pass

Yup... that's it.

Now inside your program:

    import globals
    globals.x = 5

    print globals.x

With this approach your intentions become very clear.

--
Donald Beaudry                                     Ab Initio Software Corp.
                                                   201 Spring Street
donb at init.com                                      Lexington, MA 02421
                      ...Will hack for sushi...




More information about the Python-list mailing list