Skip to content

Commit e34a7d8

Browse files
committed
init and async functions
0 parents  commit e34a7d8

30 files changed

+916
-0
lines changed

.gitignore

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Python-generated files
2+
__pycache__/
3+
*.py[oc]
4+
build/
5+
dist/
6+
wheels/
7+
*.egg-info
8+
9+
# Virtual environments
10+
.venv
11+
.idea

.python-version

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13

README.md

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 🐍 Python Async Programming Sessions
2+
3+
A repository for exploring **asynchronous programming in Python**. This collection of examples demonstrates various concurrency models, ranging from simple synchronous HTTP requests to advanced async patterns using decorators, futures, and more.
4+
5+
## What is Asynchronous Programming?
6+
7+
Asynchronous programming enables you to write non-blocking, concurrent code using constructs like `async/await` and event loops. It is ideal for I/O-bound tasks and improves the performance of network and parallel operations without relying solely on multi-threading or multi-processing.
8+
9+
## Key Imports & Modules
10+
11+
These examples utilize several Python modules, including:
12+
13+
- **Core Async Tools:** `asyncio`
14+
- **HTTP Clients:** `aiohttp`, `requests`
15+
- **Concurrency:** `threading`, `multiprocessing`
16+
- **Utilities:** `time`, `functools`, `os`
17+
18+
## Examples Included
19+
20+
- **Synchronous Requests:**
21+
Simple HTTP requests using the `requests` library.
22+
23+
- **Threading & Multiprocessing:**
24+
Demonstrations of running tasks concurrently using threads and processes.
25+
26+
- **Asyncio Basics:**
27+
Creating async functions, using `asyncio.sleep`, and managing tasks with the event loop.
28+
29+
- **Advanced Async Techniques:**
30+
Handling timeouts, cancellation, and using custom decorators (e.g., for timing execution).
31+
32+
---
33+
34+
👤 **Author:** Piotr Lipinski
35+
🗓 **Date:** March 2025
36+
💬 **Feedback:** Contributions and suggestions are welcome!

intro/__init__.py

Whitespace-only changes.

intro/example_1.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import requests
2+
3+
response = requests.get("http://www.example.com")
4+
5+
6+
items = response.headers.items()
7+
8+
headers = [f'{key}: header{header}' for key, header in items]
9+
10+
formatted_headers = '\n'.join(headers)
11+
12+
with open('headers.txt', 'w') as file:
13+
file.write(formatted_headers)

intro/example_10.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from asyncio import Future
2+
3+
my_future: Future = Future()
4+
5+
print(f'Is my_future done? {my_future.done()}')
6+
7+
my_future.set_result(42)
8+
9+
print(f'Is my_future done? {my_future.done()}')
10+
print(f'What is the result of my_future? {my_future.result()}')

intro/example_11.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from asyncio import Future
2+
import asyncio
3+
4+
5+
def make_request() -> Future:
6+
future: Future = Future()
7+
asyncio.create_task(set_future_value(future))
8+
return future
9+
10+
11+
async def set_future_value(future: Future) -> None:
12+
await asyncio.sleep(1)
13+
future.set_result(42)
14+
15+
16+
async def main() -> None:
17+
future = make_request()
18+
print(f'Is the future done? {future.done()}')
19+
value = await future
20+
print(f'Is the future done? {future.done()}')
21+
print(value)
22+
23+
24+
asyncio.run(main())

intro/example_12.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
3+
from util import async_timed
4+
5+
6+
@async_timed()
7+
async def delay(delay_second: int) -> int:
8+
print(f'sleeping for {delay_second} seconds')
9+
await asyncio.sleep(delay_second)
10+
print(f'finishing for {delay_second} seconds')
11+
return delay_second
12+
13+
@async_timed()
14+
async def main() -> None:
15+
task_one = asyncio.create_task(delay(2))
16+
task_two = asyncio.create_task(delay(3))
17+
18+
await task_one
19+
await task_two
20+
21+
asyncio.run(main())

intro/example_13.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
from util import async_timed
3+
4+
5+
@async_timed()
6+
async def cpu_bound_work() -> int:
7+
counter = 0
8+
for i in range(100000000):
9+
counter = counter + 1
10+
return counter
11+
12+
13+
@async_timed()
14+
async def main() -> None:
15+
task_one = asyncio.create_task(cpu_bound_work())
16+
task_two = asyncio.create_task(cpu_bound_work())
17+
await task_one
18+
await task_two
19+
20+
21+
asyncio.run(main())

intro/example_14.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import asyncio
2+
from util import async_timed, delay
3+
4+
5+
@async_timed()
6+
async def cpu_bound_work() -> int:
7+
counter = 0
8+
for i in range(100000000):
9+
counter = counter + 1
10+
return counter
11+
12+
13+
@async_timed()
14+
async def main() -> None:
15+
task_one = asyncio.create_task(cpu_bound_work())
16+
task_two = asyncio.create_task(cpu_bound_work())
17+
task_three = asyncio.create_task(delay(4))
18+
await task_one
19+
await task_two
20+
await task_three
21+
22+
23+
asyncio.run(main())

