Skip to content

Commit 583ec6a

Browse files
committed
ch02
1 parent ff85709 commit 583ec6a

File tree

17 files changed

+952
-0
lines changed

17 files changed

+952
-0
lines changed

ch02/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Chapter 2 data files
2+
====================
3+
4+
The files in this folder are not supposed to work if run.
5+
They serve as source for the book chapters, and to provide a
6+
quick copy/paste tool for whoever would need their content.

ch02/bytearray.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# bytearray.py
2+
3+
4+
>>> bytearray() # empty bytearray object
5+
bytearray(b'')
6+
>>> bytearray(10) # zero-filled instance with given length
7+
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
8+
>>> bytearray(range(5)) # bytearray from iterable of integers
9+
bytearray(b'\x00\x01\x02\x03\x04')
10+
>>> name = bytearray(b'Lina') #A - bytearray from bytes
11+
>>> name.replace(b'L', b'l')
12+
bytearray(b'lina')
13+
>>> name.endswith(b'na')
14+
True
15+
>>> name.upper()
16+
bytearray(b'LINA')
17+
>>> name.count(b'L')
18+
1

ch02/chainmap.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# chainmap.py
2+
3+
4+
>>> from collections import ChainMap
5+
>>> default_connection = {'host': 'localhost', 'port': 4567}
6+
>>> connection = {'port': 5678}
7+
>>> conn = ChainMap(connection, default_connection) # map creation
8+
>>> conn['port'] # port is found in the first dictionary
9+
5678
10+
>>> conn['host'] # host is fetched from the second dictionary
11+
'localhost'
12+
>>> conn.maps # we can see the mapping objects
13+
[{'port': 5678}, {'host': 'localhost', 'port': 4567}]
14+
>>> conn['host'] = 'packtpub.com' # let's add host
15+
>>> conn.maps
16+
[{'port': 5678, 'host': 'packtpub.com'},
17+
{'host': 'localhost', 'port': 4567}]
18+
>>> del conn['port'] # let's remove the port information
19+
>>> conn.maps
20+
[{'host': 'packtpub.com'}, {'host': 'localhost', 'port': 4567}]
21+
>>> conn['port'] # now port is fetched from the second dictionary
22+
4567
23+
>>> dict(conn) # easy to merge and convert to regular dictionary
24+
{'host': 'packtpub.com', 'port': 4567}

