Python Advanced (2023-09-25 - 2023-09-27)

JSON

[1]:
user = {
    'id': 1,
    'firstname': 'Joerg',
    'lastname': 'Faschingbauer',
}
[2]:
user
[2]:
{'id': 1, 'firstname': 'Joerg', 'lastname': 'Faschingbauer'}
[3]:
type(user)
[3]:
dict
[4]:
import json
[5]:
data_to_send = json.dumps(user)
[7]:
type(data_to_send)
[7]:
str
[8]:
print(data_to_send)
{"id": 1, "firstname": "Joerg", "lastname": "Faschingbauer"}
[9]:
repr(data_to_send)
[9]:
'\'{"id": 1, "firstname": "Joerg", "lastname": "Faschingbauer"}\''

Now data_to_send is sent over a tcp connection, and received into a variable data_received

[10]:
data_received = data_to_send
[12]:
type(data_received)
[12]:
str
[13]:
user_received = json.loads(data_received)
[15]:
user_received
[15]:
{'id': 1, 'firstname': 'Joerg', 'lastname': 'Faschingbauer'}

Equality vs. Identity

[16]:
d1 = {
    'id': 1,
    'firstname': 'Joerg',
}
[17]:
d2 = {
    'id': 1,
    'firstname': 'Joerg',
}
[18]:
d1 == d2
[18]:
True
[19]:
d1 is d2
[19]:
False
[20]:
id(d1)
[20]:
140048588115008
[21]:
id(d2)
[21]:
140048588341376
[22]:
id(d1) == id(d2)
[22]:
False

Functions Are Objects

[23]:
def add(a, b):
    return a + b
[24]:
add(1, 2)
[24]:
3
[25]:
summe = add
[26]:
summe(1,2)
[26]:
3
[ ]: