Why recreate __builtins __. Does dict affect the creation of new dictionary objects?

A classmate asked about rewriting the built-in dict class, and after some push I became even more vague.

Take the inline dict. I can assign this variable:

>>> dict=5 >>> dict 5 

Now I have lost access to the dict (will it be a shader, like in C ++ or is it different?), But I still have access to the class using the built-in .dict. But I can rewrite this as well:

 >>> __builtins__.dict = 6 >>> __builtins__.dict 6 

But even this does not violate the class itself:

 >>> stillDict = {'key': 'value'} >>> stillDict {'key': 'value'} 

So why is the class still β€œworking” after I shadowed it? How does the interpreter know that I am making the dictionary with this purpose, and how is the dictionary created because it really does not require __builtins__.dict ?

change Taking this a little further, from the answer of Simeon, who says this, because I create a literal dictionary ...

before overwriting, I can do this:

 >>> a = dict() >>> a.items <built-in method items of dict object at 0x0000000002C97C08> 

after overwriting the dict and __builtins__.dict , I can do this:

 >>> b = {} >>> b.items <built-in method items of dict object at 0x000000000288FC88> 

Which leads to the following ... Both of them are still "dict objects", is this a dict class, just using the constructor to create a dict object? Why do I still have access to inline methods when I shadowed the class?

+7
built-in
source share
1 answer

{'key': 'value'} is a dictionary literal, so it continues to have behavior when creating a dictionary. Python does not need to look for what dict means - it skips this step and directly generates bytecode to build the dictionary:

 >>> def f(): {'a': 3} >>> import dis >>> dis.dis(f) 1 0 BUILD_MAP 1 3 LOAD_CONST 1 (3) 6 LOAD_CONST 2 ('a') 9 STORE_MAP 10 POP_TOP 11 LOAD_CONST 0 (None) 14 RETURN_VALUE 

In byte code, it continues to use BUILD_MAP , as before (i.e. it builds a map / dictionary based on the code you wrote).

The value of dict has changed as you mentioned.


As for the next question: you did not obscure the class / type of the dictionary - you only changed the meaning of what dict means. You cannot delete a dictionary, and Python creates it using a dictionary literal (for example, {} ).

Once you have an object of type dict , you have access to its methods (for example, items() ) - you just built it using the syntax (which you cannot influence), and not the dict() call (which you can influence).

+4
source share

All Articles