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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 5 07:26:57 EST 2014


Chris Angelico wrote:

> 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!

That's one way of dealing with circular imports. That way the problematic
import is deferred until the function is called, which hopefully is after
both modules have finished initialising their global names. And by making
the imported name a global, you don't have to bother writing "import math"
in every single function. You just need to ensure your initialisation
function is called before doing any real work.

I'm not saying that this is an ideal solution, but there are no ideal
solutions to circular imports. 


> 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)

Oooh! That's nice too!


> 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.

No more than any other global variable. Just because something is unusual
doesn't make it harmful. If you have globals (constants, or variables), you
might put their initialisation code into a function:

def init():
    global x, y, z
    x = some_calculation(arg1)
    y = another_calculation(arg2)
    z = yet_a_third_calculation(arg3)


import is just a special case of a particular calculation.



-- 
Steven




More information about the Python-list mailing list