Mayhap: Where your functions may happen... or not.
Embrace the uncertainty in your code execution!
Mayhap is a whimsical Python package that allows you to introduce controlled randomness into your function executions. By decorating your functions with @maybe, you can specify various probability distributions to determine whether a function should execute or not. It's perfect for simulations, testing, or just adding a bit of unpredictability to your code.
- Multiple Distributions: Choose from uniform, weighted, normal, exponential, Bernoulli distributions, or define your own custom logic.
- Easy Integration: Simply decorate your functions with
@maybeand specify the desired distribution and parameters. - Flexible Probability Control: Tailor the execution probability to fit your specific needs.
- Optional Verbosity: Control whether skipped executions print a message with the
verboseflag.
Install Mayhap using pip:
pip install mayhapHere's how you can use Mayhap in your projects:
Execute a function with a fixed probability.
from mayhap import maybe
@maybe(distribution='uniform', probability=0.7)
def greet(name):
print(f"Hello, {name}!")
greet('Alice') # Has a 70% chance to print the greeting.Assign different weights to execution outcomes.
@maybe(distribution='weighted', weights=[3, 1])
def farewell(name):
print(f"Goodbye, {name}!")
farewell('Bob') # 'Goodbye, Bob!' is three times more likely to print than not.Execution probability follows a normal (Gaussian) distribution.
@maybe(distribution='normal', mean=0.5, stddev=0.1)
def announce(event):
print(f"Announcing {event}!")
announce('the event') # Execution probability is centered around 50%.Execution probability decreases exponentially over time.
@maybe(distribution='exponential', lambd=1.0)
def notify(user):
print(f"Notification sent to {user}.")
notify('Charlie') # Execution probability decreases over time.Execute based on a Bernoulli trial with probability p.
@maybe(distribution='bernoulli', p=0.3)
def alert():
print("Alert triggered!")
alert() # Has a 30% chance to trigger the alert.Define your own logic for execution probability.
def custom_logic():
# Custom conditions for execution
return some_external_condition_check()
@maybe(distribution='custom', custom_func=custom_logic)
def process():
print("Processing data.")
process() # Executes based on custom logic.You can control whether skipped function calls print a message with the verbose flag.
@maybe(distribution='uniform', probability=0.5, verbose=False)
def silent():
print("Might run... but won't explain if not.")Contributions are welcome! If you'd like to improve Mayhap or add new features, please fork the repository and submit a pull request. For major changes, open an issue first to discuss your ideas.
This project is licensed under the GPL-3.0-only License.
See the LICENSE file for more details.
Mayhap: Embrace the uncertainty in your code execution!