forked from UWPCE-PythonCert/ProgrammingInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmangler_dec.py
More file actions
71 lines (55 loc) · 1.5 KB
/
Copy pathmangler_dec.py
File metadata and controls
71 lines (55 loc) · 1.5 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
#!/usr/bin/env python3
"""
class decorator that adds both upper and lower case versions of
class attributes.
Same as the NameMangler metaclass, but with a class decorator instead
Usage example:
@name_mangler
class Foo:
x = 1
f = Foo()
print(f.x)
print(f.X)
"""
def name_mangler(cls):
"""
Class decorator that adds upper and lower case names to the
decorated class
"""
# get the dictionary of class attributes
att_dict = vars(cls)
# create a new dict to hold the attributes
new_attrs = {}
# loop thorough all the class attributes
for name, val in att_dict.items():
# skip all the "dunder" attributes
if not name.startswith("__"):
# Create both upper and lower case versions of all non-dunder names
# They are stored in the new_attrs dict, as you can't
# update the class namespace while looping through it.
new_attrs[name.upper()] = val
new_attrs[name.lower()] = val
# Add the new names to the cls attributes
# you can't directly update the __dict__ -- class __dict__s are not
# writable.
for name, val in new_attrs.items():
setattr(cls, name, val)
return cls
@name_mangler
class Foo:
x = 1
Y = 2
# note that it works for methods, too!
@name_mangler
class Bar:
x = 1
def a_method(self):
print("in a_method")
if __name__ == "__main__":
f = Foo()
print(f.x)
print(f.X)
print(f.y)
print(f.Y)
b = Bar()
b.A_METHOD()