Python 에서 누락되거나 유효하지 않은 함수 인자 처리 방법

PythonBeginner
지금 연습하기

소개

Python 의 함수 인자는 프로그래밍의 기본 요소이지만, 누락되거나 유효하지 않은 인자를 처리하는 것은 어려울 수 있습니다. 이 튜토리얼에서는 Python 에서 함수 인자를 처리하는 방법을 안내하며, 기본 사항 이해부터 강력한 유효성 검사 및 오류 처리 전략 구현까지 다룹니다. 이 튜토리얼을 마치면 함수 인자를 우아하게 관리하는 Python 코드를 작성할 수 있게 되어, 더 안정적이고 유지보수가 용이한 애플리케이션을 만들 수 있습니다.

기본 함수 인자 및 기본값 이해

Python 에서 함수는 특정 작업을 수행하는 재사용 가능한 코드 블록입니다. 함수를 정의할 때, 함수가 받기를 기대하는 매개변수를 지정할 수 있습니다. 다양한 유형의 인자를 사용하여 함수를 설정하고 기본값을 제공하는 방법을 알아보겠습니다.

첫 번째 함수 만들기

작업할 간단한 Python 파일을 만들어 보겠습니다. WebIDE 에서 프로젝트 디렉토리로 이동하여 function_args.py라는 새 파일을 만듭니다.

  1. WebIDE 에서 "File" 메뉴를 클릭합니다.
  2. "New File"을 선택합니다.
  3. 파일 이름으로 function_args.py를 입력합니다.
  4. "OK"를 클릭합니다.

이제 이 파일에 기본 함수를 추가해 보겠습니다.

def greet(name):
    """A simple function that greets a person by name."""
    return f"Hello, {name}!"

## Call the function and print the result
result = greet("Alice")
print(result)

파일을 저장하고 (Ctrl+S 또는 File > Save) 터미널에서 실행합니다.

python3 function_args.py

다음과 같은 출력을 볼 수 있습니다.

Hello, Alice!

필수 인자 이해

위의 예에서 name은 필수 인자입니다. 이 인자를 제공하지 않고 함수를 호출하려고 하면 Python 은 오류를 발생시킵니다.

이것을 보여주기 위해 파일을 수정해 보겠습니다.

def greet(name):
    """A simple function that greets a person by name."""
    return f"Hello, {name}!"

## This will work
result = greet("Alice")
print(result)

## This will raise an error
try:
    result = greet()
    print(result)
except TypeError as e:
    print(f"Error: {e}")

파일을 저장하고 실행합니다.

python3 function_args.py

출력:

Hello, Alice!
Error: greet() missing 1 required positional argument: 'name'

보시다시피, 필수 인자를 제공하지 않으면 Python 은 TypeError를 발생시킵니다.

기본값 추가

인자를 선택적으로 만들기 위해 기본값을 제공할 수 있습니다. 함수를 업데이트해 보겠습니다.

def greet(name="Guest"):
    """A function that greets a person by name, with a default value."""
    return f"Hello, {name}!"

## With an argument
result1 = greet("Alice")
print(result1)

## Without an argument - uses the default value
result2 = greet()
print(result2)

저장하고 실행합니다.

python3 function_args.py

출력:

Hello, Alice!
Hello, Guest!

이제 함수는 인자가 있든 없든 모두 작동합니다.

기본값이 있는 여러 인자

여러 인자를 처리하도록 함수를 확장하고, 일부는 기본값을 갖도록 하겠습니다.

def greet(name="Guest", message="Hello", punctuation="!"):
    """A function with multiple arguments and default values."""
    return f"{message}, {name}{punctuation}"

## Using all default values
print(greet())

## Providing only the name
print(greet("Alice"))

## Providing name and message
print(greet("Bob", "Hi"))

## Providing all arguments
print(greet("Charlie", "Welcome", "!!!"))

저장하고 실행합니다.

python3 function_args.py

출력:

Hello, Guest!
Hello, Alice!
Hi, Bob!
Welcome, Charlie!!!

키워드 인자 사용

