why globals() exits python when quit() is aliased as q - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: why globals() exits python when quit() is aliased as q (/thread-40039.html) |
why globals() exits python when quit() is aliased as q - abc12346 - May-23-2023 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=quitBut 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 $ RE: why globals() exits python when quit() is aliased as q - Larz60+ - May-23-2023 This is a duplicate thread. The other has been (soft) deleted. FYI: Please read: https://python-forum.io/misc.php?action=help&hid=22 RE: why globals() exits python when quit() is aliased as q - deanhystad - May-23-2023 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(). RE: why globals() exits python when quit() is aliased as q - Gribouillis - May-23-2023 Ctrl+d is not much harder to type than q+Return ... RE: why globals() exits python when quit() is aliased as q - Gribouillis - May-23-2023 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 QNow you can print globals() , but if you print vars(__builtins__) , it will exit the interpreter.
|