본문 바로가기

카테고리 없음

Python #6

In this session, we'll explore some advanced Python topics, including generators, decorators in more detail, and an introduction to testing with Python.

Generators

Generators are a type of iterable, like lists or tuples. Unlike lists, they do not store their contents in memory; instead, they generate items on the fly, making them more memory efficient.

Creating a Generator

You can create a generator using a function with the yield statement.

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

counter = count_up_to(5)
for number in counter:
    print(number)  # Output: 1 2 3 4 5

Generator Expressions

Similar to list comprehensions, but using parentheses instead of brackets.

squares = (x**2 for x in range(10))
for square in squares:
    print(square)

Advanced Decorators

Decorators are functions that modify the behavior of another function. They are often used for logging, enforcing access control, instrumentation, or caching.

Decorator with Arguments

You can create decorators that accept arguments by adding another layer of functions.

def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Testing with Python

Testing is crucial for ensuring code reliability and correctness. Python provides several tools for testing.

Using unittest

The unittest module is a built-in library for writing and running tests.

import unittest

def add(a, b):
    return a + b

class TestMathOperations(unittest.TestCase):

    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

Using pytest

pytest is a third-party testing framework that is more flexible and user-friendly than unittest.

# test_math.py

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

Run tests using the command:

pytest test_math.py

These advanced topics will help you write more efficient and maintainable Python code. Generators allow you to handle large datasets efficiently; decorators enable you to enhance functions with minimal code changes; and testing ensures your code works as expected.