Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Functions, Docstrings/shaare/r7T2Ww

  • python
  • python

Functions

Functions package reusable code into named blocks, improving modularity, readability, and testability. They prevent duplication (DRY) and make scripts easier to maintain.

Defining a Function (def)

Use def name(params): followed by an indented block. An optional """docstring""" explains purpose, parameters, and return value.

def greet_user(name):
    """Greets the user by name.

    Args:
        name (str): The user to greet
    """

    print(f"Hello, {name}!")

greet_user("Alice")

Calling a Function

Invoke via name(args). Control jumps into the function body and (optionally) returns a value back.

import random

def random_number(min_val, max_val):
    """Generates an integer between min_val and max_val

    Args:
        min_val (int): The lower boundary of the interval
        max_val (int): The upper boundary of the interval

    Returns:
        int: The generated random number
    """
    return random.randint(min_val, max_val)

generated_number = random_number(0, 10)
print(f"Generated number: {generated_number}")

Parameters vs Arguments

Summary: Parameters are named in the def signature; arguments are the actual values passed when calling.

generated_number = random_number(-1, 100)

Positional vs Keyword Arguments

Positional args match by order; keyword args match by name and can be out of order. Positional arguments must come first.

def check_service_status(service_name, expected_status):
    print(f"Checking {service_name} for {expected_status}...")
    return True

check_service_status("nginx", "running")
check_service_status("running", "nginx")

check_service_status(service_name="nginx", expected_status="running")
check_service_status(expected_status="running", service_name="nginx")

# Positional arguments must come before keyword arguments
# check_service_status(service_name="nginx", "running") # Uncommenting raises a SyntaxError

Default Parameter Values

It's possible to give parameters default values in the signature (param=default), making them optional.

def connect(host, port=22, timeout=30):
    print(f"Connect to host {host} on port {port} (timeout {timeout})")

connect("web01")
connect("web02", 443, 60)

# When wanting to set the value of timeout but use the default value of port
# We need to use keyword arguments, since positional arguments would be
# incorrectly mapped

# Bad exaple - see how port is set to 60 and timeout remains 30
connect("web03", 60)

# Good example - both values are set as we expect
connect("web03", timeout=60)

Docstrings – Documenting Functions

The first string in a function is its docstring, explaining purpose, Args: and Returns:. Used by help() and IDEs. Observing the following conventions is considered good practice:

  1. One-line summary
  2. Blank line
  3. Detailed description (optional)
  4. Args: section for parameters
  5. Returns: section for return values
  6. Raises: section for exceptions
import socket

def check_port(host, port, timeout=5):
    """Checks if a TCP port is open on a given host.

    Args:
        host (str): Hostname or IP address.
        port (int): TCP port number.
        timeout (int, option): Connection timeout in seconds. Defaults to 5.

    Returns:
        bool: True if the port is open, False otherwise.
    """

    try:
        with socket.create_connection((host, port), timeout):
            return True
    except Exception:
        return False

print(check_port("www.google.com", 443))

# Port 22 is not open, should return False
print(check_port("www.google.com", 22))

# Host does not exist, should return False
print(check_port("www.afbdoaubfdoabdfoubaf.com", 22))
2 months ago Permalink
cluster icon
  • List : Lists (list) Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation. Characteristic...
  • Parametrized Tests : Parametrized Tests Introduction Often, we need to test the same logic with different inputs and outputs, such as validating various IP address or hos...
  • Exceptions : Common Built‑in Exceptions Python ships with a rich hierarchy of exception classes; most automation errors fall into a small, predictable subset. A...
  • Handling Errors and Status Codes : Handling Errors and Status Codes HTTP status codes communicate the outcome of an API request, and handling them correctly is key to robust automation...
  • Classes and Objects : Classes and Objects Beyond Built-ins: Python lets you define your own data types using class. Class: A blueprint or template for creating objects. De...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community