Skip to content

Instantly share code, notes, and snippets.

@umireon
Created June 23, 2021 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umireon/9410ee22701bcdff038371e12d660ff0 to your computer and use it in GitHub Desktop.
Save umireon/9410ee22701bcdff038371e12d660ff0 to your computer and use it in GitHub Desktop.
import dis
from dataclasses import dataclass
from typing import TypedDict
@dataclass
class MyDataclass:
field1: str
field2: int
class MyTypedDict:
field1: str
field2: int
def my_dataclass():
a = MyDataclass('a', 0)
a.field1 = 'b'
a.field2 = 1
print(a.field1, a.field2)
def my_typeddict():
a = {'field1': 'a', 'field2': 0}
a['field1'] = 'b'
a['field2'] = 1
print(a['field1'], a['field2'])
my_dataclass()
my_typeddict()
print("============================")
dis.dis(my_dataclass)
print("============================")
dis.dis(my_typeddict)
b 1
b 1
============================
15 0 LOAD_GLOBAL 0 (MyDataclass)
2 LOAD_CONST 1 ('a')
4 LOAD_CONST 2 (0)
6 CALL_FUNCTION 2
8 STORE_FAST 0 (a)
16 10 LOAD_CONST 3 ('b')
12 LOAD_FAST 0 (a)
14 STORE_ATTR 1 (field1)
17 16 LOAD_CONST 4 (1)
18 LOAD_FAST 0 (a)
20 STORE_ATTR 2 (field2)
18 22 LOAD_GLOBAL 3 (print)
24 LOAD_FAST 0 (a)
26 LOAD_ATTR 1 (field1)
28 LOAD_FAST 0 (a)
30 LOAD_ATTR 2 (field2)
32 CALL_FUNCTION 2
34 POP_TOP
36 LOAD_CONST 0 (None)
38 RETURN_VALUE
============================
21 0 LOAD_CONST 1 ('a')
2 LOAD_CONST 2 (0)
4 LOAD_CONST 3 (('field1', 'field2'))
6 BUILD_CONST_KEY_MAP 2
8 STORE_FAST 0 (a)
22 10 LOAD_CONST 4 ('b')
12 LOAD_FAST 0 (a)
14 LOAD_CONST 5 ('field1')
16 STORE_SUBSCR
23 18 LOAD_CONST 6 (1)
20 LOAD_FAST 0 (a)
22 LOAD_CONST 7 ('field2')
24 STORE_SUBSCR
24 26 LOAD_GLOBAL 0 (print)
28 LOAD_FAST 0 (a)
30 LOAD_CONST 5 ('field1')
32 BINARY_SUBSCR
34 LOAD_FAST 0 (a)
36 LOAD_CONST 7 ('field2')
38 BINARY_SUBSCR
40 CALL_FUNCTION 2
42 POP_TOP
44 LOAD_CONST 0 (None)
46 RETURN_VALUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment