python - 查找最近定义的变量
问题描述
有没有办法找出最近在全局命名空间中定义的变量?
最好是通用的 python 解决方案,但在 jupyter notebook 中工作的解决方案也是可以接受的。(我知道使用 接收 cell_output _
,但未打印定义的变量)
解决方案
从 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'
推荐阅读
- ios - 在 UITableView 中滚动时视图被替换
- vba - 循环遍历两个数组以检查值是否匹配,如果不更改值
- mysql - 将逗号分隔的字符串与数字进行比较时,MySQL 的奇怪行为
- asp.net - Razor 将整个模型对象作为选项值从视图到控制器分页
- amazon-ec2 - “Appscale up”卡在“等待头节点初始化”
- macros - 显示“!”的日志 运行 SAS 宏后的感叹号
- mysql - 单个查询中的不同计数
- javascript - 使用 firebase 进行 React JS 映射
- amazon-web-services - 有没有办法记录从 S3 存储桶复制的文件?
- ios - ReactiveSwift 中的 API 请求