Skip to content

Instantly share code, notes, and snippets.

@aaronasterling
Created January 30, 2011 03:55
Show Gist options
  • Save aaronasterling/802506 to your computer and use it in GitHub Desktop.
Save aaronasterling/802506 to your computer and use it in GitHub Desktop.
Checks argument sequence and mapping to make sure it's acceptable to call a given function with them. By request.
import types
ARGS_FLAG = 4
KWARGS_FLAG = 8
def valid(f, args, kwargs):
def dummy():
pass
dummy_code = dummy.__code__
real_code = f.__code__
args_flag = real_code.co_flags & ARGS_FLAG
kwargs_flag = real_code.co_flags & KWARGS_FLAG
# help(types.CodeType) for details
test_code = types.CodeType(real_code.co_argcount,
real_code.co_kwonlyargcount,
real_code.co_nlocals,
dummy_code.co_stacksize,
args_flag | kwargs_flag,
dummy_code.co_code,
dummy_code.co_consts,
dummy_code.co_names,
real_code.co_varnames,
"<test>", "", 0, b"", ())
# help(types.FunctionType) for details
test_func = types.FunctionType(test_code, {}, "test", f.__defaults__)
try:
test_func(*args, **kwargs)
except TypeError:
return False
else:
return True
def x(a, b, c): pass
def y(a, b=1, c=2): pass
def z(a=1, b=2, c=3): pass
print(valid(x, ("hello", "goodbye", "what?"), {})) # => True
print(valid(x, ("hello", "goodbye"), {})) # => False
print(valid(y, ("hello", "goodbye", "what?"), {})) # => True
print(valid(y, (), {"a": "hello", "b": "goodbye", "c": "what"})) #=> True
print(valid(y, ("hello", "goodbye"), {"c": "what?"})) #=> True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment