How do I dynamically create a function with the same signature as another function?

I'm busy creating a metaclass that replaces the stub function on the class with a new one with the correct implementation. The original function can use any signature. My problem is that I cannot figure out how to create a new function with the same signature as the old one. How can I do it?

Update

This has nothing to do with the actual question, which is: "How do I dynamically create a function with the same signature as another function?" but I am adding this to show why I cannot use subclasses.

I am trying to implement something like Scala Case Classes in Python. (Does not match the pattern matching only automatically generated properties, eq, hashes, and str methods.)

I need something like this:

>>> class MyCaseClass(): ... __metaclass__ = CaseMetaClass ... def __init__(self, a, b): ... pass >>> instance = MyCaseClass(1, 'x') >>> instance.a 1 >>> instance.b 'x' >>> str(instance) MyCaseClass(1, 'x') 

As far as I can see, there is no way with subclasses.

+4
source share
3 answers

I believe that functools.wraps does not reproduce the original call signature. However, Michele Simionato decorator module :

 import decorator class FooType(type): def __init__(cls,name,bases,clsdict): @decorator.decorator def modify_stub(func, *args,**kw): return func(*args,**kw)+' + new' setattr(cls,'stub',modify_stub(clsdict['stub'])) class Foo(object): __metaclass__=FooType def stub(self,a,b,c): return 'original' foo=Foo() help(foo.stub) # Help on method stub in module __main__: # stub(self, a, b, c) method of __main__.Foo instance print(foo.stub(1,2,3)) # original + new 
+3
source

This can be done using inspect.getargspecs . There even

0
source

use functools.wraps

 >>> from functools import wraps >>> def f(a,b): return a+b >>> @wraps(f) def f2(*args): print(args) return f(*args) >>> f2(2,5) (2, 5) 7 
0
source

All Articles