Skip to main content

tool to expose functionalities to multiple tools

Project description

ExposedFunctionality

ExposedFunctionality is a Python library designed to facilitate the interaction between backend code and frontend interfaces. It enables developers to expose backend methods and variables in a structured and secure way, making it easier to integrate with front-end systems or API endpoints. This library is particularly useful in scenarios where backend logic needs to be accessed or manipulated from a front-end application or through web API calls.

Features

  • Function Exposition: Expose backend functions with added metadata, such as parameter types, return types, and descriptions, making it easier for frontend applications to understand and use these functions.
  • Variable Exposition: Expose backend variables in a controlled manner, with support for type enforcement, default values, and change events.
  • Docstring Parsing: Automatically parse function docstrings to extract parameter and return value descriptions, further enriching the exposed method's metadata.
  • Type Safety: Enforce type checks on exposed variables and function parameters to reduce runtime errors and ensure data integrity.
  • Event Handling: Support for change events on exposed variables, allowing the frontend to react to changes in the backend state.
  • Middleware Integration: Apply middleware functions to exposed variables for additional processing or validation before setting their values.
  • Dynamic Addition: Dynamically add exposed functions and variables to instances or classes, enhancing flexibility in runtime object configuration.

Installation

To install ExposedFunctionality, use pip:

pip install exposedfunctionality

Usage

Exposing Functions

To expose a backend function, use the exposed_method decorator. This allows you to specify metadata such as the method's name, input parameters, and output parameters.

from exposedfunctionality import exposed_method

@exposed_method(name="calculate_sum", inputs=[{"name": "a", "type": "int"}, {"name": "b", "type": "int"}], outputs=[{"name": "result", "type": "int"}])
def add(a, b):
    """Calculate the sum of two numbers."""
    return a + b

To retrieve exposed methods from an object (either an instance or a class), you can use the get_exposed_methods function provided by the exposedfunctionality package. This function scans an object for methods that have been decorated with @exposed_method and collects them into a dictionary, making it easy to access and utilize these methods programmatically, such as when dynamically generating API endpoints or interfaces.

Example

Consider the following class with an exposed method:

from exposedfunctionality import exposed_method, get_exposed_methods

class MathOperations:
    @exposed_method(name="add", inputs=[{"name": "a", "type": "int"}, {"name": "b", "type": "int"}], outputs=[{"name": "sum", "type": "int"}])
    def add_numbers(self, a, b):
        """Add two numbers."""
        return a + b

To retrieve the exposed methods from an instance of MathOperations, you would do the following:

math_operations = MathOperations()

exposed_methods = get_exposed_methods(math_operations)

for method_name, (method, metadata) in exposed_methods.items():
    print(f"Method Name: {method_name}")
    print(f"Metadata: {metadata}")
    print(f"Function: {method}")
    print("-----")

This will output something like:

Method Name: add
Metadata: {'name': 'add', 'input_params': [{'name': 'a', 'type': 'int', 'positional': True}, {'name': 'b', 'type': 'int', 'positional': True}], 'output_params': [{'name': 'sum', 'type': 'int'}], 'docstring': {'summary': 'Add two numbers.', 'original': 'Add two numbers.', 'input_params': [], 'output_params': [], 'exceptions': {}}}
Function: <bound method MathOperations.add_numbers of <__main__.MathOperations object at 0x7fcd1830f1f0>>
-----

The get_exposed_methods function is particularly useful for frameworks or libraries that need to dynamically discover which methods are available for external access, such as in web frameworks for automatically generating API routes or in GUI applications for dynamically creating user interface elements based on the backend logic.

Exposing Variables

Expose backend variables using the ExposedValue descriptor. This enables type checking, default values, and change event handling.

from exposedfunctionality.variables import ExposedValue

class Calculator:
    result = ExposedValue("result", default=0, type_=int)

calculator = Calculator()
calculator.result = 5  # Sets the result and enforces type checking

Listening to Variable Changes

You can listen to changes on an exposed variable by attaching an OnChangeEvent:

def on_result_change(new_value, old_value):
    print(f"Result changed from {old_value} to {new_value}")

calculator.result.add_on_change_callback(on_result_change)
calculator.result = 10  # Triggers the on_result_change callback

Applying Middleware

Use middleware functions to process or validate variable values before they are set:

from exposedfunctionality.variables.middleware import min_max_clamp

class RestrictedCalculator:
    result = ExposedValue("result", default=0, type_=int, valuechecker=[min_max_clamp],max=100)

restricted_calculator = RestrictedCalculator()
restricted_calculator.result = 150  # The value will be clamped to 100

Contributing

Contributions are welcome! Please feel free to submit pull requests, report bugs, or suggest features.

License

This project is licensed under the MIT License. See the LICENSE file for 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

exposedfunctionality-1.0.1.tar.gz (68.1 kB view details)

Uploaded Source

Built Distribution

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

exposedfunctionality-1.0.1-py3-none-any.whl (28.9 kB view details)

Uploaded Python 3

File details

Details for the file exposedfunctionality-1.0.1.tar.gz.

File metadata

  • Download URL: exposedfunctionality-1.0.1.tar.gz
  • Upload date:
  • Size: 68.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for exposedfunctionality-1.0.1.tar.gz
Algorithm Hash digest
SHA256 2638375ff805c4b51e8acf06bc0478a80c370cf64d5dc0dcc45f21d516d65470
MD5 52d0f988761aa2037c46071cf7e7ac0f
BLAKE2b-256 8675691ad2224a26f8e394bdb931b08de586a91bf527e8c92c92ccb1a49fe518

See more details on using hashes here.

Provenance

The following attestation bundles were made for exposedfunctionality-1.0.1.tar.gz:

Publisher: version_publish_main.yml on JulianKimmig/exposedfunctionality

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file exposedfunctionality-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for exposedfunctionality-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 99a5fb6771f1e81612163f93bc3a945afb1c8d167369b1a77a5a4d43a4211ad6
MD5 190f8be81b8b63c98ecfe07b2f2f2e05
BLAKE2b-256 adaa5a06beb4c421e56c6131cc222263c3328b5a5001d4aed97a3e8a8a158333

See more details on using hashes here.

Provenance

The following attestation bundles were made for exposedfunctionality-1.0.1-py3-none-any.whl:

Publisher: version_publish_main.yml on JulianKimmig/exposedfunctionality

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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