intro/example_15.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
async def coroutine_add_one(number: int) -> int:
2+
return number + 1
3+
4+
5+
def add_one(number: int) -> int:
6+
return number + 1
7+
8+
9+
function_result = add_one(1)
10+
coroutine_result = coroutine_add_one(1)
11+
12+
print(f'Function result is {function_result} and the type is {type(function_result)}')
13+
print(f'Coroutine result is {coroutine_result} and the type is {type(coroutine_result)}')

intro/example_16.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import asyncio
2+
import requests
3+
from util import async_timed
4+
5+
6+
@async_timed()
7+
async def get_example_status() -> int:
8+
return requests.get('https://www.example.com').status_code
9+
10+
11+
@async_timed()
12+
async def main() -> None:
13+
task_1 = asyncio.create_task(get_example_status())
14+
task_2 = asyncio.create_task(get_example_status())
15+
task_3 = asyncio.create_task(get_example_status())
16+
await task_1
17+
await task_2
18+
await task_3
19+
20+
asyncio.run(main())

intro/example_17.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import asyncio
2+
3+
async def main() -> None:
4+
await asyncio.sleep(1)
5+
6+
loop = asyncio.new_event_loop()
7+
8+
try:
9+
loop.run_until_complete(main())
10+
finally:
11+
loop.close()
12+

intro/example_18.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import asyncio
2+
3+
from util import delay
4+
5+
6+
def call_later() -> None:
7+
print("Calling in future")
8+
9+
async def main() -> None:
10+
loop = asyncio.get_running_loop()
11+
loop.call_soon(call_later)
12+
await delay(1)
13+
await delay(2)
14+
15+
asyncio.run(main())

intro/example_2.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import os
2+
import threading
3+
4+
5+
6+
def hello() -> None:
7+
# sleep(3)
8+
print(f'Hello from {threading.current_thread()}')
9+
10+
t1 = threading.Thread(target=hello)
11+
t1.start()
12+
13+
14+
print(f'Python process running with id: {os.getpid()}')
15+
16+
17+
18+
total_threads = threading.active_count()
19+
thread_name = threading.current_thread().name
20+
21+
print(f'Total threads : {total_threads}')
22+
print(f'Current thread name: {thread_name}')
23+
24+
t1.join()

intro/example_3.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import multiprocessing
2+
import os
3+
4+
5+
def hello() -> None:
6+
print(f'Hello from {os.getpid()}')
7+
8+
if __name__ == '__main__':
9+
p1 = multiprocessing.Process(target=hello)
10+
p1.start()
11+
print(f'Hello from {os.getpid()}')
12+
p1.join()
13+
14+
15+
16+

intro/example_4_fib_.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import threading
2+
import time
3+
4+
def print_fib(number: int) -> None:
5+
def fib(n: int) -> int:
6+
if n == 1:
7+
return 1
8+
if n == 2:
9+
return 1
10+
else:
11+
return fib(n - 1) + fib(n - 2)
12+
13+
print(f'fib({number}) = {fib(number)}')
14+
15+
def fibs_no_threading() -> None:
16+
print_fib(40)
17+
print_fib(41)
18+
19+
def fibs_with_threading() -> None:
20+
t1 = threading.Thread(target=print_fib, args=(40,))
21+
t2 = threading.Thread(target=print_fib, args=(41,))
22+
23+
t1.start()
24+
t2.start()
25+
26+
t1.join()
27+
t2.join()
28+
29+
30+
start = time.time()
31+
fibs_with_threading()
32+
# fibs_no_threading()
33+
end = time.time()
34+
35+
print(f'Completed in {end - start} seconds')

intro/example_5.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
async def my_coroutine() -> None:
2+
print('Hello world')
3+
4+
5+
print(my_coroutine())
6+

intro/example_6.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import asyncio
2+
3+
async def delay(delay_second: int) -> int:
4+
print(f'sleeping for {delay_second} seconds')
5+
await asyncio.sleep(delay_second)
6+
print(f'finishing for {delay_second} seconds')
7+
return delay_second
8+
9+
async def hello_every_second() -> None:
10+
for i in range(2):
11+
await asyncio.sleep(1)
12+
print('Running other code while I am waiting')
13+
14+
15+
async def main():
16+
first_delay = asyncio.create_task(delay(3))
17+
second_delay = asyncio.create_task(delay(3))
18+
await hello_every_second()
19+
await first_delay
20+
await second_delay
21+
22+
asyncio.run(main())

intro/example_7.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import asyncio
2+
3+
4+
from util import delay
5+
6+
7+
async def main() -> None:
8+
long_task = asyncio.create_task(delay(10))
9+
10+
seconds_elapsed = 0
11+
12+
while not long_task.done():
13+
print('Task not finished')
14+
await asyncio.sleep(1)
15+
seconds_elapsed += 1
16+
if seconds_elapsed > 5:
17+
long_task.cancel()
18+
19+
try:
20+
await long_task
21+
except asyncio.CancelledError:
22+
print('Cancelled')
23+
24+
25+
asyncio.run(main())
26+

intro/example_8.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import asyncio
2+
3+
4+
from util import delay
5+
6+
7+
async def main() -> None:
8+
long_task = asyncio.create_task(delay(10))
9+
10+
try:
11+
result = await asyncio.wait_for(long_task, timeout=1)
12+
print(result)
13+
except asyncio.TimeoutError:
14+
print("Timed out")
15+
print(long_task.cancelled())
16+
17+
18+
19+
asyncio.run(main())
20+

0 commit comments

Comments
 (0)