-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSignature and parameters
76 lines (58 loc) · 2.08 KB
/
Signature and parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
## New feature of python 3 in inspect module.
>>> _fields = ['name','shares','price']
>>> from inspect import Parameter, Signature
>>> parms = [ Parameter(fname, Parameter.POSITIONAL_OR_KEYWORD) for fname in _fields]
>>> parms
[<Parameter "name">, <Parameter "shares">, <Parameter "price">]
>>> sig = Signature(parms)
>>> print(sig)
(name, shares, price)
Binding the signature to arguments.
>>> def foo(*args,**kwargs):
... bound = sig.bind(*args,**kwargs)
... for name,val in bound.arguments.items():
... print(name,val)
...
...
...
>>> foo(1,2,3)
name 1
shares 2
price 3
## Also keyword arguments are working.
>>> foo(1,2,price=3)
name 1
shares 2
price 3
Ex 1 : Taking fields from class and values at instance creation time.
class Structure:
_fields = []
''' fields will take a list from class attributes '''
def __init__(self,*args):
''' args will take parameters during instance initialization '''
if len(args) != self._fields:
raise TypeError('Wrong args')
for name,value in zip(self._fields, args):
''' setting attribute by taking fields and instance initialization values '''
setattr(self,name,value)
class Students(Structure):
''' Inherited class '''
_fields = ['name','rollnumber','class']
class Teacher(Structure):
_fields = ['name','salary']
## Problem with above approach, it doesn't care about the number of arguments and we can't pass key word arguments.
## Solution is to use signature in parent class to get rid of these issues.
from inspect import Parameter, Signature
def make_signature(names):
return Signature(Parameter(name, Parameter.POSITIONAL_OR_KEYWORD) for name in names)
class Structure:
__signature__ = make_signature([])
def __init__(self, *args, **kwargs):
bound = self.__signature__.bind(*args,**kwargs)
for name,val in bound.arguments.items():
setattr(self,name,val)
class Students(Structure):
''' Inherited class '''
__signature__ = make_signature(['name','rollnumber','class'])
class Teacher(Structure):
__signature__ = make_signature(['name','salary'])