ch02/dateandtime.py

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
2+
# imports
3+
>>> from datetime import date, datetime, timedelta, timezone
4+
>>> import time
5+
>>> import calendar as cal
6+
>>> from zoneinfo import ZoneInfo
7+
8+
9+
# date
10+
>>> today = date.today()
11+
>>> today
12+
datetime.date(2021, 3, 28)
13+
>>> today.ctime()
14+
'Sun Mar 28 00:00:00 2021'
15+
>>> today.isoformat()
16+
'2021-03-28'
17+
>>> today.weekday()
18+
6
19+
>>> cal.day_name[today.weekday()]
20+
'Sunday'
21+
>>> today.day, today.month, today.year
22+
(28, 3, 2021)
23+
>>> today.timetuple()
24+
time.struct_time(
25+
tm_year=2021, tm_mon=3, tm_mday=28,
26+
tm_hour=0, tm_min=0, tm_sec=0,
27+
tm_wday=6, tm_yday=87, tm_isdst=-1
28+
)
29+
30+
# time
31+
>>> time.ctime()
32+
'Sun Mar 28 15:23:17 2021'
33+
>>> time.daylight
34+
1
35+
>>> time.gmtime()
36+
time.struct_time(
37+
tm_year=2021, tm_mon=3, tm_mday=28,
38+
tm_hour=14, tm_min=23, tm_sec=34,
39+
tm_wday=6, tm_yday=87, tm_isdst=0
40+
)
41+
>>> time.gmtime(0)
42+
time.struct_time(
43+
tm_year=1970, tm_mon=1, tm_mday=1,
44+
tm_hour=0, tm_min=0, tm_sec=0,
45+
tm_wday=3, tm_yday=1, tm_isdst=0
46+
)
47+
>>> time.localtime()
48+
time.struct_time(
49+
tm_year=2021, tm_mon=3, tm_mday=28,
50+
tm_hour=15, tm_min=23, tm_sec=50,
51+
tm_wday=6, tm_yday=87, tm_isdst=1
52+
)
53+
>>> time.time()
54+
1616941458.149149
55+
56+
57+
# datetime, timezones and tiemdeltas
58+
>>> now = datetime.now()
59+
>>> utcnow = datetime.utcnow()
60+
>>> now
61+
datetime.datetime(2021, 3, 28, 15, 25, 16, 258274)
62+
>>> utcnow
63+
datetime.datetime(2021, 3, 28, 14, 25, 22, 918195)
64+
>>> now.date()
65+
datetime.date(2021, 3, 28)
66+
>>> now.day, now.month, now.year
67+
(28, 3, 2021)
68+
>>> now.date() == date.today()
69+
True
70+
>>> now.time()
71+
datetime.time(15, 25, 16, 258274)
72+
>>> now.hour, now.minute, now.second, now.microsecond
73+
(15, 25, 16, 258274)
74+
>>> now.ctime()
75+
'Sun Mar 28 15:25:16 2021'
76+
>>> now.isoformat()
77+
'2021-03-28T15:25:16.258274'
78+
>>> now.timetuple()
79+
time.struct_time(
80+
tm_year=2021, tm_mon=3, tm_mday=28,
81+
tm_hour=15, tm_min=25, tm_sec=16,
82+
tm_wday=6, tm_yday=87, tm_isdst=-1
83+
)
84+
>>> now.tzinfo
85+
>>> utcnow.tzinfo
86+
>>> now.weekday()
87+
6
88+
>>> f_bday = datetime(
89+
1975, 12, 29, 12, 50, tzinfo=ZoneInfo('Europe/Rome')
90+
)
91+
>>> h_bday = datetime(
92+
1981, 10, 7, 15, 30, 50, tzinfo=timezone(timedelta(hours=2))
93+
)
94+
>>> diff = h_bday - f_bday
95+
>>> type(diff)
96+
<class 'datetime.timedelta'>
97+
>>> diff.days
98+
2109
99+
>>> diff.total_seconds()
100+
182223650.0
101+
>>> today + timedelta(days=49)
102+
datetime.date(2021, 5, 16)
103+
>>> now + timedelta(weeks=7)
104+
datetime.datetime(2021, 5, 16, 15, 25, 16, 258274)
105+
106+
107+
# parsing (stdlib)
108+
>>> datetime.fromisoformat('1977-11-24T19:30:13+01:00')
109+
datetime.datetime(
110+
1977, 11, 24, 19, 30, 13,
111+
tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))
112+
)
113+
114+
>>> datetime.fromtimestamp(time.time())
115+
datetime.datetime(2021, 3, 28, 15, 42, 2, 142696)
116+
117+
>>> datetime.now()
118+
datetime.datetime(2021, 3, 28, 15, 42, 1, 120094)
119+
120+
121+
# arrow small demo
122+
>>> import arrow
123+
>>> arrow.utcnow()
124+
<Arrow [2021-03-28T14:43:20.017213+00:00]>
125+
>>> arrow.now()
126+
<Arrow [2021-03-28T15:43:39.370099+01:00]>
127+
128+
>>> local = arrow.now('Europe/Rome')
129+
>>> local
130+
<Arrow [2021-03-28T16:59:14.093960+02:00]>
131+
>>> local.to('utc')
132+
<Arrow [2021-03-28T14:59:14.093960+00:00]>
133+
>>> local.to('Europe/Moscow')
134+
<Arrow [2021-03-28T17:59:14.093960+03:00]>
135+
>>> local.to('Asia/Tokyo')
136+
<Arrow [2021-03-28T23:59:14.093960+09:00]>
137+
>>> local.datetime
138+
datetime.datetime(
139+
2021, 3, 28, 16, 59, 14, 93960,
140+
tzinfo=tzfile('/usr/share/zoneinfo/Europe/Rome')
141+
)
142+
>>> local.isoformat()
143+
'2021-03-28T16:59:14.093960+02:00'

ch02/defaultdict.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# defaultdict.py
2+
3+
4+
>>> d = {}
5+
>>> d['age'] = d.get('age', 0) + 1 # age not there, we get 0 + 1
6+
>>> d
7+
{'age': 1}
8+
>>> d = {'age': 39}
9+
>>> d['age'] = d.get('age', 0) + 1 # age is there, we get 40
10+
>>> d
11+
{'age': 40}
12+
13+
14+
>>> from collections import defaultdict
15+
>>> dd = defaultdict(int) # int is the default type (0 the value)
16+
>>> dd['age'] += 1 # short for dd['age'] = dd['age'] + 1
17+
>>> dd
18+
defaultdict(<class 'int'>, {'age': 1}) # 1, as expected

