-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes_module.py
More file actions
47 lines (34 loc) · 1.33 KB
/
types_module.py
File metadata and controls
47 lines (34 loc) · 1.33 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
from types import new_class
print("Provides utility function to dynamically create new types.")
print("\n**************Create a class object dynamically**************")
def callback(class_namespace):
print(class_namespace)
class_namespace['var1'] = 'var1_value'
class BaseMeta(type):
def __new__(cls, name, bases, body, some_arg):
print(f"received some_args={some_arg}")
return super().__new__(cls, name, bases, body)
# kwds : class keyword arguments, These meta-arguments are useful when configuring meta-classes.
ClassA = new_class('ClassA', (object,), {'metaclass': BaseMeta, 'some_arg': 'value'}, callback)
print(ClassA.var1)
print("\n***********************A read-only dict************************")
from types import MappingProxyType
data = {'a': 1, 'b': 2}
read_only = MappingProxyType(data)
print(read_only)
try:
read_only['a'] = 3
except TypeError:
print("can't modify read only")
# read_only is actually a view of the underlying dict(data), and is not an independent object.
data['a'] = 3
data['c'] = 4
print(read_only)
print("\n***********************Class allowing you to set, change and delete attributes.************************")
from types import SimpleNamespace
dict_data = {'c': 3, 'd': 4}
data = SimpleNamespace(a=1, b=2, **dict_data)
print(data)
data.e = 5
print(data)
print("data.c=", data.c)