pyspecification 1.0.0__tar.gz → 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,12 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pyspecification
3
- Version: 1.0.0
3
+ Version: 2.0.1
4
4
  Summary: A lightweight, typed Python library for composing business rules as reusable, executable predicates.
5
5
  Author: aaltatan
6
6
  Author-email: aaltatan <a.altatan@gmail.com>
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
9
9
  Classifier: Operating System :: OS Independent
10
- Requires-Dist: pydantic==2.5.3
11
10
  Requires-Python: >=3.12
12
11
  Project-URL: Homepage, https://github.com/aaltatan/pyspecification
13
12
  Project-URL: Issues, https://github.com/aaltatan/pyspecification/issues
@@ -25,7 +24,7 @@ This project was inspired by the work and ideas shared by [ArjanCodes](https://g
25
24
  - predicates compose with `&`, `|`, and `~`
26
25
  - registry-based registration keeps rules organized
27
26
  - structured rule definitions can be compiled from dictionaries or JSON-like payloads
28
- - generated schemas make rule metadata portable and machine-readable
27
+ - structured rule definitions make rule metadata portable and machine-readable
29
28
 
30
29
  It is especially useful for filtering, validation, authorization checks, and declarative rule engines without introducing a heavy framework.
31
30
 
@@ -68,7 +67,6 @@ This keeps your logic:
68
67
  - Registry pattern for rule registration and lookup
69
68
  - Custom argument processors for coercion and normalization
70
69
  - `PredicateCompiler` for compiling structured rule dictionaries into executable predicates
71
- - `RuleSchema` validation for declarative rule payloads
72
70
  - JSON schema generation for rule arguments and return types
73
71
  - Support for both logical and bitwise operator modes
74
72
  - Hidden rules and custom naming for internal/private rule registration
@@ -251,7 +249,7 @@ One of the strongest real-world use cases is turning rule definitions into SQLAl
251
249
  ```python
252
250
  from typing import Any
253
251
 
254
- from pyspecification import ObjectRulesRegistry, Predicate, PredicateCompiler, RuleSchema
252
+ from pyspecification import ObjectRulesRegistry, Predicate, PredicateCompiler
255
253
  from sqlalchemy import ColumnElement, and_, create_engine, or_
256
254
  from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
257
255
 
@@ -336,11 +334,13 @@ filter_rule_data = {
336
334
  ],
337
335
  }
338
336
 
339
- predicate = compiler.compile(RuleSchema(**filter_rule_data).model_dump())
337
+ predicate = compiler.compile(filter_rule_data)
338
+ # is_admin() | age__ge(18)
339
+ # User.is_admin | User.age >= 18
340
340
 
341
341
  with SessionLocal() as session:
342
342
  users = session.query(User).filter(predicate(User)).all()
343
- print([user.name for user in users])
343
+ print([user.name for user in users]) # ['Abdullah', 'Bob', 'Charlie', 'Eve']
344
344
  ```
345
345
 
346
346
  This pattern is especially useful when you want:
@@ -354,6 +354,140 @@ This pattern is especially useful when you want:
354
354
 
355
355
  ---
356
356
 
357
+ ### 6. Django ORM integration example
358
+
359
+ This example demonstrates how to use `pyspecification` with Django models.
360
+ `pyspecification` does not import Django or provide a Django-specific adapter;
361
+ the rules return Django `Q` objects, while the existing bitwise predicate
362
+ composition supplies `&`, `|`, and `~` support.
363
+
364
+ ```python
365
+ # models.py
366
+ from typing import Any, Self
367
+
368
+ from django.db import models
369
+ from pyspecification import Predicate
370
+
371
+
372
+ class EmployeeQuerySet(models.QuerySet):
373
+ def filter_by_rule(self, rule: Predicate[Any, models.Q]) -> Self:
374
+ return self.filter(rule(Employee))
375
+
376
+
377
+ class EmployeeManager(models.Manager):
378
+ def get_queryset(self) -> EmployeeQuerySet:
379
+ return EmployeeQuerySet(self.model, using=self._db)
380
+
381
+ def filter_by_rule(self, rule: Predicate[Any, models.Q]) -> EmployeeQuerySet:
382
+ return self.get_queryset().filter_by_rule(rule)
383
+
384
+
385
+ class Employee(models.Model):
386
+ name = models.CharField(max_length=100)
387
+ age = models.IntegerField()
388
+ is_admin = models.BooleanField(default=False)
389
+
390
+ objects = EmployeeManager()
391
+
392
+ def __str__(self) -> str:
393
+ return self.name
394
+ ```
395
+
396
+ ```python
397
+ # rules.py
398
+ from typing import Any
399
+
400
+ from pyspecification import ObjectRulesRegistry
401
+ from django.db.models import Q
402
+
403
+
404
+ registry = ObjectRulesRegistry[Any, Q](operator="bitwise")
405
+
406
+
407
+ @registry.rule()
408
+ def is_admin(_: Any) -> Q:
409
+ return Q(is_admin=True)
410
+
411
+
412
+ @registry.rule()
413
+ def name__eq(_: Any, value: str) -> Q:
414
+ return Q(name=value)
415
+
416
+
417
+ @registry.rule()
418
+ def age__gte(_: Any, value: int) -> Q:
419
+ return Q(age__gte=value)
420
+
421
+
422
+ @registry.rule()
423
+ def age__lte(_: Any, value: int) -> Q:
424
+ return Q(age__lte=value)
425
+ ```
426
+
427
+ ```python
428
+ # views.py
429
+ from typing import Any
430
+
431
+ from django.db.models import Q
432
+ from django.http import HttpRequest, HttpResponse
433
+ from pyspecification import Predicate, PredicateCompiler
434
+
435
+ from .rules import registry
436
+ from .models import Employee
437
+
438
+
439
+ FILTER_RULE = {
440
+ "operator": "any",
441
+ "expressions": [
442
+ {
443
+ "name": "is_admin",
444
+ "args": [],
445
+ "kwargs": {},
446
+ "inverse": False,
447
+ },
448
+ {
449
+ "operator": "all",
450
+ "expressions": [
451
+ {
452
+ "name": "name__eq",
453
+ "args": ["admin"],
454
+ "kwargs": {},
455
+ "inverse": False,
456
+ },
457
+ {
458
+ "name": "age__gte",
459
+ "args": [18],
460
+ "kwargs": {},
461
+ "inverse": False,
462
+ },
463
+ ]
464
+ }
465
+ ]
466
+ }
467
+
468
+ compiler = PredicateCompiler[Any, Q](
469
+ registry.rules,
470
+ lambda _: Predicate(lambda _: Q(), operator="bitwise"),
471
+ )
472
+
473
+ def filter_employees(request: HttpRequest) -> HttpResponse:
474
+ predicate = compiler.compile(FILTER_RULE)
475
+ employees = Employee.objects.filter_by_rule(predicate)
476
+ return HttpResponse(f"Employees: {employees}")
477
+ ```
478
+
479
+ The model, rule, and view snippets can live in their normal Django app
480
+ modules. No Django settings or model changes are required beyond the standard
481
+ Django project setup.
482
+
483
+ This pattern is especially useful when you want:
484
+
485
+ - declarative Django queryset filters
486
+ - reusable admin and dashboard filter rules
487
+ - object-level permissions backed by Django `Q` expressions
488
+
489
+ ---
490
+
357
491
  ## Custom processors
358
492
 
359
493
  Rules can apply argument processors to coerce values before evaluation.
@@ -407,7 +541,7 @@ If conversion fails, the library raises `ProcessArgumentError`.
407
541
  ```python
408
542
  from dataclasses import dataclass
409
543
 
410
- from pyspecification import Predicate, PredicateCompiler, RuleSchema, object_rule
544
+ from pyspecification import Predicate, PredicateCompiler, object_rule
411
545
 
412
546
 
413
547
  @dataclass
@@ -462,7 +596,7 @@ rule_data = {
462
596
  "inverse": False,
463
597
  },
464
598
  {
465
- "name": "rule_not_exists",
599
+ "name": "age__between",
466
600
  "args": [18, 30],
467
601
  "kwargs": {},
468
602
  "inverse": False,
@@ -472,67 +606,16 @@ rule_data = {
472
606
  ],
473
607
  }
474
608
 
475
- predicate = compiler.compile(RuleSchema(**rule_data).model_dump())
476
- print(predicate(User("admin", 25, True))) # True
477
- ```
478
-
479
- ### Predicate schema
480
-
481
- `PredicateCompiler.compile()` consumes the normalized dictionary produced by
482
- `RuleSchema(...).model_dump()`. A predicate schema always has four keys:
483
-
484
- ```json
485
- {
486
- "name": "<rule_name>",
487
- "args": [],
488
- "kwargs": {},
489
- "inverse": false
490
- }
491
- ```
492
-
493
- The `name` must be present in the dictionary of rules passed to the compiler.
494
- Use `args` for positional arguments and `kwargs` for keyword arguments. These
495
- examples assume the rules from the previous section:
496
-
497
- ```json
498
- {
499
- "name": "is_admin",
500
- "args": [],
501
- "kwargs": {},
502
- "inverse": false
503
- }
504
- ```
505
-
506
- ```json
507
- {
508
- "name": "name__istartswith",
509
- "args": ["admin"],
510
- "kwargs": {},
511
- "inverse": false
512
- }
513
- ```
514
-
515
- ```json
516
- {
517
- "name": "age__between",
518
- "args": [],
519
- "kwargs": {"min_age": 18, "max_age": 30},
520
- "inverse": false
521
- }
522
- ```
523
-
524
- Set `inverse` to `true` to negate one predicate:
609
+ predicate = compiler.compile(rule_data)
610
+ # is_admin() | (name__istartswith("admin") & age__between(18, 30))
525
611
 
526
- ```json
527
- {
528
- "name": "is_admin",
529
- "args": [],
530
- "kwargs": {},
531
- "inverse": true
532
- }
612
+ print(predicate(User("admin", 25, True))) # True
533
613
  ```
534
614
 
535
- The normalized schema is convenient when rule definitions arrive as JSON:
615
+ `PredicateCompiler.compile()` consumes a normalized dictionary. The `name`
616
+ must be present in the dictionary of rules passed to the compiler. Use `args`
617
+ for positional arguments, `kwargs` for keyword arguments, and `inverse` to
618
+ negate one predicate:
536
619
 
537
620
  ```python
538
621
  import json
@@ -540,12 +623,12 @@ import json
540
623
  rule_json = '{"name": "age__between", "args": [18, 30], "kwargs": {}, "inverse": false}'
541
624
  rule_data = json.loads(rule_json)
542
625
  predicate = compiler.compile(rule_data)
543
- ```
544
626
 
545
- ### Expression wrapper schema
627
+ print(repr(predicate)) # Predicate(age__between)
628
+ ```
546
629
 
547
- Use a wrapper to combine predicates. A wrapper has an `operator`, an
548
- `expressions` list, and an `inverse` flag:
630
+ Use a wrapper to combine predicates. A wrapper has an `operator` and an
631
+ `expressions` list:
549
632
 
550
633
  ```json
551
634
  {
@@ -563,9 +646,8 @@ Use a wrapper to combine predicates. A wrapper has an `operator`, an
563
646
  "kwargs": {},
564
647
  "inverse": false
565
648
  }
566
- ],
567
- "inverse": false
568
- }
649
+ ]
650
+ } // is_admin() & age__between(18, 30)
569
651
  ```
570
652
 
571
653
  `operator` must be either `"all"` or `"any"`. Expressions can be nested to
@@ -596,88 +678,27 @@ represent more complex logic:
596
678
  "kwargs": {"min_age": 18, "max_age": 30},
597
679
  "inverse": false
598
680
  }
599
- ],
600
- "inverse": false
601
- }
602
- ],
603
- "inverse": false
604
- }
605
- ```
606
-
607
- You can also invert a complete wrapper:
608
-
609
- ```json
610
- {
611
- "operator": "any",
612
- "expressions": [
613
- {
614
- "name": "is_admin",
615
- "args": [],
616
- "kwargs": {},
617
- "inverse": false
618
- },
619
- {
620
- "name": "age__between",
621
- "args": [18, 30],
622
- "kwargs": {},
623
- "inverse": false
681
+ ]
624
682
  }
625
- ],
626
- "inverse": true
627
- }
683
+ ]
684
+ } // is_admin() | (name__istartswith("admin") & age__between(min_age=18, max_age=30))
628
685
  ```
