有没有办法打印所有局部变量而不显式打印它们?
def some_function(a,b):
name='mike'
city='new york'
#here print all the local variables inside this function?
最佳答案
那就是locals()内置函数
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> x = 5
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 5}
您可以使用列表理解过滤掉内置函数:
>>> [_ for _ in locals() if not (_.startswith('__') and _.endswith('__'))]
['x']
关于python - 如何获取python中函数内部定义的所有局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65364296/