python __builtins__

Status
Not open for further replies.

DavlinLotze

Ars Scholae Palatinae
830
I'm trying to understand __builtins__ in Python (python3, specifically). (This thread is not about whether it's a good idea to clear the globals() dict. I know that's dumb.)

I used to think they were only accessed through the globals of the current context, but if that were true, the following would result in a NameError:

Code:
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  globals().clear()
...  print("hi")
... 
>>> f()
hi
>>>

Obviously it doesn't. It appears that a reference to __builtins__ is squirrelled away somewhere magical and hidden at the beginning of the function's run. But how far does that extend?

If you look at this example, you can see that __builtins__ seems to be passed on to a completely different scope:

Code:
Python 3.4.0 (default, Jun 19 2015, 14:18:46) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  g_ = g
...  globals().clear()
...  print("hi from f")
...  return g_
... 
>>> def g(): print("hi from g")
... 
>>> f()()
hi from f
hi from g
>>>

Likewise if you call it this way:

Code:
Python 3.4.0 (default, Jun 19 2015, 14:18:46) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  g_ = g
...  globals().clear()
...  print("hi from f")
...  return g_
... 
>>> def g(): print("hi from g")
... 
>>> g = f() ; g()
hi from f
hi from g
>>>

But not if you call it this way:

Code:
Python 3.4.0 (default, Jun 19 2015, 14:18:46) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  g_ = g
...  globals().clear()
...  print("hi from f")
...  return g_
... 
>>> def g(): print("hi from g")
... 
>>> g = f()
hi from f
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in g
NameError: name 'print' is not defined
>>>

o_O Okay, well that's absurd.

One last example indicates that it's squirrelled away using the value for the key "__builtins__" in the function's globals dict, but I have no idea as to how it decides whether it's passed on to other scopes:

Code:
Python 3.4.0 (default, Jun 19 2015, 14:18:46) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def mk_f():
...  globs = {}
...  bi = globs["__builtins__"] = type(__builtins__)("")
...  bi.print = lambda *args: print("f says:", *args)
...  def f():
...   del globs["__builtins__"]
...   print("bye")
...   def g():
...    print("hi from g")
...   return g
...  f = type(f)(f.__code__, globs, closure=f.__closure__)
...  return f
... 
>>> mk_f()()()
f says: bye
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in g
NameError: name 'print' is not defined
>>>


I'd really enjoy an explanation. The documentation I found was exceedingly sparse on the subject of __builtins__.
 

Apteris

Ars Tribunus Angusticlavius
9,589
Subscriptor
Your functions only work once. :p (Disclaimer: not a Python expert by any means, corrections welcome.)

What you're seeing is the effect of a function already on the call stack being called. So:

