简体   繁体   中英

Why to directly modifying __dict__ would return undefined result?

I'm reading the book 'Beginning Python'. In which it mentions:

In general, you should not modify the dictionary returned by vars because, according to the official Python documentation, the result is undefined. In other words, you might not get the result you're after.

I'm confused here.

As vars() get the __dict__ of the specified object. And all the variable in that scope are based on that __dict__ . How could it be so called undefined when modify it?

eg I did this:

>>> x = 0
>>> vars()['x'] += 2
>>> x
>>> 2

Won't this x keep the value of 2 in that scope until someone changed the value of x?

So, what does result is undefined mean here?

As the documentation states :

Without an argument, vars() acts like locals() .

Switching to locals , then:

Note : The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Note the "may not" ; undefined means exactly that, there isn't an exact definition for what should happen. In other words, it's not guaranteed and you shouldn't write code that relies on it (either way).

Maybe the documentation does answer your question:

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a dictproxy to prevent direct dictionary updates).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM