首页 > 解决方案 > 查找最近定义的变量

问题描述

有没有办法找出最近在全局命名空间中定义的变量?

最好是通用的 python 解决方案,但在 jupyter notebook 中工作的解决方案也是可以接受的。(我知道使用 接收 cell_output _,但未打印定义的变量)

标签: pythonjupyter-notebookjupyter-lab

解决方案


从 Python 3.7 开始,字典保持插入键的顺序。因此,最后声明的变量应该是globals().

Python 3.7.6 (default, Jan  8 2020, 13:42:34)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> a = 1
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1}
>>> c = 2
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, 'c': 2}
>>> list(globals().keys())[-1]
'c'

推荐阅读