-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunvert.py
More file actions
86 lines (62 loc) · 1.96 KB
/
Copy pathfunvert.py
File metadata and controls
86 lines (62 loc) · 1.96 KB
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
77
78
79
80
81
82
83
84
85
86
# funvert.py
# A hack to enable calling functions as if they were methods
#
# Author: Dustin King (cathodion@gmail.com)
# Grown from this tweet by Zygmunt Zając:
# https://twitter.com/zygmuntzajac/status/685161914117296128
import inspect
def stackFrameContext(depth):
context = {}
# depth + 1 because 0 is the context of the calling function
frame = inspect.stack()[depth + 1].frame
# add global and local variables from the appropriate context
context.update(frame.f_globals)
context.update(frame.f_locals)
return context
class Funverted:
def __init__(self, obj):
self._obj=obj
def __getattr__(self, name):
try:
return getattr(self._obj, name)
except AttributeError:
globprop = stackFrameContext(1).get(name, None)
if callable(globprop):
return lambda *args, **kwargs: funvert(globprop(self._obj, *args, **kwargs))
else:
raise
def __str__(self):
return str(self._obj)
def __add__(self, rhs):
return self._obj + rhs
def __radd__(self, lhs):
return lhs + self._obj
def __sub__(self, rhs):
return self._obj - rhs
def __rsub__(self, lhs):
return lhs - self._obj
def __mul__(self, rhs):
return self._obj * rhs
def __rmul__(self, lhs):
return lhs * self._obj
def __truediv__(self, rhs):
return self._obj / rhs
def __rtruediv__(self, lhs):
return lhs / self._obj
def __floordiv__(self, rhs):
return self._obj // rhs
def __rfloordiv__(self, lhs):
return lhs // self._obj
def __mod__(self, rhs):
return self._obj % rhs
def __rmod__(self, lhs):
return lhs % self._obj
def funvert(obj):
if isinstance(obj, Funverted):
return obj
else:
return Funverted(obj)
if __name__ == '__main__':
from test_funvert import TestFunvert
import unittest
unittest.main()