enforce_signature: allow defined type by name
Over at https://github.com/coala/coala/pull/5690 we have a scenario where we want to check that the first arg is of a certain type, and raise a predicatable exception if it is not.
Sounds perfect for enforce_signature.
However, due to circular dependencies, we can not import and use the type class. We need to use duck typing, or 'is instance checking using obj.__class__.__name__
'
Rather than create a new decorator,
- introduce a special class which cooperates with enforce_signature to provide it the class names which it should check against.
@enforce_signature
def foo(duck : signature_type_by_name('Bear'), bar):
...
where signature_type_by_name
is:
class _SignatureProxy():
def __init__(self, name):
self.name = name
def signature_type_by_name(name):
return _SignatureProxy(name)
def enforce_signature(..):
...
for i, args in enumerate(func_args):
val = invocation_args[i]
if isinstance(arg, _SignatureProxy):
if val.__class__.__name__ == arg.name:
# yay, found it
# possibly cache the class, etc.
else:
...