629
686
 
630
687
  The compiler raises `RuleDoesNotExistError` when a predicate name is not in the
631
688
  compiler's rule mapping. If the dictionary passed directly to `compile()` does
632
- not match a predicate or wrapper schema, it raises `TypeError`. The error
633
- includes the location of the invalid expression, the expected schemas, and the
634
- received value. Validate external payloads with `RuleSchema` before compilation.
689
+ not match a predicate or wrapper shape, it raises `TypeError`.
635
690
 
636
691
  ---
637
-
638
- ## Rule schema validation
639
-
640
- `RuleSchema` validates declarative rule payloads.
641
-
642
- ```python
643
- from pyspecification import RuleSchema
644
-
645
- rule_data = {
646
- "operator": "all",
647
- "expressions": [
648
- {
649
- "name": "name__startswith",
650
- "args": ["admin"],
651
- "kwargs": {},
652
- "inverse": False,
653
- },
654
- {
655
- "name": "age__gt",
656
- "args": [18],
657
- "kwargs": {},
658
- "inverse": False,
659
- }
660
- ],
661
- }
662
-
663
- schema = RuleSchema(**rule_data)
664
- print(schema.model_dump())
665
- ```
666
-
667
- This is useful when you want to validate incoming rule definitions before compile-time execution.
668
-
669
- You can also use `RuleSchema` to represent nested predicate trees as typed, portable data.
670
-
671
692
  ---