ch02/dicts.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# dicts.py
2+
3+
4+
>>> a = dict(A=1, Z=-1)
5+
>>> b = {'A': 1, 'Z': -1}
6+
>>> c = dict(zip(['A', 'Z'], [1, -1]))
7+
>>> d = dict([('A', 1), ('Z', -1)])
8+
>>> e = dict({'Z': -1, 'A': 1})
9+
>>> a == b == c == d == e # are they all the same?
10+
True # They are indeed
11+
12+
13+
# zip
14+
>>> list(zip(['h', 'e', 'l', 'l', 'o'], [1, 2, 3, 4, 5]))
15+
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
16+
>>> list(zip('hello', range(1, 6))) # equivalent, more pythonic
17+
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
18+
19+
20+
# basic
21+
>>> d = {}
22+
>>> d['a'] = 1 # let's set a couple of (key, value) pairs
23+
>>> d['b'] = 2
24+
>>> len(d) # how many pairs?
25+
2
26+
>>> d['a'] # what is the value of 'a'?
27+
1
28+
>>> d # how does `d` look now?
29+
{'a': 1, 'b': 2}
30+
>>> del d['a'] # let's remove `a`
31+
>>> d
32+
{'b': 2}
33+
>>> d['c'] = 3 # let's add 'c': 3
34+
>>> 'c' in d # membership is checked against the keys
35+
True
36+
>>> 3 in d # not the values
37+
False
38+
>>> 'e' in d
39+
False
40+
>>> d.clear() # let's clean everything from this dictionary
41+
>>> d
42+
{}
43+
44+
45+
46+
# views
47+
>>> d = dict(zip('hello', range(5)))
48+
>>> d
49+
{'h': 0, 'e': 1, 'l': 3, 'o': 4}
50+
>>> d.keys()
51+
dict_keys(['h', 'e', 'l', 'o'])
52+
>>> d.values()
53+
dict_values([0, 1, 3, 4])
54+
>>> d.items()
55+
dict_items([('h', 0), ('e', 1), ('l', 3), ('o', 4)])
56+
>>> 3 in d.values()
57+
True
58+
>>> ('o', 4) in d.items()
59+
True
60+
61+
62+
# other methods
63+
>>> d
64+
{'h': 0, 'e': 1, 'l': 3, 'o': 4}
65+
>>> d.popitem() # removes a random item (useful in algorithms)
66+
('o', 4)
67+
>>> d
68+
{'h': 0, 'e': 1, 'l': 3}
69+
>>> d.pop('l') # remove item with key `l`
70+
3
71+
>>> d.pop('not-a-key') # remove a key not in dictionary: KeyError
72+
Traceback (most recent call last):
73+
File "<stdin>", line 1, in <module>
74+
KeyError: 'not-a-key'
75+
>>> d.pop('not-a-key', 'default-value') # with a default value?
76+
'default-value' # we get the default value
77+
>>> d.update({'another': 'value'}) # we can update dict this way
78+
>>> d.update(a=13) # or this way (like a function call)
79+
>>> d
80+
{'h': 0, 'e': 1, 'another': 'value', 'a': 13}
81+
>>> d.get('a') # same as d['a'] but if key is missing no KeyError
82+
13
83+
>>> d.get('a', 177) # default value used if key is missing
84+
13
85+
>>> d.get('b', 177) # like in this case
86+
177
87+
>>> d.get('b') # key is not there, so None is returned
88+
89+
90+
# setdefault
91+
>>> d = {}
92+
>>> d.setdefault('a', 1) # 'a' is missing, we get default value
93+
1
94+
>>> d
95+
{'a': 1} # also, the key/value pair ('a', 1) has now been added
96+
>>> d.setdefault('a', 5) # let's try to override the value
97+
1
98+
>>> d
99+
{'a': 1} # no override, as expected
100+
101+
102+
# setdefault example
103+
>>> d = {}
104+
>>> d.setdefault('a', {}).setdefault('b', []).append(1)
105+
>>> d
106+
{'a': {'b': [1]}}
107+
108+
109+
# union
110+
>>> d = {'a': 'A', 'b': 'B'}
111+
>>> e = {'b': 8, 'c': 'C'}
112+
>>> d | e
113+
{'a': 'A', 'b': 8, 'c': 'C'}
114+
>>> e | d
115+
{'b': 'B', 'c': 'C', 'a': 'A'}
116+
>>> {**d, **e}
117+
{'a': 'A', 'b': 8, 'c': 'C'}
118+
>>> {**e, **d}
119+
{'b': 'B', 'c': 'C', 'a': 'A'}
120+
121+
>>> d |= e
122+
>>> d
123+
{'a': 'A', 'b': 8, 'c': 'C'}

ch02/enum.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
>>> GREEN = 1
2+
>>> YELLOW = 2
3+
>>> RED = 4
4+
>>> TRAFFIC_LIGHTS = (GREEN, YELLOW, RED)
5+
>>> # or with a dict
6+
>>> traffic_lights = {'GREEN': 1, 'YELLOW': 2, 'RED': 4}
7+
8+
9+
10+
# using enum
11+
>>> from enum import Enum
12+
>>> class TrafficLight(Enum):
13+
... GREEN = 1
14+
... YELLOW = 2
15+
... RED = 4
16+
...
17+
>>> TrafficLight.GREEN
18+
<TrafficLight.GREEN: 1>
19+
>>> TrafficLight.GREEN.name
20+
'GREEN'
21+
>>> TrafficLight.GREEN.value
22+
1
23+
>>> TrafficLight(1)
24+
<TrafficLight.GREEN: 1>
25+
>>> TrafficLight(4)
26+
<TrafficLight.RED: 4>

0 commit comments

Comments
 (0)