How to reassign the value of the variable on runtime?

Chris Angelico rosuav at
Sat Aug 29 18:02:04 CEST 2015

On Sun, Aug 30, 2015 at 1:46 AM, Ivan Evstegneev
<webmailgroups at> wrote:
> It looks like, when the module is loaded (imported) for the first time, all
> the functions that are defined within it and using a  global varialbles as
> their defaults, they would keep the first value of this globals.

That's correct. When you define a function, it snapshots the default
values for its arguments; if you say "engine=engine_object", Python
will evaluate the name "engine_object" at the time when the 'def'
statement is executed (which in this case is module load) and save
that as the default value for the argument "engine". Changing the
value of engine_object won't change that.

> So assumed you've already knew about this behavior and suggested to use
> "lazy links". Am I right?

Right. If you use "engine=None", then Python will evaluate the
expression "None", which (what a surprise!) means the special object
None. There's only one such object, and you'll never be replacing it.
Then, whenever the function is called, you say "hey, if this thing's
None, go and grab the one from the global"; and since that happens
when the function's _called_ rather than when it's _defined_, it uses
the value of engine_object at that time.

> Still what is the difference between the way proposed:
> ***************************************************
>>def current_data_export(engine=None, meta=None):
>>    if engine is None: engine = engine_object
>>   if meta is None: meta = meta_object
> ****************************************************
> and the direct use of these globals within the function?
> Like so:
> ******************************************************
> def current_data_export():
>         engine_object.some_method_used
>         meta_object.some_metheod_used
> ******************************************************
>  In both cases the engine and meta objects will be searched in outerscope,
> what is the difference then?

Correct, both will be fetched from the outer scope. The difference is
that you can override them using the first form, by calling the
function with arguments:

current_data_export(some_other_engine, some_other_meta)

which you can't do if you use the globals directly. But both forms do
use the current values of the globals as at when the function is


More information about the Python-list mailing list