672
693
 
673
694
  ## JSON schema generation
674
695
 
675
- `get_json_schema` inspects a rule function and returns JSON-schema-like metadata for parameters and return value.
696
+ `get_rule_json_schema` inspects a rule function and returns JSON-schema-like metadata for parameters and return value.
676
697
 
677
698
  ```python
678
699
  from dataclasses import dataclass
679
700
 
680
- from pyspecification import get_json_schema, object_rule
701
+ from pyspecification import get_rule_json_schema, object_rule
681
702
 
682
703
 
683
704
  @dataclass
@@ -692,11 +713,8 @@ def name__istartswith(user: User, value: str) -> bool:
692
713
  return user.name.lower().startswith(value.lower())
693
714
 
694
715
 
695
- print(get_json_schema(name__istartswith))
696
- # {
697
- # "value": {"type": "string"},
698
- # "return": {"type": "boolean"},
699
- # }
716
+ print(get_rule_json_schema(name__istartswith))
717
+ # {'value': {'type': 'string'}, 'return': {'type': 'boolean'}}
700
718
  ```
701
719
 
702
720
  This is useful for:
@@ -755,7 +773,7 @@ filtered = [user for user in users if predicate(user)]
755
773
  This is one of the most useful real-world patterns for the package. You can define a reusable rule set and compile it into SQLAlchemy boolean expressions for database queries.
