Which of the following is the most concise and Pythonic way to create a list containing the squares of numbers from 0 to 4 (i.e., [0, 1, 4, 9, 16])?
Anonymous Quiz
0%
[x**2 for x in range(5)]
0%
squares = [] for x in range(5): squares.append(x**2)
0%
list(map(lambda x: x**2, range(5)))
0%
[x*x for x in [0, 1, 2, 3, 4]]
Here's your Telegram post for Day 25: Unit Testing!
---
π Day 25: Master Unit Testing in Python! π
Ever wondered how to ensure your code works perfectly every time? π€ Today, we dive into Unit Testing β a crucial practice for writing robust and bug-free applications. We'll use Python's built-in `unittest` module to create and run tests for our functions. Get ready to build confidence in your code! πͺ Let's make our programs reliable! β¨
First, create a file named `calculator.py`:
```python
# calculator.py
def add(a, b):
"""Adds two numbers and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a + b
def subtract(a, b):
"""Subtracts b from a and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a - b
```
Now, create a file named `test_calculator.py` in the same directory:
```python
# test_calculator.py
import unittest
from calculator import add, subtract
class TestCalculator(unittest.TestCase):
def test_add(self):
"""Test the add function with various valid inputs."""
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(0, 0), 0)
self.assertAlmostEqual(add(0.1, 0.2), 0.3)
def test_subtract(self):
"""Test the subtract function with various valid inputs."""
self.assertEqual(subtract(5, 3), 2)
self.assertEqual(subtract(3, 5), -2)
self.assertEqual(subtract(0, 0), 0)
self.assertEqual(subtract(-1, -1), 0)
self.assertEqual(subtract(10, 0), 10)
def test_add_type_error(self):
"""Test add function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
add(1, "2")
with self.assertRaises(TypeError):
add("a", 2)
with self.assertRaises(TypeError):
add(None, 5)
def test_subtract_type_error(self):
"""Test subtract function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
subtract(1, "2")
with self.assertRaises(TypeError):
subtract("a", 2)
if __name__ == '__main__':
unittest.main()
```
To run the tests, navigate to the directory containing these files in your terminal and execute:
`python -m unittest test_calculator.py`
Output example:
```
...
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
```
π‘ **Your Challenge:**
Modify `calculator.py` to include a `multiply(a, b)` function. Don't forget to add type checking! Then, add a new test method `test_multiply` within `TestCalculator` in `test_calculator.py` to thoroughly test your new function with both valid and invalid inputs! Share your solution in the comments! π
---
---
π Day 25: Master Unit Testing in Python! π
Ever wondered how to ensure your code works perfectly every time? π€ Today, we dive into Unit Testing β a crucial practice for writing robust and bug-free applications. We'll use Python's built-in `unittest` module to create and run tests for our functions. Get ready to build confidence in your code! πͺ Let's make our programs reliable! β¨
First, create a file named `calculator.py`:
```python
# calculator.py
def add(a, b):
"""Adds two numbers and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a + b
def subtract(a, b):
"""Subtracts b from a and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a - b
```
Now, create a file named `test_calculator.py` in the same directory:
```python
# test_calculator.py
import unittest
from calculator import add, subtract
class TestCalculator(unittest.TestCase):
def test_add(self):
"""Test the add function with various valid inputs."""
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(0, 0), 0)
self.assertAlmostEqual(add(0.1, 0.2), 0.3)
def test_subtract(self):
"""Test the subtract function with various valid inputs."""
self.assertEqual(subtract(5, 3), 2)
self.assertEqual(subtract(3, 5), -2)
self.assertEqual(subtract(0, 0), 0)
self.assertEqual(subtract(-1, -1), 0)
self.assertEqual(subtract(10, 0), 10)
def test_add_type_error(self):
"""Test add function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
add(1, "2")
with self.assertRaises(TypeError):
add("a", 2)
with self.assertRaises(TypeError):
add(None, 5)
def test_subtract_type_error(self):
"""Test subtract function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
subtract(1, "2")
with self.assertRaises(TypeError):
subtract("a", 2)
if __name__ == '__main__':
unittest.main()
```
To run the tests, navigate to the directory containing these files in your terminal and execute:
`python -m unittest test_calculator.py`
Output example:
```
...
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
```
π‘ **Your Challenge:**
Modify `calculator.py` to include a `multiply(a, b)` function. Don't forget to add type checking! Then, add a new test method `test_multiply` within `TestCalculator` in `test_calculator.py` to thoroughly test your new function with both valid and invalid inputs! Share your solution in the comments! π
---
What is the primary purpose of unit testing in Python using the `unittest` module?
Anonymous Quiz
0%
To test individual components or functions of a software application in isolation.
0%
To test the entire application's functionality from a user's perspective.
0%
To measure the performance and speed of an application.
0%
To deploy the application to a production server.
π **Day 26: Basic Web Scraping with Beautiful Soup** π
Today, we unlock the power of collecting data directly from websites! πΈοΈ Web scraping is a valuable skill, and Python's `BeautifulSoup` library makes it incredibly easy. We'll learn how to parse HTML content and extract specific information like titles, paragraphs, or links. Get ready to dive into the web's structure and pull out the data you need! π»β¨
```python
import requests
from bs4 import BeautifulSoup
# For this example, let's use a simple local HTML string.
# In a real scenario, you'd use requests.get('URL').text
html_doc = """
<html>
<head>
<title>Learning Beautiful Soup</title>
</head>
<body>
<h1>Web Scraping Fundamentals</h1>
<p class="intro">Beautiful Soup helps parse HTML and XML documents.</p>
<a href="https://www.python.org">Python Official Website</a>
<p>Another paragraph.</p>
</body>
</html>
"""
# Create a BeautifulSoup object
soup = BeautifulSoup(html_doc, 'html.parser')
# 1. Get the title of the page
page_title = soup.title.string
print(f"Page Title: {page_title}")
# 2. Find the first h1 tag
h1_tag = soup.find('h1')
print(f"H1 Content: {h1_tag.text}")
# 3. Find a paragraph with a specific class
intro_paragraph = soup.find('p', class_='intro')
print(f"Intro Paragraph: {intro_paragraph.text}")
# 4. Find the first link (a tag)
first_link = soup.find('a')
print(f"First Link Text: {first_link.text}")
print(f"First Link URL: {first_link['href']}")
```
Output example:
```
Page Title: Learning Beautiful Soup
H1 Content: Web Scraping Fundamentals
Intro Paragraph: Beautiful Soup helps parse HTML and XML documents.
First Link Text: Python Official Website
First Link URL: https://www.python.org
```
### Small Challenge π
Try to find *all* the `<p>` tags in the `html_doc` string using `soup.find_all('p')` and print their text content! Can you also extract the `href` attribute from the `<a>` tag using `first_link.get('href')`?
---
Today, we unlock the power of collecting data directly from websites! πΈοΈ Web scraping is a valuable skill, and Python's `BeautifulSoup` library makes it incredibly easy. We'll learn how to parse HTML content and extract specific information like titles, paragraphs, or links. Get ready to dive into the web's structure and pull out the data you need! π»β¨
```python
import requests
from bs4 import BeautifulSoup
# For this example, let's use a simple local HTML string.
# In a real scenario, you'd use requests.get('URL').text
html_doc = """
<html>
<head>
<title>Learning Beautiful Soup</title>
</head>
<body>
<h1>Web Scraping Fundamentals</h1>
<p class="intro">Beautiful Soup helps parse HTML and XML documents.</p>
<a href="https://www.python.org">Python Official Website</a>
<p>Another paragraph.</p>
</body>
</html>
"""
# Create a BeautifulSoup object
soup = BeautifulSoup(html_doc, 'html.parser')
# 1. Get the title of the page
page_title = soup.title.string
print(f"Page Title: {page_title}")
# 2. Find the first h1 tag
h1_tag = soup.find('h1')
print(f"H1 Content: {h1_tag.text}")
# 3. Find a paragraph with a specific class
intro_paragraph = soup.find('p', class_='intro')
print(f"Intro Paragraph: {intro_paragraph.text}")
# 4. Find the first link (a tag)
first_link = soup.find('a')
print(f"First Link Text: {first_link.text}")
print(f"First Link URL: {first_link['href']}")
```
Output example:
```
Page Title: Learning Beautiful Soup
H1 Content: Web Scraping Fundamentals
Intro Paragraph: Beautiful Soup helps parse HTML and XML documents.
First Link Text: Python Official Website
First Link URL: https://www.python.org
```
### Small Challenge π
Try to find *all* the `<p>` tags in the `html_doc` string using `soup.find_all('p')` and print their text content! Can you also extract the `href` attribute from the `<a>` tag using `first_link.get('href')`?
---
Python.org
Welcome to Python.org
The official home of the Python Programming Language
What is the primary purpose of Beautiful Soup in Python web scraping?
Anonymous Quiz
100%
To parse HTML and XML documents and extract data.
0%
To make HTTP requests to web servers.
0%
To execute JavaScript on web pages.
0%
To store scraped data in a database.
π Day 27: Diving into Web Development with Python! π Today, we're getting a sneak peek at the powerful world of Python web frameworks: Flask and Django! β¨ These frameworks are your go-to tools for building dynamic and interactive web applications, from simple APIs to complex websites. Flask is known for its simplicity and flexibility (a microframework), while Django offers a full-stack solution with everything included. Let's write our first tiny Flask app! π
```python
# First, if you haven't, install Flask:
# pip install Flask
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the homepage ('/')
@app.route('/')
def hello_world():
return 'Hello, Flask World! π'
# Run the application if this script is executed directly
if __name__ == '__main__':
# debug=True allows for automatic reloading and provides a debugger
# For production, set debug=False
app.run(debug=True)
```
Output example:
To run this:
1. Save the code as `app.py` (or any `.py` file).
2. Open your terminal in the same directory.
3. Run: `python app.py`
You'll see output like:
```
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
```
Open `http://127.0.0.1:5000/` in your browser to see "Hello, Flask World! π"
π‘ **Challenge:** Add another route to the Flask application! Create a new route `@app.route('/greet/<name>')` that takes a name as a URL parameter (e.g., `/greet/Alice`) and returns a personalized greeting like `Hello, Alice!` Try it out! π§βπ»
---
```python
# First, if you haven't, install Flask:
# pip install Flask
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the homepage ('/')
@app.route('/')
def hello_world():
return 'Hello, Flask World! π'
# Run the application if this script is executed directly
if __name__ == '__main__':
# debug=True allows for automatic reloading and provides a debugger
# For production, set debug=False
app.run(debug=True)
```
Output example:
To run this:
1. Save the code as `app.py` (or any `.py` file).
2. Open your terminal in the same directory.
3. Run: `python app.py`
You'll see output like:
```
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
```
Open `http://127.0.0.1:5000/` in your browser to see "Hello, Flask World! π"
π‘ **Challenge:** Add another route to the Flask application! Create a new route `@app.route('/greet/<name>')` that takes a name as a URL parameter (e.g., `/greet/Alice`) and returns a personalized greeting like `Hello, Alice!` Try it out! π§βπ»
---
π Day 28: Dive into the fascinating world of Asynchronous Programming with `asyncio`! π’ Tired of your program waiting? `asyncio` lets your Python code perform multiple tasks *seemingly* at once, especially great for I/O-bound operations like network requests or file operations. Say goodbye to blocking and hello to efficiency! π¨ Let's make your code run smarter, not harder.
```python
import asyncio
import time
async def perform_task(name, delay):
"""Simulates an I/O-bound operation."""
print(f"[{name}] Starting...")
await asyncio.sleep(delay) # Yield control back to the event loop
print(f"[{name}] Finished after {delay} seconds!")
return f"{name} done"
async def main():
start_time = time.time()
print("Main: Kicking off async tasks...")
# Run tasks concurrently
results = await asyncio.gather(
perform_task("Task A", 2),
perform_task("Task B", 1),
perform_task("Task C", 3)
)
end_time = time.time()
print(f"nMain: All tasks completed in {end_time - start_time:.2f} seconds.")
print(f"Main: Results: {results}")
if __name__ == "__main__":
asyncio.run(main())
```
Output example:
Main: Kicking off async tasks...
[Task A] Starting...
[Task B] Starting...
[Task C] Starting...
[Task B] Finished after 1 seconds!
[Task A] Finished after 2 seconds!
[Task C] Finished after 3 seconds!
Main: All tasks completed in 3.00 seconds.
Main: Results: ['Task A done', 'Task B done', 'Task C done']
π‘ **Small Challenge:** Add another `async` function that attempts to read a (non-existent) file using `asyncio.to_thread` to simulate a blocking file read. How would you integrate it into the `asyncio.gather` call? What's the benefit of `asyncio.to_thread` here?
---
```python
import asyncio
import time
async def perform_task(name, delay):
"""Simulates an I/O-bound operation."""
print(f"[{name}] Starting...")
await asyncio.sleep(delay) # Yield control back to the event loop
print(f"[{name}] Finished after {delay} seconds!")
return f"{name} done"
async def main():
start_time = time.time()
print("Main: Kicking off async tasks...")
# Run tasks concurrently
results = await asyncio.gather(
perform_task("Task A", 2),
perform_task("Task B", 1),
perform_task("Task C", 3)
)
end_time = time.time()
print(f"nMain: All tasks completed in {end_time - start_time:.2f} seconds.")
print(f"Main: Results: {results}")
if __name__ == "__main__":
asyncio.run(main())
```
Output example:
Main: Kicking off async tasks...
[Task A] Starting...
[Task B] Starting...
[Task C] Starting...
[Task B] Finished after 1 seconds!
[Task A] Finished after 2 seconds!
[Task C] Finished after 3 seconds!
Main: All tasks completed in 3.00 seconds.
Main: Results: ['Task A done', 'Task B done', 'Task C done']
π‘ **Small Challenge:** Add another `async` function that attempts to read a (non-existent) file using `asyncio.to_thread` to simulate a blocking file read. How would you integrate it into the `asyncio.gather` call? What's the benefit of `asyncio.to_thread` here?
---
Here's your Telegram post for Day 29:
---
**Day 29: Basic Database Interaction (SQLite) πΎ**
Ever wondered how applications store all that important information? Today, we dive into the world of databases with Python's built-in `sqlite3` module! π SQLite is a super lightweight, file-based database β perfect for learning and small projects. You'll learn to connect, create tables, insert data, and retrieve it. Let's get persistent! β¨
```python
import sqlite3
# 1. Connect to the database (or create it if it doesn't exist)
# This will create a file named 'my_items.db' in your script's directory.
conn = sqlite3.connect('my_items.db')
cursor = conn.cursor()
# 2. Create a table (IF NOT EXISTS prevents errors if you run this multiple times)
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
item_name TEXT NOT NULL,
quantity INTEGER NOT NULL
)
''')
# 3. Insert some data into the table
# Using placeholders (?) is crucial to prevent SQL injection vulnerabilities.
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Laptop", 5))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Mouse", 12))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Keyboard", 8))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Monitor", 3))
# Important: Commit the changes to save them permanently to the database file
conn.commit()
# 4. Retrieve and print all data from the 'products' table
print("All products in the database:")
cursor.execute("SELECT * FROM products")
items = cursor.fetchall() # Fetches all rows from the last executed query
for item in items:
print(item)
# 5. Close the database connection
conn.close()
```
Output example:
```
All products in the database:
(1, 'Laptop', 5)
(2, 'Mouse', 12)
(3, 'Keyboard', 8)
(4, 'Monitor', 3)
```
Challenge Time! π§ Can you modify the `SELECT` query in the code to retrieve *only* products with a `quantity` greater than 10? Share your solution! π
---
---
**Day 29: Basic Database Interaction (SQLite) πΎ**
Ever wondered how applications store all that important information? Today, we dive into the world of databases with Python's built-in `sqlite3` module! π SQLite is a super lightweight, file-based database β perfect for learning and small projects. You'll learn to connect, create tables, insert data, and retrieve it. Let's get persistent! β¨
```python
import sqlite3
# 1. Connect to the database (or create it if it doesn't exist)
# This will create a file named 'my_items.db' in your script's directory.
conn = sqlite3.connect('my_items.db')
cursor = conn.cursor()
# 2. Create a table (IF NOT EXISTS prevents errors if you run this multiple times)
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
item_name TEXT NOT NULL,
quantity INTEGER NOT NULL
)
''')
# 3. Insert some data into the table
# Using placeholders (?) is crucial to prevent SQL injection vulnerabilities.
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Laptop", 5))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Mouse", 12))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Keyboard", 8))
cursor.execute("INSERT INTO products (item_name, quantity) VALUES (?, ?)", ("Monitor", 3))
# Important: Commit the changes to save them permanently to the database file
conn.commit()
# 4. Retrieve and print all data from the 'products' table
print("All products in the database:")
cursor.execute("SELECT * FROM products")
items = cursor.fetchall() # Fetches all rows from the last executed query
for item in items:
print(item)
# 5. Close the database connection
conn.close()
```
Output example:
```
All products in the database:
(1, 'Laptop', 5)
(2, 'Mouse', 12)
(3, 'Keyboard', 8)
(4, 'Monitor', 3)
```
Challenge Time! π§ Can you modify the `SELECT` query in the code to retrieve *only* products with a `quantity` greater than 10? Share your solution! π
---
In Python's `sqlite3` module, what method is essential to save changes (like `INSERT` or `UPDATE`) permanently to the database file after executing them?
Anonymous Quiz
0%
cursor.execute()
100%
conn.commit()
0%
0%
cursor.save_changes()
π Wow, we've made it to Day 30! π
Congratulations on completing a month of consistent Python learning! Today isn't just about new syntax, but about reflecting, consolidating, and dreaming big. It's time to start thinking about your *final project* β the culmination of everything you've learned. Let's get those creative juices flowing and brainstorm some ideas, then review what makes a good project. What will you build? π€π‘
```python
import random
def generate_project_idea():
"""Generates a random Python project idea from a predefined list."""
ideas = [
"A simple To-Do List application (CLI or basic GUI)",
"A calculator program with basic operations",
"A password generator (with options for length, symbols, numbers)",
"A unit converter (e.g., Celsius to Fahrenheit, meters to feet)",
"A basic 'Guess the Number' game",
"A text-based adventure game",
"A file organizer (e.g., sort files by type)",
"A simple web scraper for product prices on a specific site",
"A weather app (using a public API like OpenWeatherMap)",
"A basic contact book with add/view/delete functionality"
]
return random.choice(ideas)
print("π Your potential project idea for today is:")
print(f"π {generate_project_idea()}")
```
Output example:
π Your potential project idea for today is:
π A password generator (with options for length, symbols, numbers)
*(Note: Your actual output will vary each time you run the code!)*
**Small Challenge:**
Pick one of the generated ideas (or come up with your own awesome project concept!) and list 3 core features you would implement first. How would you start planning the steps to build it? Share your thoughts! π
---
Congratulations on completing a month of consistent Python learning! Today isn't just about new syntax, but about reflecting, consolidating, and dreaming big. It's time to start thinking about your *final project* β the culmination of everything you've learned. Let's get those creative juices flowing and brainstorm some ideas, then review what makes a good project. What will you build? π€π‘
```python
import random
def generate_project_idea():
"""Generates a random Python project idea from a predefined list."""
ideas = [
"A simple To-Do List application (CLI or basic GUI)",
"A calculator program with basic operations",
"A password generator (with options for length, symbols, numbers)",
"A unit converter (e.g., Celsius to Fahrenheit, meters to feet)",
"A basic 'Guess the Number' game",
"A text-based adventure game",
"A file organizer (e.g., sort files by type)",
"A simple web scraper for product prices on a specific site",
"A weather app (using a public API like OpenWeatherMap)",
"A basic contact book with add/view/delete functionality"
]
return random.choice(ideas)
print("π Your potential project idea for today is:")
print(f"π {generate_project_idea()}")
```
Output example:
π Your potential project idea for today is:
π A password generator (with options for length, symbols, numbers)
*(Note: Your actual output will vary each time you run the code!)*
**Small Challenge:**
Pick one of the generated ideas (or come up with your own awesome project concept!) and list 3 core features you would implement first. How would you start planning the steps to build it? Share your thoughts! π
---
When starting a new Python project, what is generally considered the *most crucial first step* after deciding on an idea?
Anonymous Quiz
100%
Writing all the code for the main functionality immediately.
0%
Designing the project architecture and breaking it into smaller tasks.
0%
Creating an exhaustive list of all possible advanced features.
0%
Picking a random Python library to integrate, regardless of need.
What is the primary purpose of `asyncio.loop.run_in_executor()` when integrating with blocking C functions via FFI?
Anonymous Quiz
0%
To move blocking C calls off the main event loop thread to prevent it from freezing.
0%
To convert a synchronous C function directly into a coroutine without using threads.
0%
To execute C code directly on the Python interpreter's main thread for maximum speed.
0%
To automatically compile and link C code at runtime within the event loop.
π Day 32: Unlock the ultimate power of Python! π Ever wondered how frameworks create magical APIs or enforce specific class structures? Today, we dive deep into the #MetaclassMultiverse! π€― We'll explore how to forge custom type systems, going far beyond simple `type` calls to control class creation itself. Get ready to redefine what a Python class can be! Let's build some powerful magic together. β¨ #PythonLearning #AdvancedPython #Metaclasses
Metaclasses allow you to intercept class creation and inject behavior, attributes, or methods before the class is even fully defined. This enables powerful patterns for validation, registration, and framework building!
```python
import datetime
# π Our custom metaclass
class MyMeta(type):
"""
A metaclass that automatically adds a creation timestamp and a 'greet' method
to any class that uses it.
"""
def __new__(cls, name, bases, dct):
# 1. Add a creation timestamp to the class dictionary
dct['_creation_timestamp'] = datetime.datetime.now()
# 2. Add a default 'greet' method if not already defined
if 'greet' not in dct:
def greet_method(self):
return (f"Hello from {self.__class__.__name__}! "
f"Created at {self._creation_timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
dct['greet'] = greet_method
# 3. Call the base type's __new__ to complete class creation
return super().__new__(cls, name, bases, dct)
# π§ββοΈ Classes using our custom metaclass
class Character(metaclass=MyMeta):
def __init__(self, name):
self.name = name
class Item(metaclass=MyMeta):
def __init__(self, name):
self.name = name
# This class defines its own greet, which will override the metaclass's
def greet(self):
return f"Hello, I am {self.name}, an item created magically!"
# β¨ Let's see them in action!
hero = Character("Alice")
sword = Item("Excalibur")
print(hero.greet())
print(sword.greet()) # Notice how Item's custom greet takes precedence!
print(f"Character created at: {Character._creation_timestamp}")
```
Output example:
```
Hello from Character! Created at 2023-10-27 10:30:00 # (Timestamp will vary)
Hello, I am Excalibur, an item created magically!
Character created at: 2023-10-27 10:30:00 # (Timestamp will vary)
```
π‘ **Your Challenge:** Modify `MyMeta` to automatically add a class-level `_registry` dictionary. For every class that uses `MyMeta`, register the class itself in this `_registry` using its `name` as the key. How would you then access this registry from another part of your code to list all registered classes?
---
Metaclasses allow you to intercept class creation and inject behavior, attributes, or methods before the class is even fully defined. This enables powerful patterns for validation, registration, and framework building!
```python
import datetime
# π Our custom metaclass
class MyMeta(type):
"""
A metaclass that automatically adds a creation timestamp and a 'greet' method
to any class that uses it.
"""
def __new__(cls, name, bases, dct):
# 1. Add a creation timestamp to the class dictionary
dct['_creation_timestamp'] = datetime.datetime.now()
# 2. Add a default 'greet' method if not already defined
if 'greet' not in dct:
def greet_method(self):
return (f"Hello from {self.__class__.__name__}! "
f"Created at {self._creation_timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
dct['greet'] = greet_method
# 3. Call the base type's __new__ to complete class creation
return super().__new__(cls, name, bases, dct)
# π§ββοΈ Classes using our custom metaclass
class Character(metaclass=MyMeta):
def __init__(self, name):
self.name = name
class Item(metaclass=MyMeta):
def __init__(self, name):
self.name = name
# This class defines its own greet, which will override the metaclass's
def greet(self):
return f"Hello, I am {self.name}, an item created magically!"
# β¨ Let's see them in action!
hero = Character("Alice")
sword = Item("Excalibur")
print(hero.greet())
print(sword.greet()) # Notice how Item's custom greet takes precedence!
print(f"Character created at: {Character._creation_timestamp}")
```
Output example:
```
Hello from Character! Created at 2023-10-27 10:30:00 # (Timestamp will vary)
Hello, I am Excalibur, an item created magically!
Character created at: 2023-10-27 10:30:00 # (Timestamp will vary)
```
π‘ **Your Challenge:** Modify `MyMeta` to automatically add a class-level `_registry` dictionary. For every class that uses `MyMeta`, register the class itself in this `_registry` using its `name` as the key. How would you then access this registry from another part of your code to list all registered classes?
---