인자의 순서에 관계없이 이름을 지정하여 인자를 지정할 수도 있습니다.

def greet(name="Guest", message="Hello", punctuation="!"):
    """A function with multiple arguments and default values."""
    return f"{message}, {name}{punctuation}"

## Using keyword arguments
print(greet(message="Hey", name="David"))
print(greet(punctuation="...", message="Welcome back", name="Emma"))

저장하고 실행합니다.

python3 function_args.py

출력:

Hey, David!
Welcome back, Emma...

이것은 함수에 많은 인자가 있고 그 중 일부만 지정하려는 경우 특히 유용합니다.

이제 기본 인자가 있는 함수를 만드는 방법과 키워드 인자를 사용하는 방법을 이해했습니다. 다음 단계에서는 누락되거나 유효하지 않은 함수 인자를 처리하는 더 고급 방법을 살펴보겠습니다.

*args 및 **kwargs 를 사용하여 누락된 인자 처리

Python 에서는 가변 개수의 인자를 허용하는 유연한 함수를 만들어야 하는 경우가 있습니다. 이러한 경우를 처리하기 위해 Python 은 두 가지 특수 구문 요소인 *args**kwargs를 제공합니다.

새 Python 파일 만들기

이러한 개념을 사용해 볼 새 파일을 만들어 보겠습니다.

  1. WebIDE 에서 "File" 메뉴를 클릭합니다.
  2. "New File"을 선택합니다.
  3. 파일 이름으로 flexible_args.py를 입력합니다.
  4. "OK"를 클릭합니다.

*args 이해

*args 구문을 사용하면 함수가 임의의 수의 위치 인자를 허용할 수 있으며, 이는 튜플로 수집됩니다.

flexible_args.py에 다음 코드를 추가합니다.

def sum_numbers(*args):
    """A function that sums up any number of arguments."""
    result = 0
    for num in args:
        result += num
    return result

## Test the function with different numbers of arguments
print(f"Sum of 1, 2: {sum_numbers(1, 2)}")
print(f"Sum of 1, 2, 3, 4, 5: {sum_numbers(1, 2, 3, 4, 5)}")
print(f"No arguments: {sum_numbers()}")

파일을 저장하고 실행합니다.

python3 flexible_args.py

출력:

Sum of 1, 2: 3
Sum of 1, 2, 3, 4, 5: 15
No arguments: 0

이것은 *args가 전혀 없는 경우를 포함하여 임의의 수의 인자를 처리할 수 있음을 보여줍니다. 함수 내부에서 args는 제공된 모든 인자를 포함하는 튜플입니다.

**kwargs 이해

**kwargs 구문을 사용하면 함수가 임의의 수의 키워드 인자를 허용할 수 있으며, 이는 딕셔너리로 수집됩니다.

파일에 다른 함수를 추가해 보겠습니다.

def build_profile(**kwargs):
    """A function that builds a user profile from keyword arguments."""
    profile = {}

    ## Add required fields with defaults
    profile["name"] = kwargs.get("name", "Anonymous")
    profile["age"] = kwargs.get("age", "Not specified")

    ## Add any additional fields
    for key, value in kwargs.items():
        if key not in ["name", "age"]:
            profile[key] = value

    return profile

## Test the function with different keyword arguments
print("Basic profile:", build_profile())
print("Full profile:", build_profile(name="Alice", age=30, occupation="Developer", location="New York"))
print("Custom fields:", build_profile(hobby="Reading", favorite_color="Blue"))

저장하고 실행합니다.

python3 flexible_args.py

출력:

Basic profile: {'name': 'Anonymous', 'age': 'Not specified'}
Full profile: {'name': 'Alice', 'age': 30, 'occupation': 'Developer', 'location': 'New York'}
Custom fields: {'name': 'Anonymous', 'age': 'Not specified', 'hobby': 'Reading', 'favorite_color': 'Blue'}

kwargs.get("key", default_value)를 사용하여 존재하지 않는 경우 기본값으로 값을 검색할 수 있음을 확인하십시오.

필수, 기본, *args 및 **kwargs 결합