756
774
 
757
775
  ```python
758
- from pyspecification import ObjectRulesRegistry, Predicate, PredicateCompiler, RuleSchema
776
+ from pyspecification import ObjectRulesRegistry, Predicate, PredicateCompiler
759
777
  from sqlalchemy import ColumnElement, and_, or_
760
778
  from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
761
779
 
@@ -812,7 +830,9 @@ filter_rule = {
812
830
  ],
813
831
  }
814
832
 
815
- query_predicate = compiler.compile(RuleSchema(**filter_rule).model_dump())
833
+ query_predicate = compiler.compile(filter_rule)
834
+ # is_admin() | age__ge(18)
835
+ # User.is_admin | User.age >= 18
816
836
  ```
817
837
 
818
838
  This makes it easy to expose admin filters, user search rules, and role-based queries without manually stitching SQL conditions together.
@@ -829,7 +849,7 @@ This allows readable authorization checks without large condition trees.
829
849
 
830
850
  ### 3. Dynamic rule engines
831
851
 
832
- The compiler and schema APIs make it easy to store or receive rules as structured data.
852
+ The compiler makes it easy to store or receive rules as structured data.
833
853
 
834
854
  Examples:
835
855
 
@@ -870,10 +890,6 @@ Rules should do one thing and avoid hidden side effects.
870
890
 
