How to get all variable and method names used in script

前端 未结 4 1049
攒了一身酷
攒了一身酷 2020-12-25 08:54

It can be weird but I am looking for a way to get automatically all variables and method within a python script.

For example,

a = 1
b = 2
c = 3
myLis         


        
4条回答
  •  囚心锁ツ
    2020-12-25 09:24

    You can use globals() function to get all the global names in your module, and since python has some global names by default like __builtins__ you can escape them :

    Since globals() return a dictionary contains the names and the values and builtin names have a format like __builtins__ you can filter them:

    >>> print([var for var in globals().keys() if '__' not in var])
    ['someMethod', 'c', 'b', 'a', 'myList']
    

    But note that it won't give you the local names inside the function like something. For that aim you can see inspect module https://docs.python.org/3/library/inspect.html#inspect.getmembers

提交回复
热议问题