简体   繁体   English

如何获取python中function中定义的所有局部变量?

[英]How to get all the local variables defined inside the function in python?

Is there any way to print all the local variables without printing them expilictly?有没有办法打印所有局部变量而不显式打印它们?

def some_function(a,b):
    name='mike'
    city='new york'

    #here print all the local variables inside this function?

That would be the locals() built-in function那将是locals()内置 function

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}

You can filter out the builtins with a list comprehension:您可以使用列表理解过滤掉内置函数:

>>> [_ for _ in locals() if not (_.startswith('__') and _.endswith('__'))]
['x']

If you just want variable names you can use dir() as well:如果你只想要变量名,你也可以使用 dir() :

def some_function(a,b):
    name='Mike'
    city='New York'

    #here print all the local variables inside this function?
    print(dir())
some_function()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM