Say I have this function:
def destroy_all_the_users(a, b, c, d, e, f=2, *g, **h):
i = 2
It seems I can calculate its minimum arity (the minimum amount of arguments I have to give it) like so:
import types
# This doesn't work on some C functions like, say, file.write
def get_minimum_arity(func_alike):
# This might not be a function but a method
if type(func_alike) is types.MethodType:
func_alike = func_alike.im_func
# This might not be a function but a __call__'able
if type(func_alike) is not types.FunctionType:
func_alike = func_alike.__call__
return func_alike.__code__.co_argcount - len(func_alike.__defaults__)
How can I, however, determine the names of those 5 arguments? For destroy_all_the_users
, that would be ('a', 'b', 'c', 'd', 'e')
. Attributes that may look promising aren't (for instance, destroy_all_the_users.__code__.co_varnames
also include g, h, i
) and I don't necessarily have the source code of the function. The output of dis.dis(destroy_all_the_users)
seems similarly unhelpful.
Say for example that I want to check for the file
ness of an arbitrary class that may not even derive from file
. All that you really care about is that this arbitrary class has enough of the same methods (say, write
), which means that at least they should accept the same number of parameters (1, but more optional arguments are not a problem) and the same parameter names (...bad example: it seems that file.write
is special and doesn't allow its mandatory arguments to be passed by keyword)).