magic-filter
magic-filter is a lightweight Python library designed to simplify conditional logic, particularly useful in event-driven programming like Telegram bots (e.g., aiogram). It provides a fluent, declarative syntax for building complex filtering expressions using the `F` object, allowing developers to write more readable and concise conditions. It is currently at version 1.0.12 and sees active, though not strictly regular, development with several minor releases annually.
Warnings
- breaking The `extract` operation for negative results (conditions not met) now returns `None` instead of `False`. Code that explicitly checked for `False` will need adjustment.
- gotcha The `__bool__` method for `F` objects now always returns `True`. This means `if F.attribute:` will always evaluate to true, regardless of whether `F.attribute` would pass a condition. This can be misleading if expecting conditional evaluation.
- breaking MagicFilter instances can no longer be used as iterable objects. Attempting to iterate over an `F` object will now raise an error.
- gotcha Starting from 1.0.5, `TypeError` and `ValueError` are suppressed when calling function operations on `F` objects. This means operations that previously might have failed with an error (e.g., `F.attribute.len()` on `None`) will now silently fail the filter condition.
Install
-
pip install magic-filter
Imports
- F
from magic_filter import F
Quickstart
from magic_filter import F
data = {"text": "Hello World", "user": {"id": 123, "is_bot": False}}
# Define filters using the F object
is_admin = F.user.id == 123
starts_with_H = F.text.startswith("H")
# Apply a single filter
print(f"Is admin: {is_admin(data)}")
# Combine filters with logical operators
complex_filter = is_admin & starts_with_H & ~F.user.is_bot
print(f"Complex filter result: {complex_filter(data)}")
# Using with lists
numbers = [1, 5, 10, 3, 7]
gt_5 = F > 5
filtered_numbers = [num for num in numbers if gt_5(num)]
print(f"Numbers greater than 5: {filtered_numbers}")