Articles

Python Intermediate - Lesson 20 - Decorators and Function Wrappers

Python Intermediate · Lesson 20 Decorators and Function Wrappers A decorator lets you add behavior around a function without rewriting that function's core work. Decorators are used for logging, timing, permissions, and many other reusable tasks. By the end, you can: define a decorator, wrap a function with *args and **kwargs , preserve function metadata with functools.wraps , and use try/finally for wrapper cleanup. Keep wrappers transparent: a wrapper should normally pass the original arguments through and return the original result. Add only the behavior you need, and do not accidentally hide exceptions or change the function's output. 1. Functions can be passed to other functions In Python, a function is a value. You can pass one to another function and call it there. A decorator uses that idea to receive a function and return a replacement function. def run_twice(funct...

Python Intermediate - Lesson 19 - Iterators and Generators

Python Intermediate · Lesson 19 Iterators and Generators Python can produce values one at a time instead of building a large list first. Iterators and generators are useful for processing files, records, or calculated sequences in a steady stream. By the end, you can: use iter() and next() , write a generator function with yield , create a generator expression, and process a stream of CSV rows without loading the whole file into memory. One-pass reminder: a generator is usually consumed as you loop over it. If you need to process the same values multiple times, create a new generator or deliberately save the values in a collection. 1. Iterable versus iterator An iterable can provide an iterator. Lists, strings, and dictionaries are common iterables. An iterator produces the next value when asked and remembers where it is in the sequence. topics = ["functions", "files", ...

Python Intermediate - Lesson 18 - Dataclasses and Type Hints

Python Intermediate · Lesson 18 Dataclasses and Type Hints Many classes mainly hold data. Python's dataclasses module generates useful methods for these classes, while type hints make expected inputs and outputs easier to understand. In this lesson, you’ll build clearer data models for study sessions. By the end, you can: add type hints to variables and functions, define a dataclass, use default values safely with field(default_factory=...) , and add runtime validation when your program needs it. Type hints are documentation, not automatic validation. Python does not reject a value just because it does not match an annotation. If invalid data must be rejected, write a check or use a validation library. dataclasses is included with Python 3.7 and later. 1. Add type hints to variables and functions A type hint indicates the kind of value a function expects or returns. It helps people read...

Python Intermediate - Lesson 17 - Inheritance and Composition

Python Intermediate · Lesson 17 Inheritance and Composition Classes can share behavior through inheritance, or work together by containing instances of other classes. These patterns help organize larger programs, but choosing the simpler relationship matters: a focus block is a kind of study block, while a study plan has study blocks. By the end, you can: define a subclass, reuse a parent initializer with super() , override a method, and use composition to build a larger object from smaller objects. Design rule of thumb: use inheritance for a true “is-a” relationship with shared behavior. Use composition for a “has-a” relationship. Prefer a small, clear design over a deep class hierarchy. 1. Inherit from a parent class A subclass can reuse methods and attributes from a parent class. Put the parent class inside parentheses when defining the subclass. class StudyBlock: def __init...

Python Intermediate - Lesson 16 - Classes and Objects

Python Intermediate · Lesson 16 Classes and Objects A class groups related data and behavior into a new kind of object. You already use objects in Python: strings, lists, and dictionaries all have methods. In this lesson, you’ll define a small class of your own and create multiple independent objects from it. By the end, you can: define a class, initialize instance attributes, write methods that use self , create instances, and keep related data and behavior together. Keep it practical: classes are useful when several pieces of data and actions belong together. A short function is often simpler when there is no persistent object state to manage. 1. Define a class A class is a recipe for creating objects. By convention, class names use CapWords . The __init__ method runs when a new instance is created. class StudySession: def __init__(self, topic, minutes): self.topic = topic...

Python Intermediate - Lesson 15 - Testing Python Programs

Python Intermediate · Lesson 15 Testing Python Programs Tests check whether code behaves as expected, including when it receives edge cases or invalid input. Python includes unittest , so you can write and run a useful test suite without installing another package. By the end, you can: write tests with unittest.TestCase , compare expected and actual values, check that invalid input raises an error, and run test discovery from the command line. Test safely: begin with small functions that do not send emails, change files, or call live services. For programs with side effects, use temporary files or replace external services with test doubles so a test run does not send messages or alter important data. 1. What makes a useful test? A test supplies an input, runs a function, and checks the result against an expected value. A good test name describes the behavior it verifies. def minutes_to_hour...

Python Intermediate - Lesson 14 - Email Automation, Safely

Python Intermediate · Lesson 14 Email Automation, Safely Python can prepare and send email through an SMTP server. In this lesson, you’ll build a plain-text message with the standard library, keep account credentials out of your code, and make sending an explicit choice. By the end, you can: create an email message, read settings from environment variables, connect to an SMTP server using TLS, and preview a draft before choosing to send. Email safety: practice with your own address or a consenting test recipient. Do not send unsolicited bulk email. Never publish a password, app password, or API key in a Blogger post, source file, or browser-side JavaScript. Use a protected secret store or environment settings, and follow your email provider's sending rules. 1. Build an email message EmailMessage represents an email. Set the sender, recipient, subject, and body before handing the message to a...