Skip to content

Commit fdda308

Browse files
committed
Added dataclasses and typing examples
1 parent 1ab946c commit fdda308

File tree

1 file changed

+393
-0
lines changed

1 file changed

+393
-0
lines changed

09_New_in_Python/09_dataclasses.ipynb

+393
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,393 @@
1+
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
4+
"metadata": {
5+
"colab": {
6+
"provenance": [],
7+
"toc_visible": true
8+
},
9+
"kernelspec": {
10+
"name": "python3",
11+
"display_name": "Python 3"
12+
},
13+
"language_info": {
14+
"name": "python"
15+
}
16+
},
17+
"cells": [
18+
{
19+
"cell_type": "markdown",
20+
"source": [
21+
"## **`dataclasses`**"
22+
],
23+
"metadata": {
24+
"id": "XE_IcA4YSc-F"
25+
}
26+
},
27+
{
28+
"cell_type": "code",
29+
"source": [
30+
"from dataclasses import dataclass\n",
31+
"\n",
32+
"@dataclass\n",
33+
"class Person:\n",
34+
" name: str\n",
35+
" age: int\n",
36+
" city: str\n",
37+
"\n",
38+
"# Creating an instance of the Person dataclass\n",
39+
"person = Person(name=\"Alice\", age=30, city=\"New York\")\n",
40+
"\n",
41+
"# Accessing the fields\n",
42+
"print(person.name) # Output: Alice\n",
43+
"print(person.age) # Output: 30\n",
44+
"print(person.city) # Output: New York"
45+
],
46+
"metadata": {
47+
"colab": {
48+
"base_uri": "https://localhost:8080/"
49+
},
50+
"id": "9KpkWmtTCmbd",
51+
"outputId": "07ed2ee3-e954-40f9-f2bf-425ad55b67a7"
52+
},
53+
"execution_count": 1,
54+
"outputs": [
55+
{
56+
"output_type": "stream",
57+
"name": "stdout",
58+
"text": [
59+
"Alice\n",
60+
"30\n",
61+
"New York\n"
62+
]
63+
}
64+
]
65+
},
66+
{
67+
"cell_type": "code",
68+
"source": [
69+
"from dataclasses import dataclass\n",
70+
"\n",
71+
"@dataclass\n",
72+
"class Address:\n",
73+
" street: str\n",
74+
" city: str\n",
75+
" zipcode: str\n",
76+
"\n",
77+
"@dataclass\n",
78+
"class Person:\n",
79+
" name: str\n",
80+
" age: int\n",
81+
" address: Address\n",
82+
"\n",
83+
"# Creating an instance of the Address class\n",
84+
"address1 = Address(street=\"123 Main St\", city=\"New York\", zipcode=\"10001\")\n",
85+
"\n",
86+
"# Creating an instance of the Person class with the Address instance\n",
87+
"person1 = Person(name=\"Alice\", age=30, address=address1)\n",
88+
"\n",
89+
"# Accessing the nested attributes\n",
90+
"print(person1.address.city) # Output: New York"
91+
],
92+
"metadata": {
93+
"colab": {
94+
"base_uri": "https://localhost:8080/"
95+
},
96+
"id": "N1V7ZtvFlsGs",
97+
"outputId": "5aaa41b0-82e4-4037-f80f-3f4f8c7584c5"
98+
},
99+
"execution_count": 2,
100+
"outputs": [
101+
{
102+
"output_type": "stream",
103+
"name": "stdout",
104+
"text": [
105+
"New York\n"
106+
]
107+
}
108+
]
109+
},
110+
{
111+
"cell_type": "code",
112+
"source": [
113+
"from dataclasses import dataclass, field\n",
114+
"\n",
115+
"@dataclass\n",
116+
"class Product:\n",
117+
" name: str\n",
118+
" price: float\n",
119+
" in_stock: bool = True\n",
120+
" tags: list = field(default_factory=list)\n",
121+
"\n",
122+
"# Creating an instance of the Product class\n",
123+
"product1 = Product(name=\"Laptop\", price=999.99)\n",
124+
"\n",
125+
"# Accessing the attributes\n",
126+
"print(product1.name) # Output: Laptop\n",
127+
"print(product1.in_stock) # Output: True\n",
128+
"print(product1.tags) # Output: []\n",
129+
"\n",
130+
"# Adding a tag to the product\n",
131+
"product1.tags.append(\"Electronics\")\n",
132+
"print(product1.tags)"
133+
],
134+
"metadata": {
135+
"colab": {
136+
"base_uri": "https://localhost:8080/"
137+
},
138+
"id": "z1312whblx0i",
139+
"outputId": "700cd896-488a-4627-d111-58d2813ab8dc"
140+
},
141+
"execution_count": 3,
142+
"outputs": [
143+
{
144+
"output_type": "stream",
145+
"name": "stdout",
146+
"text": [
147+
"Laptop\n",
148+
"True\n",
149+
"[]\n",
150+
"['Electronics']\n"
151+
]
152+
}
153+
]
154+
},
155+
{
156+
"cell_type": "markdown",
157+
"source": [
158+
"In this example, the `Person` class is defined as a `dataclass` with three fields: `name`, `age`, and `city`. The `dataclass` decorator automatically generates special methods like `__init__()`and `__repr__()` for the class, making it easier to work with.\n",
159+
"\n",
160+
"- The `__init__` method in Python is a **special method** used to initialize the attributes of an object when it is created. It’s often referred to as a constructor. When you create a new instance of a class, Python automatically calls the `__init__` method to set up the initial state of the object.\n",
161+
"\n",
162+
"- The `__repr__` method in Python is a **special method** used to define the string representation of an object."
163+
],
164+
"metadata": {
165+
"id": "huCxk1dfCuey"
166+
}
167+
},
168+
{
169+
"cell_type": "code",
170+
"source": [
171+
"class Person:\n",
172+
" def __init__(self, name: str, age: int, city: str):\n",
173+
" self.name = name\n",
174+
" self.age = age\n",
175+
" self.city = city\n",
176+
"\n",
177+
" def __repr__(self):\n",
178+
" return f\"Person(name={self.name}, age={self.age}, city={self.city})\"\n",
179+
"\n",
180+
"# Creating an instance of the Person class\n",
181+
"person = Person(name=\"Alice\", age=30, city=\"New York\")\n",
182+
"\n",
183+
"# Accessing the fields\n",
184+
"print(person.name) # Output: Alice\n",
185+
"print(person.age) # Output: 30\n",
186+
"print(person.city) # Output: New York"
187+
],
188+
"metadata": {
189+
"colab": {
190+
"base_uri": "https://localhost:8080/"
191+
},
192+
"id": "GQngSHM6Dl8M",
193+
"outputId": "4605dca3-1aa3-4bed-87f6-74ae7d453501"
194+
},
195+
"execution_count": 4,
196+
"outputs": [
197+
{
198+
"output_type": "stream",
199+
"name": "stdout",
200+
"text": [
201+
"Alice\n",
202+
"30\n",
203+
"New York\n"
204+
]
205+
}
206+
]
207+
},
208+
{
209+
"cell_type": "markdown",
210+
"source": [
211+
"If you don’t use `dataclasses`, you would typically define a class with an `__init__` method to initialize the attributes.\n",
212+
"\n",
213+
"\n",
214+
">The `@dataclass` decorator in Python is used to automatically generate special methods for classes, such as `__init__()`, `__repr__()`, `__eq__()`, and others. **This helps reduce boilerplate code and makes it easier to create classes that are primarily used to store data.**"
215+
],
216+
"metadata": {
217+
"id": "nrEN6XXfDrmu"
218+
}
219+
},
220+
{
221+
"cell_type": "markdown",
222+
"source": [
223+
"## **`typing`**\n",
224+
"\n",
225+
"\n",
226+
"The `from typing import List` statement in Python is used to import the `List` type hint from the `typing` module. This allows you to specify the type of elements that a list should contain, which can be very helpful for code readability and for tools like type checkers and IDEs to provide better support and error checking.\n",
227+
"\n",
228+
"Here’s an example of how it’s used:"
229+
],
230+
"metadata": {
231+
"id": "rqWqyDyvTzpB"
232+
}
233+
},
234+
{
235+
"cell_type": "code",
236+
"source": [
237+
"from typing import List\n",
238+
"\n",
239+
"def sum_of_elements(elements: List[int]) -> int:\n",
240+
" return sum(elements)\n",
241+
"\n",
242+
"numbers = [1, 2, 3, 4, 5]\n",
243+
"print(sum_of_elements(numbers))"
244+
],
245+
"metadata": {
246+
"colab": {
247+
"base_uri": "https://localhost:8080/"
248+
},
249+
"id": "BFLobiRkT1-y",
250+
"outputId": "ba1d8255-440b-4156-ea80-d909490fd764"
251+
},
252+
"execution_count": 5,
253+
"outputs": [
254+
{
255+
"output_type": "stream",
256+
"name": "stdout",
257+
"text": [
258+
"15\n"
259+
]
260+
}
261+
]
262+
},
263+
{
264+
"cell_type": "code",
265+
"source": [
266+
"from typing import Dict\n",
267+
"\n",
268+
"def get_student_grades() -> Dict[str, int]:\n",
269+
" return {\"Alice\": 90, \"Bob\": 85, \"Charlie\": 92}\n",
270+
"\n",
271+
"grades = get_student_grades()\n",
272+
"print(grades)"
273+
],
274+
"metadata": {
275+
"colab": {
276+
"base_uri": "https://localhost:8080/"
277+
},
278+
"id": "SSzIFknblN-6",
279+
"outputId": "ebe04324-e55a-4a25-96ed-8061aafb3120"
280+
},
281+
"execution_count": 6,
282+
"outputs": [
283+
{
284+
"output_type": "stream",
285+
"name": "stdout",
286+
"text": [
287+
"{'Alice': 90, 'Bob': 85, 'Charlie': 92}\n"
288+
]
289+
}
290+
]
291+
},
292+
{
293+
"cell_type": "code",
294+
"source": [
295+
"from typing import Union\n",
296+
"\n",
297+
"def process_data(data: Union[int, str]) -> str:\n",
298+
" if isinstance(data, int):\n",
299+
" return f\"Processed number: {data}\"\n",
300+
" elif isinstance(data, str):\n",
301+
" return f\"Processed string: {data}\"\n",
302+
"\n",
303+
"print(process_data(10)) # Output: Processed number: 10\n",
304+
"print(process_data(\"hello\")) # Output: Processed string: hello\n"
305+
],
306+
"metadata": {
307+
"colab": {
308+
"base_uri": "https://localhost:8080/"
309+
},
310+
"id": "nq_kZmBWlZc6",
311+
"outputId": "37816c45-9070-497f-eb1d-ecaaa3858170"
312+
},
313+
"execution_count": 7,
314+
"outputs": [
315+
{
316+
"output_type": "stream",
317+
"name": "stdout",
318+
"text": [
319+
"Processed number: 10\n",
320+
"Processed string: hello\n"
321+
]
322+
}
323+
]
324+
},
325+
{
326+
"cell_type": "code",
327+
"source": [
328+
"from typing import Optional\n",
329+
"\n",
330+
"def find_user(user_id: int) -> Optional[str]:\n",
331+
" users = {1: \"Alice\", 2: \"Bob\", 3: \"Charlie\"}\n",
332+
" return users.get(user_id)\n",
333+
"\n",
334+
"print(find_user(1)) # Output: Alice\n",
335+
"print(find_user(4)) # Output: None\n"
336+
],
337+
"metadata": {
338+
"colab": {
339+
"base_uri": "https://localhost:8080/"
340+
},
341+
"id": "0CfFra8rlaxr",
342+
"outputId": "c196b561-96dd-4a49-a4f5-3a8e30609135"
343+
},
344+
"execution_count": 8,
345+
"outputs": [
346+
{
347+
"output_type": "stream",
348+
"name": "stdout",
349+
"text": [
350+
"Alice\n",
351+
"None\n"
352+
]
353+
}
354+
]
355+
},
356+
{
357+
"cell_type": "code",
358+
"source": [
359+
"from typing import Callable\n",
360+
"\n",
361+
"def execute_function(func: Callable[[int, int], int], a: int, b: int) -> int:\n",
362+
" return func(a, b)\n",
363+
"\n",
364+
"def add(x: int, y: int) -> int:\n",
365+
" return x + y\n",
366+
"\n",
367+
"def multiply(x: int, y: int) -> int:\n",
368+
" return x * y\n",
369+
"\n",
370+
"print(execute_function(add, 2, 3)) # Output: 5\n",
371+
"print(execute_function(multiply, 2, 3)) # Output: 6"
372+
],
373+
"metadata": {
374+
"colab": {
375+
"base_uri": "https://localhost:8080/"
376+
},
377+
"id": "TzSljUHPlb6h",
378+
"outputId": "b1a35987-7a64-4081-e74f-07aebad6110e"
379+
},
380+
"execution_count": 9,
381+
"outputs": [
382+
{
383+
"output_type": "stream",
384+
"name": "stdout",
385+
"text": [
386+
"5\n",
387+
"6\n"
388+
]
389+
}
390+
]
391+
}
392+
]
393+
}

0 commit comments

Comments
 (0)