[url=http:/civis/viewtopic.php?p=29400435#p29400435:21lnong3 said:
DavlinLotze[/url]":21lnong3]
Code:
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  globals().clear()
...  print("hi")
... 
>>> f()
hi
>>>
After you've called globals().clear(), the next function on the call stack will be print("hi"), which will duly get called. If you try to call f() a second time, just below the first, you immediately get "NameError: name 'f' is not defined".

The same thing happens with examples 2 and 3: a second call to f()() and g = f(); g(), respectively, will raise a not defined error. In example 3, in fact, you won't be able to call g() again either, because:

Code:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     g_ = g
...     globals().clear()
...     print("hi from f")
...     return g_
...
>>> def g(): print("hi from g")
...
>>> g = f() ; g()
hi from f
hi from g

>>> g # note that g is still defined
<function g at 0x007335D0>

>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in g
NameError: name 'print' is not defined

>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'f' is not defined

In example 4, when you bind g to the return value of function f, you also call function f, thus clearing the globals dictionary.

Where example 5 is concerned, I have no idea what mk_f()()() is supposed to do--because of my lack of understanding of Python closures, not because of your code--but I'm sure the same issue is at play. Running it in script mode rather than in interactive mode yields this:

Code:
> python3 Davlin5.py
f says: bye
Traceback (most recent call last):
  File "Davlin5.py", line 19, in <module>
    mk_f()()()
TypeError: 'NoneType' object is not callable

I figured out the above by pasting your code into PyCharm and stepping through it with the debugger. You should do the same. Note, you will get slightly different behaviour in some examples, because you will be running in script mode (is that the right term?) rather than interactive mode. Tip: instead of globals().clear() do
Code:
myGlobals = globals()
globals().clear()
so that it's obvious when the global dictionary gets cleared.
 

Apteris

Ars Tribunus Angusticlavius
9,589
Subscriptor
Hmm, after having written the above it dawns on me that I'm not really answering your question.

My best guess is that the Python interpreter itself has a reference to __builtins__ and that's how it's able to call print("hi"). I tested this just now:

Code:
>>> globals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

>>> globals().clear()

>>> globals()
{'__builtins__': {'TypeError': <class 'TypeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'hasattr': <built-in function hasattr>, 'ord': <built-in function ord>, 'ImportError': <class 'ImportError'>, 'frozenset': <class 'frozenset'>, 'NotImplemented': NotImplemented, 'list': <class 'list'>, 'callable': <built-in function callable>, 'GeneratorExit': <class 'GeneratorExit'>, 'OSError': <class 'OSError'>, 'True': True, 'TabError': <class 'TabError'>, 'min': <built-in function min>, 'object': <class 'object'>, 'any': <built-in function any>, 'Warning': <class 'Warning'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'SyntaxError': <class 'SyntaxError'>, 'round': <built-in function round>, 'BaseException': <class 'BaseException'>, 'ImportWarning': <class 'ImportWarning'>, 'sorted': <built-in function sorted>, 'vars': <built-in function vars>, 'filter': <class 'filter'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'NotImplementedError': <class 'NotImplementedError'>, 'pow': <built-in function pow>, '__name__': 'builtins', 'int': <class 'int'>, 'BytesWarning': <class 'BytesWarning'>, 'super': <class 'super'>, 'oct': <built-in function oct>, 'divmod': <built-in function divmod>, 'repr': <built-in function repr>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'delattr': <built-in function delattr>, 'StopIteration': <class 'StopIteration'>, 'MemoryError': <class 'MemoryError'>, 'RuntimeError': <class 'RuntimeError'>, '__debug__': True, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'KeyError': <class 'KeyError'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'bytearray': <class 'bytearray'>, 'map': <class 'map'>, 'enumerate': <class 'enumerate'>, 'FutureWarning': <class 'FutureWarning'>, '__package__': '', 'SystemExit': <class 'SystemExit'>, 'AssertionError': <class 'AssertionError'>, 'Exception': <class 'Exception'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'set': <class 'set'>, 'open': <built-in function open>, 'setattr': <built-in function setattr>, 'SystemError': <class 'SystemError'>, 'BufferError': <class 'BufferError'>, '__build_class__': <built-in function __build_class__>, 'issubclass': <built-in function issubclass>, 'format': <built-in function format>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ascii': <built-in function ascii>, 'bytes': <class 'bytes'>, 'IndentationError': <class 'IndentationError'>, 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'next': <built-in function next>, 'sum': <built-in function sum>, 'locals': <built-in function locals>, 'exec': <built-in function exec>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'all': <built-in function all>, 'TimeoutError': <class 'TimeoutError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'False': False, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'staticmethod': <class 'staticmethod'>, 'classmethod': <class 'classmethod'>, 'UnicodeError': <class 'UnicodeError'>, 'compile': <built-in function compile>, 'BlockingIOError': <class 'BlockingIOError'>, 'zip': <class 'zip'>, 'help': Type help() for interactive help, or help(object) for help about object., 'eval': <built-in function eval>, 'print': <built-in function print>, 'complex': <class 'complex'>, 'UserWarning': <class 'UserWarning'>, 'None': None, 'abs': <built-in function abs>, 'str': <class 'str'>, 'ResourceWarning': <class 'ResourceWarning'>, 'globals': <built-in function globals>, 'EnvironmentError': <class 'OSError'>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'WindowsError': <class 'OSError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, '_': None, 'ProcessLookupError': <class 'ProcessLookupError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'chr': <built-in function chr>, 'type': <class 'type'>, 'ChildProcessError': <class 'ChildProcessError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'bin': <built-in function bin>, 'float': <class 'float'>, 'memoryview': <class 'memoryview'>, 'hash': <built-in function hash>, 'bool': <class 'bool'>, 'Ellipsis': Ellipsis, 'OverflowError': <class 'OverflowError'>, 'property': <class 'property'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'tuple': <class 'tuple'>, 'ReferenceError': <class 'ReferenceError'>, 'id': <built-in function id>, 'license': Type license() to see the full license text, 'NameError': <class 'NameError'>, 'FileExistsError': <class 'FileExistsError'>, 'ConnectionError': <class 'ConnectionError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'ArithmeticError': <class 'ArithmeticError'>, 'max': <built-in function max>, 'ValueError': <class 'ValueError'>, 'input': <built-in function input>, 'reversed': <class 'reversed'>, 'len': <built-in function len>, '__import__': <built-in function __import__>, 'EOFError': <class 'EOFError'>, 'copyright': Copyright (c) 2001-2015 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'exit': Use exit() or Ctrl-Z plus Return to exit, 'slice': <class 'slice'>, 'dict': <class 'dict'>, 'isinstance': <built-in function isinstance>, 'IndexError': <class 'IndexError'>, 'getattr': <built-in function getattr>, 'dir': <built-in function dir>, 'IOError': <class 'OSError'>, 'range': <class 'range'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'hex': <built-in function hex>, 'iter': <built-in function iter>, 'LookupError': <class 'LookupError'>}}
Subsequent calls to globals().clear() return the same (big) dictionary.

So it appears as though you can't get rid of the python interpreter reference to __builtins__ with globals().clear(). But you can if you do

Code:
__builtins__ = None

Then nothing will work. Except your function, which will still print "hi". Hmm... :/
 

DavlinLotze

Ars Scholae Palatinae
830
[url=http:/civis/viewtopic.php?p=29411173#p29411173:195opgzh said:
Apteris[/url]":195opgzh]Your functions only work once. :p
Yeah, I know that, but I'm surprised when some of them work even once.

[url=http:/civis/viewtopic.php?p=29411173#p29411173:195opgzh said:
Apteris[/url]":195opgzh]What you're seeing is the effect of a function already on the call stack being called. ... After you've called globals().clear(), the next function on the call stack will be print("hi"), which will duly get called.
But python isn't like a static compiled language where "print" is defined at compile time. It's not even fixed at the beginning of function execution, but has to be looked up from somewhere every time it's referenced. Using globals().clear() is obviously effective in that I can't run f a second time (f deletes itself, and everything else), but even if we hadn't lost 'f', we'd still be unable to run it a second time without error because __builtins__ is no longer in the globals() dict:
Code:
Python 3.4.0 (default, Jun 19 2015, 14:18:46) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...  from builtins import globals, __import__
...  globals()["__builtins__"] = {"globals":globals, "__import__":__import__}
...  print("hi")
... 
>>> f()
hi
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
NameError: name 'print' is not defined
>>>

So where did Python get "print" from the first time?

[url=http:/civis/viewtopic.php?p=29411173#p29411173:195opgzh said:
Apteris[/url]":195opgzh]
Code:
>>> g = f() ; g()
hi from f
hi from g

>>> g # note that g is still defined
<function g at 0x007335D0>

It's as expected that 'g' should be defined, because it was set based on the result of f(), so it's set after the globals().clear(). 'g' is the ONLY thing in globals(). What I didn't expect was for g() to run the first time without error. (or 'f' either, as above). But it's made increasingly perplexing when
Code:
>>> g = f() ; g()
and
Code:
>>> g = f()
>>> g()
actually produce different results.

[url=http:/civis/viewtopic.php?p=29411173#p29411173:195opgzh said:
Apteris[/url]":195opgzh]Where example 5 is concerned, I have no idea what mk_f()()() is supposed to do
Now with comments:
Davlin5.py
Code:
def mk_f():
    # Create an empty dict to hold globals for what will be 'f'.
    globs = {}
    # Add to it an empty module under the key "__builtins__".
    # ('type(__builtins__)' is a shortcut to access types.ModuleType)
    bi = globs["__builtins__"] = type(__builtins__)("")
    # Add to the __builtins__ module stand-in a new definition for 'print'.
    # (The only reason we use a new definition instead of the old is to prove where 'print' is being accessed from.)
    bi.print = lambda *args: print("f says:", *args)
    # Create the function 'f'.
    def f():
        del globs["__builtins__"]
        print("bye")
        def g():
            print("hi from g")
        return g
    # Replace 'f' with a copy that has its __globals__ switched out.
    # (You have to remake 'f' because f.__globals__ is a readonly attribute.)
    # ('type(f)' is just a shortcut to access types.FunctionType)
    # (Because 'f' has a closure on 'globs', you must copy f's closure as well, not just its code.)
    f = type(f)(f.__code__, globs, closure=f.__closure__)
    return f

mk_f()()()

But of course we could have done it without the closure. (I'm a bit of a closure freak lately.) And you don't even need to make "__builtins__" be an actual module, since Python will also accept it as a dict, as I did in the example above.

Davlin5_b.py
Code:
def f():
 globals().clear()
 print("Hi from f")
 def g():
  print("Hi from g")
 return g

globs = {}
globs["__builtins__"] = {"print": (lambda *args: print("Special print:", *args)),
                         "globals": (lambda : globs)}

from types import FunctionType
f = FunctionType(f.__code__, globs)

f()()

Code:
$ python3 Davlin5_b.py 
Special print: Hi from f
Traceback (most recent call last):
  File "Davlin5_b.py", line 15, in <module>
    f()()
  File "Davlin5_b.py", line 5, in g
    print("Hi from g")
NameError: name 'print' is not defined

'f' still gets the mysterious ability to find 'print', but this time it isn't carried over to 'g' also.

[url=http:/civis/viewtopic.php?p=29411173#p29411173:195opgzh said:
Apteris[/url]":195opgzh]Running it in script mode rather than in interactive mode yields this:

Code:
> python3 Davlin5.py
f says: bye
Traceback (most recent call last):
  File "Davlin5.py", line 19, in <module>
    mk_f()()()
TypeError: 'NoneType' object is not callable

Are you sure you didn't forget the "return f" or "return g" statements? That would make easy sense of that message. Then again, whatever you're doing with PyCharm isn't like running it for real, as your next post made clear. The fact that your globals().clear() still could be followed up by a call to globals(), and also that the contents of globals() is now just __builtins__ indicates to me that PyCharm is doing some kind of magic with "exec()". If you give exec() a globals dict with no "__builtins__" key, Python adds it to your dict before running your code. [1]
 
Status
Not open for further replies.