Skip to main content

Simple and readable Pure Python callbacks!

Project description

callpyback

Python Versions Build Status Coverage Status PyPI version Known Vulnerabilities Maintainability Issues License: MIT Code style: black  Repo Size Downloads Project Status: Active Commit activity

Description

"callpyback" is a comprehensive Python library designed to help developers add callbacks to their functions with ease. It comes with a range of powerful features that make it easy to customize the behavior of your functions in different stages of their execution.

You can specify callbacks for on_call, on_success, on_failure, and on_end, and customize the default return value from the decorated function. Additionally, you can pass local scope variables of the decorated function to the on_end callback and define expected exceptions to trigger the on_failure callback. If desired, you can also omit callbacks, falling back to default behavior, and choose which parameters of the callback function to use. Furthermore, with the @background_callback decorator, you can execute callbacks on the background, making it easier to manage concurrency in your code.

Features

  • Support on_call, on_success, on_failure and on_end callbacks
  • Pass decorated function **kwargs and function itself to callbacks
  • Option to specify default return from the decorated function
  • Option to pass local scope variables of the decorated function to the on_end callback
  • Option to specify exception classes to be expected and invoke on_failure callback
  • Option to omit callbacks - default callback
  • Option to omit callback's function parameters (specify only those which you need)
  • Option to execute callbacks on the background (new thread) via @background_callpyback decorator

Instalation

Package is currently available under the same name at PyPI version.

pip install callpyback

(back to top)

Usage

! important note !

In latest version of callpyback, when declaring callback functions, following rules must be obeyed:

a) on_call() callback MUST eitheraccept no parameters or combination of the following:

  • func - will receive reference to decorated function
  • func_kwargs - will receive parameters passed to the function decorated with CallPyBack

b) on_success() callback MUST either accept no parameters or combination of the following:

  • func - will receive reference to decorated function
  • func_result - will receive return value of the function decorated with CallPyBack
  • func_kwargs - will receive parameters passed to the function decorated with CallPyBack

c) on_failure() callback MUST either accept no parameters or combination of the following:

  • func - will receive reference to decorated function
  • func_exception - will receive exception raised by the function decorated with CallPyBack
  • func_kwargs - will receive parameters passed to the function decorated with CallPyBack

d) on_end() callback MUST either accept no parameters or combination of the following:

  • func - will receive reference to decorated function
  • func_result - will receive return value of the function decorated with CallPyBack
  • func_exception - will receive exception raised by the function decorated with CallPyBack
  • func_kwargs - will receive parameters passed to the function decorated with CallPyBack
  • func_scope_vars - will receive local variables of the function decorated with CallPyBack, whose names were specified in the pass_vars decorator parameter.

These rules are enforced to allow omitting parameters in the callback function. This is useful when some of these parameters are not needed for the callback function. If those rules are not obeyed, error will be raised during the initialization of the CallPyBack decorator class.

(back to top)

Prerequisites

Consider following callbacks:

def on_call(func, func_kwargs):
    print('-----ON CALL CALLBACK-----')
    func_kwargs_repr = ', '.join(f'{key}={val}' for key, val in func_kwargs.items())
    print(f'Function `{func.__name__}` called with parameters: {func_kwargs_repr}.\n')

@background_callpyback
def on_success(func, func_result, func_kwargs):
    print('-----ON SUCCESS CALLBACK-----')
    func_kwargs_repr = ', '.join(f'{key}={val}' for key, val in func_kwargs.items())
    print(f'Function `{func.__name__}` successfully done with a result: {func_result}.')
    print(f'Was called with parameters: {func_kwargs_repr}\n')

@background_callpyback
def on_failure(func, func_exception, func_kwargs):
    print('-----ON FAILURE CALLBACK-----')
    func_kwargs_repr = ', '.join(f'{key}={val}' for key, val in func_kwargs.items())
    print(f'Function `{func.__name__} failed with an error: {func_exception}!')
    print(f'Was called with parameters: {func_kwargs_repr}\n')

