Skip to main content

Overloading Utilities

Project description

pyloadover

Function Overloading Made Easy in Python

pyloadover is a Python package that enables function overloading in Python. It allows you to define multiple implementations of a function with different signatures and automatically selects the appropriate one based on the arguments provided. Additionally, it offers advanced features like custom ID generation, validation, and group management for overloaded functions.


Installation

Install pyloadover using pip:

pip install pyloadover

NOTE: pyloadover requires Python3.8 or higher.


Quick Start

Basic Overloading

Function overloading allows you to define multiple implementations of a function with different signatures. pyloadover automatically selects the appropriate implementation based on the arguments provided.

Here’s how you can use pyloadover to overload functions:

from pyloadover import overload


@overload
def greet():
    return "Hello, World!"


@overload
def greet(name: str):
    return f"Hello, {name}!"


@overload
def greet(first_name: str, last_name: str):
    return f"Hello, {first_name} {last_name}!"


# Calling the overloaded functions
print(greet())  # Output: Hello, World!
print(greet("Alice"))  # Output: Hello, Alice!
print(greet("Alice", "Smith"))  # Output: Hello, Alice Smith!

If no matching function is found, a NoMatchingSignatureError is raised:

print(greet(1, 2, 3))  # Raises: NoMatchingSignatureError

Configuration

You can configure pyloadover using the configure function. For example, you can enforce unique function signatures and customize how function IDs are generated:

  • propagate: Applies the configuration to all existing and future groups.
  • function_id_generator: Determines how function IDs are generated (e.g., using fully qualified names). When no group is explicitly specified, these IDs are used to automatically assign functions to their respective groups.
  • group_function_validators: Ensures functions meet specific criteria when added to a group (e.g., unique signatures).
from pyloadover import overload, configure, FullyQualifiedNameIdGenerator, UniqueSignaturesValidator


@overload
def greet():
    return "Hello, World!"


# Configure pyloadover
configure(
    propagate=True,  # Propagate configuration to all groups
    function_id_generator=FullyQualifiedNameIdGenerator(),  # Use fully qualified names as IDs
    group_function_validators=[UniqueSignaturesValidator()]  # Enforce unique signatures
)


# Attempting to register a duplicate signature will raise an error
@overload
def greet():
    return "Hello again!"
SignatureExistsError: Function 'main.greet' with signature () already exists in group 'main.greet'

Function Groups

pyloadover allows you to organize overloaded functions into groups. A group is a collection of functions that share the same name but have different signatures.

Creating and Using Groups

You can create and manage groups in three ways:

Method 1: Using get_or_create_group

from pyloadover import get_or_create_group

greet_group = get_or_create_group("greet")


@greet_group
def greet(name: str):
    return f"Hello, {name}!"

Method 2: Using overloader

from pyloadover import overloader


@overloader("greet")
def greet(first_name: str, last_name: str):
    return f"Hello, {first_name} {last_name}!"

Method 3: Using the Dynamic Overload Builder Syntax

import pyloadover


@pyloadover.greet
def greet(first_name: str, middle_name: str, last_name: str):
    return f"Hello, {first_name} {middle_name} {last_name}!"

Calling Functions in a Group

You can call functions in a group using their arguments:

print(greet("Alice"))  # Output: Hello, Alice!
print(greet("Alice", "Smith"))  # Output: Hello, Alice Smith!
print(greet("Alice", "Marie", "Smith"))  # Output: Hello, Alice Marie Smith!

You can also call functions by using their group:

greet_group.call_function_by_arguments("Alice")  # Output: Hello, Alice!
greet_group.find_single_function_by_arguments("Alice")("Alice")  # Output: Hello, Alice!

Advanced Features

Custom ID Generators

ID generators determine how functions are identified and grouped. pyloadover provides two built-in generators:

  • FullyQualifiedNameIdGenerator: Uses the function’s module and qualified name as the ID.
  • NameIdGenerator: Uses the function’s name as the ID.

You can also create custom ID generators:

from pyloadover import FunctionIdGenerator, FunctionContext


class CustomIdGenerator(FunctionIdGenerator):
    def generate_id(self, context: FunctionContext) -> str:
        return f"custom_{context.function.name}"

Custom Validators

Validators ensure that functions meet specific criteria when added to a group. pyloadover provides two built-in validators:

  • EqualIdsValidator: Ensures the function’s ID matches the group’s ID.
  • UniqueSignaturesValidator: Ensures no two functions in a group have the same signature.

You can create custom validators:

from pyloadover import GroupFunctionValidator, GroupContext, Function


class CustomValidator(GroupFunctionValidator):
    def validate_function(self, group_context: GroupContext, function: Function):
        if "admin" in function.context.name:
            raise ValueError("Admin functions are not allowed!")

Default Configuration

By default, pyloadover is configured as follows:

configure(
    function_id_generator=FullyQualifiedNameIdGenerator(),
    group_function_validators=[EqualIdsValidator(), UniqueSignaturesValidator()]
)

Contributing

If you’d like to contribute to pyloadover, feel free to open an issue or submit a pull request on GitHub.


License

pyloadover is licensed under the MIT License. See LICENSE for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyloadover-4.0.1.tar.gz (7.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyloadover-4.0.1-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file pyloadover-4.0.1.tar.gz.

File metadata

  • Download URL: pyloadover-4.0.1.tar.gz
  • Upload date:
  • Size: 7.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.0.1 CPython/3.13.1 Linux/6.8.0-1020-azure

File hashes

Hashes for pyloadover-4.0.1.tar.gz
Algorithm Hash digest
SHA256 6274807e4ca44d45512bbce4c527ab3d0f207143f2cf9deb5a5111a45e45cb2a
MD5 504ca755d349ba6e9be3bc746ab0e9c0
BLAKE2b-256 478bfba1a804d6afcfe49bd5b2ecbba36829b24df3756a2e50076c288910bd00

See more details on using hashes here.

File details

Details for the file pyloadover-4.0.1-py3-none-any.whl.

File metadata

  • Download URL: pyloadover-4.0.1-py3-none-any.whl
  • Upload date:
  • Size: 10.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.0.1 CPython/3.13.1 Linux/6.8.0-1020-azure

File hashes

Hashes for pyloadover-4.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a3945030db61377504242e00f69eb1b1e4c6aa97e244d7aeb9622f49c594b954
MD5 97df871c1c595dd905e95937442a2767
BLAKE2b-256 635dacd2a7efa44a0f6cf433e92699aa5f1279ab37f9eaa74989a1caaaf40df1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page