Explain Codes LogoExplain Codes Logo

Getting list of parameter names inside python function

python
functions
best-practices
python-2
Nikita BarsukovbyNikita Barsukov·Oct 17, 2024
TLDR

Use the built-in inspect module to fetch parameter names from a Python function efficiently. The inspect.signature() function is your ticket to access the function's signature. Use dictionary comprehension to extract the names.

import inspect def example_function(param1, param2, kwarg1="default"): pass param_names = [name for name, _ in inspect.signature(example_function).parameters.items()] print(param_names) # ['param1', 'param2', 'kwarg1']

This [name for name, _ in ...parameters.items()] expression goes Indiana Jones on your function and pulls out the parameter names.

Go inspect-less

Wanna bid farewell to inspect? You've still got choices! You can fetch parameter names tapping into a function's __code__ attribute, revealing the secrets locked within:

def example_function(param1, param2, kwarg1='default'): pass param_names = example_function.__code__.co_varnames[:example_function.__code__.co_argcount] print(param_names) # ('param1', 'param2')

For the Indiana Jones of Python 2.5 or older versions, replace your whip __code__ with func_code and swap the fedora __defaults__ with func_defaults.

Grappling with defaults

Don't let default values catch you off-guard! With __defaults__ and the magical power of dictionary comprehension, you can crack this mystery too:

def example_function(param1, param2='two', kwarg1='default'): pass default_values = dict(zip(example_function.__code__.co_varnames[example_function.__code__.co_argcount-len(example_function.__defaults__):], example_function.__defaults__)) print(default_values) # {'param2': 'two', 'kwarg1': 'default'}

Inside approach

What if you need parameter names during function execution? Well, it's locals().keys() to the rescue but remember to grab these at the beginning of the function:

def example_function(param1, param2, kwarg1='default'): params = locals().keys() # QUICK, grab the keys before locals() floods with more variables! param_list = list(params) # rest of the function print(param_list) # ['param1', 'param2', 'kwarg1'] example_function(1, 2)

Don't delay your copy of locals(). The longer you wait, you might accidentally collect local variables, and we ain't collecting Pokémon here.

Niche scenarios and peculiarities

Dynamic functions

Facing dynamic functions, the ones crafted with types.FunctionType or shapeshifters decorated by decorators? Well, inspect isn't a problem chicken. It elegantly handles such scenarios.

Object methods

For instance methods, remember 'self' is the uninvited guest everyone expects. If you're strictly looking for method's own arguments, you might want to del self.

Type annotations

Python's function signatures are like a buffet, they even serve type annotations. If this is a dish you'd like to try, inspect.signature() will serve it for you, perfect for your static analysis tools or custom logic that gets tickled by types.