871
891
  If your project has many rules, registries provide structure and reduce duplication.
872
892
 
873
- ### Validate schema before compile
874
-
875
- If you load rules from external sources, validate them via `RuleSchema` before compiling.
876
-
877
893
  ---
878
894
 
879
895
  ## Exceptions
@@ -904,7 +920,7 @@ rule. Its specialized exceptions describe the problem:
904
920
  `RuleDoesNotExistError` includes the missing name and the available rule names,
905
921
  which is useful when rules are dynamically loaded. Malformed normalized
906
922
  compiler payloads raise `TypeError`; its message identifies the JSON-like path
907
- of the invalid expression and shows the expected schemas.
923
+ of the invalid expression and shows the expected shapes.
908
924
 
909
925
  ---
910
926
 
@@ -914,14 +930,13 @@ This project includes runnable examples under the `scripts/` directory:
914
930
 
915
931
  - `scripts/rules_example.py` — basic object-based rule composition
916
932
  - `scripts/reg_example.py` — registry usage and compiled rule predicate patterns
917
- - `scripts/json_schema_example.py` — JSON schema generation examples
918
933
 
919
934
  The test suite under `tests/` also demonstrates behavior for:
920
935
 
921
936
  - registry registration
922
937
  - predicate composition
923
938
  - compiler validation
924
- - schema serialization
939
+ - structured rule compilation
925
940
  - filtering workflows
926
941
 
927
942
  ---
@@ -931,7 +946,7 @@ The test suite under `tests/` also demonstrates behavior for:
931
946
  ```python
932
947
  from dataclasses import dataclass
933
948
 
934
- from pyspecification import ObjectRulesRegistry, PredicateCompiler, RuleSchema
949
+ from pyspecification import ObjectRulesRegistry, Predicate, PredicateCompiler
935
950
 
936
951
 
937
952
  @dataclass
@@ -988,9 +1003,9 @@ rule_definition = {
988
1003
  ],
989
1004
  }
990
1005
 
991
- schema = RuleSchema(**rule_definition)
992
1006
  compiler = PredicateCompiler(registry.rules, lambda spec: Predicate(lambda _: True, operator="logical"))
993
- predicate = compiler.compile(schema.model_dump())
1007
+ predicate = compiler.compile(rule_definition)
1008
+ # is_admin() | (name__istartswith("admin") & age__between(18, 30))
994
1009
 
995
1010
  users = [
996
1011
  User("Abdullah", 18, True),
@@ -998,20 +1013,20 @@ users = [
998
1013
  User("Charlie", 12, False),
999
1014
  ]
1000
1015
 
1001
- print([predicate(user) for user in users])
1016
+ print([predicate(user) for user in users]) # [True, True, False]
1002
1017
  ```
1003
1018
 
1004
1019
  ---
1005
1020
 
1006
1021
  ## Summary
1007
1022
 
1008
- `pyspecification` brings together rule registration, predicate composition, schema validation, and runtime compilation in a compact library designed around functional and declarative rule authoring.
1023
+ `pyspecification` brings together rule registration, predicate composition, and runtime compilation in a compact library designed around functional and declarative rule authoring.
1009
1024
 
1010
1025
  It is a practical fit for projects that need to:
1011
1026
 
1012
1027
  - express business rules clearly
1013
1028
  - compose conditions without nested `if` chains
1014
- - validate dynamic rule payloads
1029
+ - compile dynamic rule payloads
1015
1030
  - support filtering and policy evaluation
1016
1031
  - keep rule logic easy to test and maintain
1017
1032