Python Forum

Full Version: why globals() exits python when quit() is aliased as q
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was trying to set up my python so that typing 'q' or 'quit' (instead of 'quit()') will exit the python interpreter, by doing:
type(quit).__repr__ = type(quit).__call__
q=quit
But then I noticed that if I do 'globals()', it will exit the python. Can anybody tell me why this happens? Thanks!

abc12@kc-lenovo@~
26 $ python
Python 3.9.10 (main, Jan 20 2022, 22:28:26)
[GCC 11.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
Could not open PYTHONSTARTUP
FileNotFoundError: [Errno 2] No such file or directory: '/home/mobaxterm/kdrive/misc/dot.pythonrc.py'
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> type(quit).__repr__ = type(quit).__call__
>>> q=quit
>>> globals()

abc12@kc-lenovo@~
27 $
This is a duplicate thread. The other has been (soft) deleted.
FYI: Please read: https://python-forum.io/misc.php?action=help&hid=22
You remapped quit.__repr__() to call quit(). Then you assign a variable (q) to reference quit. When you type globals() it prints q: q.__repr__(), but __repr__() now does quit() instead of returning a string. Boom! I mean, that is why typing "q" works, why wouldn't you expect the same thing for globals().
Ctrl+d is not much harder to type than q+Return ...
You could insert a q object in __builtins__ instead of __globals__
# startup.py
class Q:
    def __repr__(self):
        self()

    def __call__(self):
        quit()

    def __str__(self):
        return f'<{type(self).__module__}.{type(self).__name__} object at {hex(id(self))}>'

__builtins__.q = Q()
del Q
Now you can print globals(), but if you print vars(__builtins__), it will exit the interpreter.

Output:
λ PYTHONSTARTUP=paillasse/pf/startup.py python Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> print(q) <__main__.Q object at 0x7f0b751f1b10> >>> q λ