@background_callpyback
def on_end(func, func_result, func_exception, func_kwargs, func_scope_vars):
    print('-----ON END CALLBACK-----')
    func_kwargs_repr = ', '.join(f'{key}={val}' for key, val in func_kwargs.items())
    func_scope_vars_repr = ', '.join(f'{key}={val}' for key, val in func_scope_vars.items())
    if func_exception:
        print(f'Function `{func.__name__} failed with an error: {func_exception}!')
    else:
        print('No exception was raised')
    print(f'Function `{func.__name__}` done with a result: {func_result}.')
    print(f'Was called with parameters: {func_kwargs_repr}')
    print(f'Local variables of the function: {func_scope_vars_repr}')

and initialization of a decorator:

custom_callpyback = CallPyBack(
    on_call=on_call,
    on_success=on_success,
    on_failure=on_failure,
    on_end=on_end,
    default_return='default', 
    exception_classes=(RuntimeError,),
    pass_vars=('a',)
)

These will be used in following examples:

1. Decorated function executes without error

@custom_callpyback
def method(x, y, z=None):
    a = 42
    return x + y

result = method(1, 2)
print(f'Result: {result}')

will result in

-----ON CALL CALLBACK-----
Function `method` called with parameters: x=1, y=2, z=None.

Result: 3

-----ON SUCCESS CALLBACK-----
Function `method` successfully done with a result: 3.
Was called with parameters: x=1, y=2, z=None

-----ON END CALLBACK-----
No exception was raised
Function `method` done with a result: 3.
Was called with parameters: x=1, y=2, z=None
Local variables of the function: a=42

on_success and on_end will be executed on the background thread, while on_call will be executed in a blocking way and on_failure will not be called.

2. Decorated function raises an error

@custom_callpyback
def method(x, y, z=None):
    a = 42
    raise RuntimeError("some error")

result = method(1, 2)
print(f'Result: {result}')

will result in

-----ON CALL CALLBACK-----
Function `method` called with parameters: x=1, y=2, z=None.

-----ON FAILURE CALLBACK-----
Function `method` failed with an error: some error!
Was called with parameters: x=1, y=2, z=None

-----ON END CALLBACK-----
Function `method` failed with an error: some error!
Function `method` done with a result: default.
Was called with parameters: x=1, y=2, z=None
Local variables of the function: a=42

on_failure and on_end will be executed on the background thread, while on_call will be executed in a blocking way and on_success will not be called.

(back to top)

Roadmap

  • Add Changelog
  • Support on_call, on_success, on_failure and on_end callbacks
  • Option to specify default return from the decorated function
  • Option to pass local scope variables of the decorated function to the on_end callback
  • Option to specify exception classes to be expected and invoke on_failure callback
  • Option to omit callbacks - default callback
  • Option to omit callback's function parameters (specify only those which you need)
  • Option to execute callbacks on the background (new thread) via @background_callpyback decorator
  • Option to pass decorated function reference to all callbacks
  • To be determined...

See the open issues for a full list of proposed features (and known issues).

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/feature-name)
  3. Commit your Changes (git commit -m 'Add some FeatureName')
  4. Push to the Branch (git push origin feature/feature-name)
  5. Open a Pull Request
  6. Let us review your magical feature

(back to top)

License

Distributed under the MIT License. See LICENSE.txt for more information.

(back to top)

Contact

Samuel Gregorovič - samuel-gregorovic - samuelgregorovic@gmail.com

Project Link: https://github.com/samuelgregorovic/callpyback

(back to top)

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

callpyback-1.2.1.tar.gz (16.5 kB view details)

Uploaded Source

File details

Details for the file callpyback-1.2.1.tar.gz.

File metadata

  • Download URL: callpyback-1.2.1.tar.gz
  • Upload date:
  • Size: 16.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 colorama/0.4.4 importlib-metadata/4.6.4 keyring/23.5.0 pkginfo/1.8.2 readme-renderer/34.0 requests-toolbelt/0.9.1 requests/2.25.1 rfc3986/1.5.0 tqdm/4.57.0 urllib3/1.26.5 CPython/3.10.6

File hashes

Hashes for callpyback-1.2.1.tar.gz
Algorithm Hash digest
SHA256 973473e5431d240021ac296e2f338aac2d743a3190f9bea43d5b09f953eb20ad
MD5 56ce335ea9a3ebc372ce53d201fb95ec
BLAKE2b-256 50d131ada295099e3a315f8f24b8f9f671e7fa6e12ccdafc603921055aeb8157

See more details on using hashes here.

Supported by

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