Skip to content

Commit e2e3cc9

Browse files
authored
Merge branch 'master' into python-with-statement
2 parents fb67fa2 + cfba954 commit e2e3cc9

File tree

87 files changed

+1750
-38
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+1750
-38
lines changed

debug-python-errors/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Debug Common Python Errors
2+
3+
This folder provides the code examples for the Real Python tutorial [How to Debug Common Python Errors](https://realpython.com/debug-python-errors/).

debug-python-errors/cat.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cat = "Siamese"
2+
3+
print(cat)

debug-python-errors/fruit.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def capitalize_fruit_names(fruits):
2+
capitalized_fruit_names = []
3+
cleaned = [fruit if isinstance(fruit, str) else "" for fruit in fruits]
4+
5+
for fruit in cleaned:
6+
capitalized_fruit_names.append(fruit.capitalize())
7+
8+
return capitalized_fruit_names
9+
10+
11+
if __name__ == "__main__":
12+
print(capitalize_fruit_names(["apple", "BANANA", "cherry", "maNgo"]))

debug-python-errors/palindromes.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def find_palindromes(text):
2+
# Split sentence into words
3+
words = text.split()
4+
5+
# Remove punctuation and convert to lowercase
6+
normalized_words = [
7+
"".join(filter(str.isalnum, word)).lower() for word in words
8+
]
9+
10+
# Check for palindromes
11+
return [word for word in normalized_words if word == word[::-1]]
12+
13+
14+
if __name__ == "__main__":
15+
print(
16+
find_palindromes("Dad plays many solos at noon, and sees a racecar.")
17+
)

debug-python-errors/test_fruit.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import unittest
2+
3+
from fruit import capitalize_fruit_names
4+
5+
6+
class TestFruit(unittest.TestCase):
7+
def test_empty_list(self):
8+
"""with empty list"""
9+
self.assertEqual(capitalize_fruit_names([]), [])
10+
11+
def test_lowercase(self):
12+
"""with lowercase strings"""
13+
self.assertEqual(
14+
capitalize_fruit_names(["apple", "banana", "cherry"]),
15+
["Apple", "Banana", "Cherry"],
16+
)
17+
18+
def test_uppercase(self):
19+
"""with uppercase strings"""
20+
self.assertEqual(
21+
capitalize_fruit_names(["APPLE", "BANANA", "CHERRY"]),
22+
["Apple", "Banana", "Cherry"],
23+
)
24+
25+
def test_mixed_case(self):
26+
"""with mixed case strings"""
27+
self.assertEqual(
28+
capitalize_fruit_names(["mAnGo", "grApE"]),
29+
["Mango", "Grape"],
30+
)
31+
32+
def test_non_string_element(self):
33+
"""with a mix of integer and string elements"""
34+
self.assertEqual(
35+
capitalize_fruit_names([123, "banana"]),
36+
["", "Banana"],
37+
)
38+
39+
40+
if __name__ == "__main__":
41+
unittest.main()

python-asyncio/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python's `asyncio`: A Hands-On Walkthrough
2+
3+
This folder provides the code examples for the Real Python tutorial [Python's `asyncio`: A Hands-On Walkthrough](https://realpython.com/async-io-python/).

python-asyncio/as_completed.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import asyncio
2+
import time
3+
4+
5+
async def main():
6+
task1 = asyncio.create_task(coro([10, 5, 2]))
7+
task2 = asyncio.create_task(coro([3, 2, 1]))
8+
print("Start:", time.strftime("%X"))
9+
for task in asyncio.as_completed([task1, task2]):
10+
result = await task
11+
print(f'result: {result} completed at {time.strftime("%X")}')
12+
print("End:", time.strftime("%X"))
13+
print(f"Both tasks done: {all((task1.done(), task2.done()))}")
14+
15+
16+
async def coro(numbers):
17+
await asyncio.sleep(min(numbers))
18+
return list(reversed(numbers))
19+
20+
21+
if __name__ == "__main__":
22+
asyncio.run(main())

python-asyncio/chained.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import asyncio
2+
import random
3+
import time
4+
5+
6+
async def main():
7+
user_ids = [1, 2, 3]
8+
start = time.perf_counter()
9+
await asyncio.gather(
10+
*(get_user_with_posts(user_id) for user_id in user_ids)
11+
)
12+
end = time.perf_counter()
13+
print(f"\n==> Total time: {end - start:.2f} seconds")
14+
15+
16+
async def get_user_with_posts(user_id):
17+
user = await fetch_user(user_id)
18+
await fetch_posts(user)
19+
20+
21+
async def fetch_user(user_id):
22+
delay = random.uniform(0.5, 2.0)
23+
print(f"User coro: fetching user by {user_id=}...")
24+
await asyncio.sleep(delay)
25+
user = {"id": user_id, "name": f"User{user_id}"}
26+
print(f"User coro: fetched user with {user_id=} (done in {delay:.1f}s).")
27+
return user
28+
29+
30+
async def fetch_posts(user):
31+
delay = random.uniform(0.5, 2.0)
32+
print(f"Post coro: retrieving posts for {user['name']}...")
33+
await asyncio.sleep(delay)
34+
posts = [f"Post {i} by {user['name']}" for i in range(1, 3)]
35+
print(
36+
f"Post coro: got {len(posts)} posts by {user['name']}"
37+
f" (done in {delay:.1f}s):"
38+
)
39+
for post in posts:
40+
print(f" - {post}")
41+
42+
43+
if __name__ == "__main__":
44+
random.seed(444)
45+
asyncio.run(main())

python-asyncio/countasync.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import asyncio
2+
3+
4+
async def main():
5+
await asyncio.gather(count(), count(), count())
6+
7+
8+
async def count():
9+
print("One")
10+
await asyncio.sleep(1)
11+
print("Two")
12+
await asyncio.sleep(1)
13+
14+
15+
if __name__ == "__main__":
16+
import time
17+
18+
start = time.perf_counter()
19+
asyncio.run(main())
20+
elapsed = time.perf_counter() - start
21+
print(f"{__file__} executed in {elapsed:0.2f} seconds.")

python-asyncio/countsync.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import time
2+
3+
4+
def main():
5+
for _ in range(3):
6+
count()
7+
8+
9+
def count():
10+
print("One")
11+
time.sleep(1)
12+
print("Two")
13+
time.sleep(1)
14+
15+
16+
if __name__ == "__main__":
17+
start = time.perf_counter()
18+
main()
19+
elapsed = time.perf_counter() - start
20+
print(f"{__file__} executed in {elapsed:0.2f} seconds.")

0 commit comments

Comments
 (0)