Skip to main content

This is an expression language python package.

Project description

Dilemma Expression Language

CI codecov PyPI version Python 3.12

A secure, powerful expression evaluation engine for Python applications that makes complex logical expressions readable and maintainable.

Why Dilemma?

Instead of writing complex Python conditionals like this:

if (user.get('profile', {}).get('age', 0) >= 18 and 
    user.get('subscription', {}).get('status') == 'active' and
    datetime.now() - user.get('last_login', datetime.min) < timedelta(days=30)):
    # grant access

Write this:

from dilemma import evaluate

if evaluate("user.profile.age >= 18 and user.subscription.status == 'active' and user.last_login within 30 days", context):
    # grant access

Features

  • Secure evaluation - No arbitrary code execution, only safe expressions
  • Rich data access - Navigate nested dictionaries and lists with ease
  • Date/time operations - Natural language date comparisons
  • Multiple resolvers - JsonPath, JQ, and basic dictionary lookup
  • Performance optimized - Compile expressions once, evaluate many times
  • Type safe - Built-in type checking and validation

Quick Start

pip install dilemma
from dilemma import evaluate

# Basic arithmetic and logic
result = evaluate("2 * (3 + 4)")  # Returns 14
result = evaluate("age >= 18 and status == 'active'", {"age": 25, "status": "active"})

# Date operations
result = evaluate("user.last_login within 7 days", context)
result = evaluate("subscription.end_date is $future", context)

# Complex data access
result = evaluate("user.permissions contains 'admin'", context)
result = evaluate("`users[].roles[] | select(. == 'admin')` | length > 0", context)

Language Features

Data Access Patterns

# Dot notation for nested objects
"user.profile.settings.theme == 'dark'"

# Natural possessive syntax  
"user's subscription's status == 'premium'"

# Array/list access
"users[0].name == 'Alice'"

# Check membership
"'admin' in user.roles"
"user.permissions contains 'read'"

Date and Time Operations

# Relative time checks
"user.created_at within 30 days"
"order.shipped_date older than 1 week"

# State comparisons
"subscription.expires is $future"
"last_backup is $past"
"meeting.date is $today"

# Date comparisons
"start_date before end_date"
"event.date same_day_as $now"

Advanced JQ Integration

For complex data manipulation, use JQ expressions in backticks:

# Filter and transform arrays
evaluate('`users[] | select(.active == true) | .name`')

# Mathematical operations on arrays
evaluate('`sales[].amount | add` > 10000')

# Complex conditionals
evaluate('`products[] | select(.price > 100 and .category == "electronics") | length` > 5')

Performance Optimization

For repeated evaluations, compile expressions once:

from dilemma import compile_expression

# Compile once
eligibility_check = compile_expression(
    "user.age >= 18 and user.subscription.active and user.last_login within 30 days"
)

# Evaluate many times with different contexts
for user_data in users:
    if eligibility_check.evaluate(user_data):
        send_premium_content(user_data)

Error Handling

Dilemma provides clear, actionable error messages:

try:
    result = evaluate("user.invalidfield == 'test'", context)
except ExpressionError as e:
    print(f"Expression error: {e}")
    # Suggests available fields and common fixes

Use Cases

  • Form validation rules - "email matches '^[^@]+@[^@]+$' and age >= 13"
  • Business logic - "order.total > 100 and customer.tier == 'premium'"
  • Access control - "user.roles contains 'admin' or resource.owner == user.id"
  • Data filtering - "created_at within 24 hours and status == 'pending'"
  • Workflow conditions - "approval.status == 'approved' and budget.remaining >= cost"

Safety & Security

  • ✅ No arbitrary Python code execution
  • ✅ No access to imports or builtins
  • ✅ Sandboxed evaluation environment
  • ✅ Input validation and sanitization
  • ✅ Memory and complexity limits

Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

License

MIT License - see 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

dilemma-0.2.0.tar.gz (112.8 kB view details)

Uploaded Source

Built Distribution

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

dilemma-0.2.0-py3-none-any.whl (36.9 kB view details)

Uploaded Python 3

File details

Details for the file dilemma-0.2.0.tar.gz.

File metadata

  • Download URL: dilemma-0.2.0.tar.gz
  • Upload date:
  • Size: 112.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for dilemma-0.2.0.tar.gz
Algorithm Hash digest
SHA256 f0a586db2485368d720f7f9a657c33fe3ab1f10c7e847760a3ce27ae1e13ed96
MD5 74141f60b32907ec655b54a265285b7b
BLAKE2b-256 c858d66ffce49cb013134e4cd57875de83fee4991e0da17de305895e241fe09c

See more details on using hashes here.

File details

Details for the file dilemma-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: dilemma-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 36.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for dilemma-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f97c00f25a1c0128dcb37e6e9e2c3e34f111ec710c4eb4c435e4922122b10e72
MD5 a8bc4e32851d70c2c4a5fc2be65a3ff6
BLAKE2b-256 2e4d1e0837b22daf9be712191b5173e3acd45b4aa1234a02deef8d56c61733da

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