The binding operator, and what gets bound to what (was: About Modifying Globals)

Chris Angelico rosuav at gmail.com
Fri Dec 5 05:03:04 EST 2014


On Fri, Dec 5, 2014 at 8:53 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Oh, I learned something new: strictly speaking, this is implementation-
> dependent and not guaranteed to work in the future!
>
> def func():
>     global math
>     import math

When would you actually *want* this, though? Given that 'import'
already caches, there's not much point caching globally, and the idea
that a function could cause a module-level import to happen is pretty
weird!

The only scheme I could concoct would be something like this:

def use_foo():
    global useme
    import foo as useme
    # code to initialize foo for our use

def use_bar():
    global useme
    import bar as useme
    # likewise

def do_stuff():
    useme.blah(1,2,3,4)

So, for instance, if you need a JavaScript executor, you might support
several different runtimes, and allow one to be selected like this.
But this would be serious code smell.

ChrisA



More information about the Python-list mailing list