[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to reassign the value of the variable on runtime?

On Fri, Aug 28, 2015 at 4:25 AM, Ivan Evstegneev
<webmailgroups at gmail.com> wrote:
> Can some please (I mean very please) explain me how do I reassign
> "engine_object" and "meta_object" variables,
> so they would store(point to) a new connection objects of my database,
> while other functions still would see those variables as their defaults?
> ****************alchemy_data_export.py**************************************
> engine_object, meta_object = db_existence_check_and_create()
> def db_new_copy():
>         engine_object, meta_object = create_new_db()
> def current_data_export(engine=engine_object, meta=meta_object):
>     ... code goes here ...

First off, there's one easy - almost trivial - change to make: inside
db_new_copy, declare "global engine_object, meta_object" and then it's
able to change the global (module-level) name bindings.

The second part is a little more tricky: how do you specify a default
argument of "whatever is in the global at the time of the call"? The
answer is: You can't. The normal way to do this is with a sentinel;
since it wouldn't make sense to use None as your engine, you can write
it like this:

def current_data_export(engine=None, meta=None):
    if engine is None: engine = engine_object
    if meta is None: meta = meta_object

You lose some of the clarity, but you gain a "lazy link" between the
function default args and the global.

Does that help at all?