이러한 모든 유형의 인자를 결합하는 더 복잡한 함수를 만들어 보겠습니다.

def format_message(recipient, message="Hello", *args, **kwargs):
    """
    A function that formats a message with various customization options.
    - recipient: Required - who the message is for
    - message: Default greeting
    - *args: Additional message parts
    - **kwargs: Formatting options
    """
    ## Start with the basic message
    full_message = f"{message}, {recipient}!"

    ## Add any additional message parts
    if args:
        full_message += " " + " ".join(args)

    ## Apply formatting options
    if kwargs.get("upper", False):
        full_message = full_message.upper()

    if kwargs.get("wrap", False):
        full_message = f"[{full_message}]"

    return full_message

## Test with different combinations
print(format_message("Alice"))
print(format_message("Bob", "Hi"))
print(format_message("Charlie", "Welcome", "Hope", "you", "are", "well"))
print(format_message("David", "Greetings", upper=True))
print(format_message("Emma", wrap=True))
print(format_message("Frank", "Hey", "How's it going?", upper=True, wrap=True))

저장하고 실행합니다.

python3 flexible_args.py

출력:

Hello, Alice!
Hi, Bob!
Welcome, Charlie! Hope you are well
GREETINGS, DAVID!
[Hello, Emma!]
[HEY, FRANK! HOW'S IT GOING?]

이 예제는 모든 유형의 함수 인자를 함께 사용하는 방법을 보여줍니다.

  1. recipient는 필수 위치 인자입니다.
  2. message는 기본값을 가지므로 선택 사항입니다.
  3. *args는 추가 위치 인자를 캡처합니다.
  4. **kwargs는 키워드 인자를 캡처합니다.

이러한 접근 방식을 결합하여 누락되거나 선택적 인자를 우아하게 처리하는 매우 유연한 함수를 만들 수 있습니다.

함수 인자 유효성 검사

Python 에서 함수를 만들 때, 함수의 주요 로직을 진행하기 전에 함수에 전달된 인자가 유효한지 확인하는 것이 중요합니다. 이 단계에서는 함수 인자를 검증하는 여러 가지 기술을 배우겠습니다.

새 Python 파일 만들기

유효성 검사 개념을 사용해 볼 새 파일을 만들어 보겠습니다.

  1. WebIDE 에서 "File" 메뉴를 클릭합니다.
  2. "New File"을 선택합니다.
  3. 파일 이름으로 validate_args.py를 입력합니다.
  4. "OK"를 클릭합니다.

조건문을 사용한 기본 유효성 검사

인자를 검증하는 가장 간단한 방법은 조건문을 사용하는 것입니다. 몇 가지 기본 유효성 검사부터 시작해 보겠습니다.

def calculate_rectangle_area(length, width):
    """Calculate the area of a rectangle, validating inputs."""
    ## Validate that inputs are numbers
    if not isinstance(length, (int, float)):
        raise TypeError("Length must be a number")
    if not isinstance(width, (int, float)):
        raise TypeError("Width must be a number")

    ## Validate that inputs are positive
    if length <= 0:
        raise ValueError("Length must be positive")
    if width <= 0:
        raise ValueError("Width must be positive")

    ## Calculate the area
    return length * width

## Test with valid inputs
try:
    area = calculate_rectangle_area(5, 3)
    print(f"Area of rectangle: {area}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

## Test with invalid types
try:
    area = calculate_rectangle_area("5", 3)
    print(f"Area of rectangle: {area}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

## Test with invalid values
try:
    area = calculate_rectangle_area(5, -3)
    print(f"Area of rectangle: {area}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

저장하고 실행합니다.

python3 validate_args.py

출력:

Area of rectangle: 15
Error: Length must be a number
Error: Width must be positive

이 함수는 계산을 수행하기 전에 인자의 유형과 값을 모두 검증합니다. 잘못된 인자가 감지되면 적절한 오류 메시지가 발생합니다.

어설션 (Assertion) 을 사용한 유효성 검사

인자를 검증하는 또 다른 방법은 어설션을 사용하는 것입니다. 어설션은 조건이 충족되지 않으면 AssertionError를 발생시키는 문입니다.

def calculate_discount(price, discount_percent):
    """Calculate the discounted price."""
    ## Assert that inputs are valid
    assert isinstance(price, (int, float)), "Price must be a number"
    assert isinstance(discount_percent, (int, float)), "Discount must be a number"
    assert price >= 0, "Price cannot be negative"
    assert 0 <= discount_percent <= 100, "Discount must be between 0 and 100"

    ## Calculate the discount
    discount_amount = price * (discount_percent / 100)
    return price - discount_amount

## Test with valid inputs
try:
    discounted_price = calculate_discount(100, 20)
    print(f"Discounted price: ${discounted_price}")
except AssertionError as e:
    print(f"Error: {e}")

## Test with invalid discount percentage
try:
    discounted_price = calculate_discount(100, 120)
    print(f"Discounted price: ${discounted_price}")
except AssertionError as e:
    print(f"Error: {e}")

저장하고 실행합니다.

python3 validate_args.py

출력:

Discounted price: $80.0
Error: Discount must be between 0 and 100

어설션은 개발 및 디버깅에 유용하지만 프로덕션 코드에서는 비활성화될 수 있으므로 실제 응용 프로그램에서 유효성 검사에 항상 최선의 선택은 아닙니다.

문서화를 위한 타입 힌트 (Type Hints) 사용

Python 3.5 이상은 타입 힌트를 지원하며, 이는 함수 인자와 반환 값의 예상 유형을 문서화하는 데 도움이 될 수 있습니다. 타입 힌트는 자체적으로 런타임 유효성 검사를 수행하지 않지만 유용한 문서를 제공하며 mypy와 같은 외부 도구로 확인할 수 있습니다.

def calculate_average(numbers: list[float]) -> float:
    """Calculate the average of a list of numbers."""
    if not numbers:
        raise ValueError("Cannot calculate average of empty list")

    if not all(isinstance(n, (int, float)) for n in numbers):
        raise TypeError("All elements must be numbers")

    return sum(numbers) / len(numbers)

## Test with valid input
try:
    avg = calculate_average([1, 2, 3, 4, 5])
    print(f"Average: {avg}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

## Test with empty list
try:
    avg = calculate_average([])
    print(f"Average: {avg}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

## Test with non-numeric elements
try:
    avg = calculate_average([1, 2, "3", 4, 5])
    print(f"Average: {avg}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

저장하고 실행합니다.

python3 validate_args.py

출력:

Average: 3.0
Error: Cannot calculate average of empty list
Error: All elements must be numbers

타입 힌트 (list[float]-> float) 는 자체적으로 유효성 검사를 수행하지 않습니다. 여전히 자체 유효성 검사 코드를 작성해야 합니다. 이는 문서 역할을 하며 외부 도구로 확인할 수 있습니다.

유효성 검사를 통해 강력한 함수 만들기

이제 이러한 모든 기술을 적용하여 할인된 품목의 총 비용을 계산하는 강력한 함수를 만들어 보겠습니다.

def calculate_total_cost(items=None, tax_rate=0, discount=0):
    """
    Calculate the total cost of items with tax and discount.

    Args:
        items: List of (item_name, price) tuples
        tax_rate: Tax rate percentage (0-100)
        discount: Discount percentage (0-100)

    Returns:
        A dictionary with the total, subtotal, tax amount, and discount amount
    """
    ## Validate items
    if items is None:
        items = []

    if not isinstance(items, list):
        raise TypeError("Items must be a list")

    ## Validate each item in the list
    for i, item in enumerate(items):
        if not isinstance(item, tuple) or len(item) != 2:
            raise ValueError(f"Item {i} must be a tuple of (name, price)")

        name, price = item
        if not isinstance(name, str):
            raise TypeError(f"Name of item {i} must be a string")
        if not isinstance(price, (int, float)):
            raise TypeError(f"Price of item {i} must be a number")
        if price < 0:
            raise ValueError(f"Price of item {i} cannot be negative")

    ## Validate tax_rate and discount
    if not isinstance(tax_rate, (int, float)):
        raise TypeError("Tax rate must be a number")
    if not isinstance(discount, (int, float)):
        raise TypeError("Discount must be a number")

    if not (0 <= tax_rate <= 100):
        raise ValueError("Tax rate must be between 0 and 100")
    if not (0 <= discount <= 100):
        raise ValueError("Discount must be between 0 and 100")

    ## Calculate the total
    subtotal = sum(price for _, price in items)
    discount_amount = subtotal * (discount / 100)
    tax_amount = (subtotal - discount_amount) * (tax_rate / 100)
    total = subtotal - discount_amount + tax_amount

    return {
        "subtotal": subtotal,
        "discount_amount": discount_amount,
        "tax_amount": tax_amount,
        "total": total
    }

## Test with valid inputs
shopping_cart = [
    ("Laptop", 1000),
    ("Mouse", 25),
    ("Keyboard", 45)
]

try:
    result = calculate_total_cost(shopping_cart, tax_rate=8.5, discount=10)
    print("Shopping Cart Total:")
    for key, value in result.items():
        print(f"  {key.replace('_', ' ').title()}: ${value:.2f}")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")

## Test with invalid item
try:
    invalid_cart = [
        ("Laptop", 1000),
        ("Mouse", "twenty-five"),  ## Invalid price
        ("Keyboard", 45)
    ]
    result = calculate_total_cost(invalid_cart)
    print(result)
except (TypeError, ValueError) as e:
    print(f"Error with invalid item: {e}")

저장하고 실행합니다.

python3 validate_args.py

출력:

Shopping Cart Total:
  Subtotal: $1070.00
  Discount Amount: $107.00
  Tax Amount: $81.86
  Total: $1044.86
Error with invalid item: Price of item 1 must be a number

이 함수는 다음을 통해 강력한 유효성 검사를 보여줍니다.

  1. 모든 입력의 유형을 확인합니다.
  2. 숫자 값의 범위를 검증합니다.
  3. 자세한 오류 메시지를 제공합니다.
  4. 선택적 매개변수에 적절한 기본값을 설정합니다.
  5. docstring 을 사용하여 예상 입력 및 반환 값을 문서화합니다.

함수에 철저한 유효성 검사를 구현하면 오류를 방지하고, 사용자에게 더 나은 피드백을 제공하며, 코드를 더 강력하고 유지 관리 가능하게 만들 수 있습니다.

완전한 애플리케이션 구축

이제 함수 인자를 처리하고 검증하는 다양한 기술을 배웠으므로 이러한 기술을 적용하여 간단하지만 완전한 애플리케이션을 구축해 보겠습니다. 함수 인자 처리에 대한 모범 사례를 보여주는 기본 지출 추적 시스템을 만들 것입니다.

애플리케이션 파일 만들기

지출 추적기를 위한 새 Python 파일을 만들어 보겠습니다.

  1. WebIDE 에서 "File" 메뉴를 클릭합니다.
  2. "New File"을 선택합니다.
  3. 파일 이름으로 expense_tracker.py를 입력합니다.
  4. "OK"를 클릭합니다.

지출 추적기 함수 설계

지출 추적기에는 지출 관리의 다양한 측면을 처리하는 여러 함수가 있습니다.

def create_expense(description, amount, category=None, date=None):
    """
    Create a new expense entry.

    Args:
        description (str): Description of the expense
        amount (float): The amount spent
        category (str, optional): Category of the expense
        date (str, optional): The date in YYYY-MM-DD format

    Returns:
        dict: An expense entry
    """
    ## Validate description
    if not isinstance(description, str):
        raise TypeError("Description must be a string")
    if not description:
        raise ValueError("Description cannot be empty")

    ## Validate amount
    if not isinstance(amount, (int, float)):
        raise TypeError("Amount must be a number")
    if amount <= 0:
        raise ValueError("Amount must be positive")

    ## Create the expense dictionary
    expense = {
        "description": description,
        "amount": float(amount),
        "category": category or "Uncategorized",
        "date": date or "Not specified"
    }

    return expense


def add_expense_to_list(expenses, **kwargs):
    """
    Add a new expense to the expenses list.

    Args:
        expenses (list): The list of expenses
        **kwargs: The expense details to be passed to create_expense

    Returns:
        list: The updated list of expenses
    """
    ## Validate the expenses list
    if not isinstance(expenses, list):
        raise TypeError("Expenses must be a list")

    ## Extract required arguments
    if "description" not in kwargs:
        raise ValueError("Expense description is required")
    if "amount" not in kwargs:
        raise ValueError("Expense amount is required")

    ## Create the expense and add it to the list
    expense = create_expense(
        kwargs["description"],
        kwargs["amount"],
        kwargs.get("category"),
        kwargs.get("date")
    )

    expenses.append(expense)
    return expenses


def get_total_expenses(expenses, category=None):
    """
    Calculate the total amount of expenses, optionally filtered by category.

    Args:
        expenses (list): The list of expenses
        category (str, optional): Filter by this category if provided

    Returns:
        float: The total amount
    """
    ## Validate the expenses list
    if not isinstance(expenses, list):
        raise TypeError("Expenses must be a list")

    ## Calculate the total
    if category:
        return sum(e["amount"] for e in expenses if e["category"] == category)
    else:
        return sum(e["amount"] for e in expenses)


def get_expense_summary(expenses):
    """
    Get a summary of expenses by category.

    Args:
        expenses (list): The list of expenses

    Returns:
        dict: A dictionary with categories as keys and total amounts as values
    """
    ## Validate the expenses list
    if not isinstance(expenses, list):
        raise TypeError("Expenses must be a list")

    ## Create the summary
    summary = {}
    for expense in expenses:
        category = expense["category"]
        if category in summary:
            summary[category] += expense["amount"]
        else:
            summary[category] = expense["amount"]

    return summary

지출 추적기 사용

이제 함수를 사용하여 일부 지출을 추적해 보겠습니다.

def print_expense_summary(summary):
    """Print a formatted summary of expenses by category."""
    print("\nExpense Summary by Category:")
    print("-" * 30)
    for category, amount in summary.items():
        print(f"{category}: ${amount:.2f}")
    print("-" * 30)
    print(f"Total: ${sum(summary.values()):.2f}")

## Initialize an empty expenses list
expenses = []

## Add some expenses
try:
    ## Add with required arguments only
    expenses = add_expense_to_list(
        expenses,
        description="Groceries",
        amount=45.75
    )

    ## Add with all arguments
    expenses = add_expense_to_list(
        expenses,
        description="Movie tickets",
        amount=25.00,
        category="Entertainment",
        date="2023-11-15"
    )

    ## Add another expense
    expenses = add_expense_to_list(
        expenses,
        description="Dinner",
        amount=65.40,
        category="Food",
        date="2023-11-14"
    )

    ## Add with default category
    expenses = add_expense_to_list(
        expenses,
        description="Gas",
        amount=35.80,
        date="2023-11-16"
    )

    ## Display all expenses
    print("All Expenses:")
    for i, expense in enumerate(expenses, 1):
        print(f"{i}. {expense['description']}: ${expense['amount']:.2f} " +
              f"({expense['category']}, {expense['date']})")

    ## Get and display the total
    total = get_total_expenses(expenses)
    print(f"\nTotal expenses: ${total:.2f}")

    ## Get and display expenses for a specific category
    food_total = get_total_expenses(expenses, "Food")
    print(f"Food expenses: ${food_total:.2f}")

    ## Get and display the summary
    summary = get_expense_summary(expenses)
    print_expense_summary(summary)

except (TypeError, ValueError) as e:
    print(f"Error: {e}")

오류 처리를 보여주는 코드를 추가해 보겠습니다.

## Try some invalid inputs
print("\nTesting error handling:")

try:
    ## Invalid expense description
    expenses = add_expense_to_list(expenses, description="", amount=10)
except ValueError as e:
    print(f"Caught error: {e}")

try:
    ## Invalid expense amount
    expenses = add_expense_to_list(expenses, description="Coffee", amount=-5)
except ValueError as e:
    print(f"Caught error: {e}")

try:
    ## Missing required argument
    expenses = add_expense_to_list(expenses, description="Coffee")
except ValueError as e:
    print(f"Caught error: {e}")

파일을 저장하고 실행합니다.

python3 expense_tracker.py

예상 출력:

All Expenses:
1. Groceries: $45.75 (Uncategorized, Not specified)
2. Movie tickets: $25.00 (Entertainment, 2023-11-15)
3. Dinner: $65.40 (Food, 2023-11-14)
4. Gas: $35.80 (Uncategorized, 2023-11-16)

Total expenses: $171.95
Food expenses: $65.40

Expense Summary by Category:
------------------------------
Uncategorized: $81.55
Entertainment: $25.00
Food: $65.40
------------------------------
Total: $171.95

Testing error handling:
Caught error: Description cannot be empty
Caught error: Amount must be positive
Caught error: Expense amount is required

애플리케이션 검토

지출 추적기는 몇 가지 중요한 개념을 보여줍니다.

  1. 인자 유효성 검사 (Argument validation): 각 함수는 인자가 예상되는 유형과 제약 조건을 충족하는지 확인합니다.

  2. 기본값 (Default values): categorydate와 같이 특정 인자를 선택 사항으로 만들기 위해 기본값을 사용합니다.

  3. 필수 인자 (Required arguments): descriptionamount와 같은 필수 정보의 경우 이러한 정보가 제공되고 유효한지 확인합니다.

  4. 키워드 인자 (Keyword arguments): add_expense_to_list 함수는 유연한 방식으로 지출 세부 정보를 허용하기 위해 **kwargs를 사용합니다.

  5. 오류 처리 (Error handling): 디버깅을 더 쉽게 하기 위해 의미 있는 오류 메시지와 함께 적절한 예외를 사용합니다.

  6. Docstrings: 각 함수에는 목적, 인자 및 반환 값을 설명하는 docstring 이 포함되어 있습니다.

이러한 기술을 적용하여 함수 인자를 안정적이고 사용자 친화적인 방식으로 처리하는 강력한 애플리케이션을 만들었습니다. 이 접근 방식은 버그를 방지하고, 코드 유지 관리성을 개선하며, 문제가 발생할 때 명확한 피드백을 제공하는 데 도움이 됩니다.

요약

이 튜토리얼에서는 Python 에서 누락되거나 유효하지 않은 함수 인자를 처리하기 위한 필수 기술을 배웠습니다.

  1. 기본 함수 인자 및 기본값 이해: 필수 인자, 기본값을 가진 선택적 인자, 키워드 인자를 포함한 다양한 유형의 함수 인자를 살펴보았습니다. 이러한 기초는 유연하고 사용자 친화적인 함수를 설계하는 데 도움이 됩니다.

  2. 가변 개수의 인자 처리: *args**kwargs를 사용하여 임의의 수의 인자를 허용할 수 있는 함수를 만드는 방법을 배웠으며, 이를 통해 함수를 다양한 사용 사례에 더 적응할 수 있도록 만들었습니다.

  3. 함수 인자 유효성 검사: 인자가 예상되는 유형과 제약 조건을 충족하는지 확인하기 위해 다양한 유효성 검사 기술을 구현하여 버그를 방지하고 명확한 오류 메시지를 제공하는 데 도움을 주었습니다.

  4. 완전한 애플리케이션 구축: 이러한 개념을 실제 지출 추적 애플리케이션을 구축하는 데 적용하여 적절한 인자 처리가 강력하고 유지 관리 가능한 코드로 이어진다는 것을 보여주었습니다.

이러한 기술은 신뢰할 수 있는 Python 코드를 작성하는 데 필수적입니다. 함수 인자를 적절하게 처리함으로써 더 유연하고 사용하기 쉬우며 오류가 발생할 가능성이 적은 함수를 만들 수 있습니다. Python 여정을 계속 진행하면서 이러한 기술은 예상치 못한 입력과 엣지 케이스를 적절하게 처리할 수 있는 더 정교한 애플리케이션을 구축하는 데 도움이 될 것입니다.