Getting list of parameter names inside python function
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.
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:
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:
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:
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.
Was this article helpful?