classicist 1.0.4__py3-none-any.whl → 1.0.5__py3-none-any.whl

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.
classicist/__init__.py CHANGED
@@ -49,6 +49,11 @@ from classicist.exceptions import (
49
49
  AttributeShadowingError,
50
50
  )
51
51
 
52
+ from classicist.types import (
53
+ NullType,
54
+ Null,
55
+ )
56
+
52
57
  __all__ = [
53
58
  # Decorators
54
59
  "alias",
@@ -75,4 +80,7 @@ __all__ = [
75
80
  "AliasError",
76
81
  "AnnotationError",
77
82
  "AttributeShadowingError",
83
+ # Types
84
+ "NullType",
85
+ "Null",
78
86
  ]
@@ -0,0 +1,6 @@
1
+ from classicist.types.null import NullType, Null
2
+
3
+ __all__ = [
4
+ "NullType",
5
+ "Null",
6
+ ]
@@ -0,0 +1,70 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class NullType(object):
5
+ """The NullType class supports the creation of a Null singleton instance that offers
6
+ support for safely chaining nested attribute accesses without raising exceptions for
7
+ attributes that have no inherent value.
8
+
9
+ As Python currently lacks a null-aware navigation operator, such as `?.`, like many
10
+ other dynamic languages, for safely navigating nested object hierarchies which may
11
+ contain null attributes, the library offers the `NullType` and `Null` singleton as a
12
+ potential option to support this need in the interim. Consistent use of the `Null`
13
+ singleton in place of the standard `None` singleton, in relevant scenarios, such as
14
+ within a data model library for example, can allow for more expressive and clearer
15
+ code that does not require endless checks for intermediary attribute existence.
16
+
17
+ However, there are some caveats to the use of the `NullType` and `Null` singleton as
18
+ these are not built-in features of the language, and Python does not offer support
19
+ for the creation of custom operators nor overriding the `is` operator for identity
20
+ checking which limits some of the cases in which the `Null` singleton could be used.
21
+
22
+ With knowledge of the caveats and in the right scenarios, the `Null` singleton can
23
+ offer a good way to achieve clearer and more expressive code while navigating nested
24
+ object hierarchies without the clutter of nested attribute existence checks."""
25
+
26
+ _instance: NullType = None
27
+
28
+ def __new__(cls) -> NullType:
29
+ """Ensure NullType can only create a singleton instance; further calls to create
30
+ instances of the NullType will return the existing singleton instance."""
31
+
32
+ if cls._instance is None:
33
+ cls._instance = super().__new__(cls)
34
+
35
+ return cls._instance
36
+
37
+ def __getattr__(self, name: str) -> NullType:
38
+ """Support nested attribute access by returning the singleton instance."""
39
+
40
+ return self.__class__._instance
41
+
42
+ def __bool__(self) -> bool:
43
+ """Support falsey equality checks for boolean comparisons against NullType."""
44
+
45
+ return False # Always returns False
46
+
47
+ def __eq__(self, value: object) -> bool:
48
+ """Support value equality checks against NullType via the `==` operator as the
49
+ fallback option to being able to support identity equality checks via the `is`
50
+ operator which are not currently possible due to language constraints."""
51
+
52
+ if value is None or value is False:
53
+ return True
54
+ else:
55
+ return self is value
56
+
57
+ def __str__(self) -> str:
58
+ return "Null"
59
+
60
+ def __repr__(self) -> str:
61
+ return "Null"
62
+
63
+
64
+ # Create the singleton instance of Null
65
+ Null = NullType()
66
+
67
+ __all__ = [
68
+ "NullType",
69
+ "Null",
70
+ ]
classicist/version.txt CHANGED
@@ -1 +1 @@
1
- 1.0.4
1
+ 1.0.5
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: classicist
3
- Version: 1.0.4
3
+ Version: 1.0.5
4
4
  Summary: Classy class decorators for Python.
5
5
  Author: Daniel Sissman
6
6
  License-Expression: MIT
@@ -33,17 +33,20 @@ Dynamic: license-file
33
33
 
34
34
  # Classicist: Classy Class Decorators & Extensions
35
35
 
36
- The Classicist library provides several useful decorators and helper methods including:
36
+ The Classicist library provides several useful decorators, functions, classes, and types
37
+ that offer useful behaviours and functionality, and help to fill some of the gaps in the
38
+ current standard library:
37
39
 
38
40
  * `@hybridmethod` – a decorator that allows methods to be used both as class methods and as instance methods;
39
- * `@classproperty` – a decorator that allow class methods to be accessed as class properties;
41
+ * `@classproperty` – a decorator that allows class methods to be accessed as class properties;
40
42
  * `@annotation` – a decorator that can be used to apply arbitrary annotations to code objects;
41
- * `@deprecated` – a decorator that can be used to mark functions, classes and methods as being deprecated;
43
+ * `@deprecated` – a decorator that can be used to mark functions, classes and methods as being deprecated, with support for adding optional arbitrary annotations;
42
44
  * `@alias` – a decorator that can be used to add aliases to classes, methods defined within classes, module-level functions, and nested functions when overriding the aliasing scope;
43
45
  * `@nocache` – a decorator that can be used to mark functions and methods as not being suitable for caching;
44
- * `@runtimer` – a decorator that can be used to time function and method calls;
46
+ * `@runtimer` – a decorator that can be used to gather call run time information for function and method calls;
45
47
  * `shadowproof` – a metaclass that can be used to protect subclasses from class-level attributes
46
- being overwritten (or shadowed) which can otherwise negatively affect class behaviour in some cases.
48
+ being overwritten (or shadowed) which can otherwise negatively affect class behaviour in some cases;
49
+ * `Null` – an alternative to `None`, useful when building custom data model classes and libraries, where supporting "null-safe" style access and navigation of the model's nested hierarchy is preferred.
47
50
 
48
51
  The `classicist` library was previously named `hybridmethod` so if a prior version had
49
52
  been installed, please update references to the new library name. Installation of the
@@ -554,6 +557,146 @@ except AttributeShadowingError as exception:
554
557
  pass
555
558
  ```
556
559
 
560
+ #### NullType: Null-Safe Style Access for Data Models and Nested Class Hierarchies
561
+
562
+ The `NullType` class supports the creation of a `Null` singleton instance that offers
563
+ support for safely chaining nested attribute accesses without raising exceptions for
564
+ attributes that have no inherent value.
565
+
566
+ As Python currently lacks a null-aware navigation operator, such as `?.`, unlike many
567
+ other dynamic languages, for safely navigating nested object hierarchies which may
568
+ contain null attributes, the library offers the `NullType` and `Null` singleton as a
569
+ potential option to support this need in the interim. Consistent use of the `Null`
570
+ singleton in place of the standard `None` singleton, in relevant scenarios, such as
571
+ within a custom data model library, can allow for more expressive and clearer code that
572
+ does not require endless checks for intermediary or nested attribute existence.
573
+
574
+ However, there are some caveats to the use of the `NullType` and `Null` singleton as
575
+ these are not built-in features of the language, and Python does not offer support for
576
+ the creation of custom operators nor overriding the `is` operator for identity checking
577
+ which limits some of the use cases in which the `Null` singleton can be used.
578
+
579
+ With knowledge of these caveats and in the right scenarios, the `Null` singleton can
580
+ offer a good way to achieve clearer and more expressive code while navigating nested
581
+ object hierarchies without the clutter of nested attribute existence checks.
582
+
583
+ ```python
584
+ from __future__ import annotations
585
+
586
+ from classicist import Null
587
+
588
+ data: dict = {
589
+ "id": 1,
590
+ "name": "A",
591
+ "related": {
592
+ "id": 2,
593
+ "name": "B",
594
+ "related": {
595
+ "id": 3,
596
+ "name": "C",
597
+ },
598
+ },
599
+ }
600
+
601
+ class Model(object):
602
+ """Sample Model class with some properties that reference nested Model instances."""
603
+
604
+ def __init__(self, data: dict):
605
+ if not isinstance(data, dict):
606
+ raise TypeError("The 'data' argument must reference a valid data dictionary!")
607
+
608
+ if not ("id" in data and isinstance(data["id"], int)):
609
+ raise ValueError("The 'data' must contain an 'id' key with an integer value!")
610
+
611
+ if not ("name" in data and isinstance(data["name"], str)):
612
+ raise ValueError("The 'data' must contain an 'name' key with an string value!")
613
+
614
+ self.data = data
615
+
616
+ @property
617
+ def id(self) -> int:
618
+ return self.data["id"]
619
+
620
+ @property
621
+ def name(self) -> str:
622
+ return self.data["name"]
623
+
624
+ @property
625
+ def related(self) -> Model | Null:
626
+ if data := self.data.get("related"):
627
+ return Model(data=data)
628
+ else:
629
+ return Null
630
+
631
+ @property
632
+ def relates(self) -> Model | Null:
633
+ if data := self.data.get("relates"):
634
+ return Model(data=data)
635
+ else:
636
+ return Null
637
+
638
+ # Create an instance of the sample Model data class
639
+ model = Model(data=data)
640
+
641
+ # Check that the expected data attributes are available
642
+ assert model.id == 1
643
+ assert model.name == "A"
644
+
645
+ # The model.related property references A/1 in the data above, so these properties exist
646
+ assert model.related
647
+ assert model.related.id
648
+ assert model.related.name
649
+
650
+ # Ensure the nested property values are as expected
651
+ assert model.related.id == 2
652
+ assert model.related.name == "B"
653
+
654
+ # Note that model.relates had no corresponding data, so the Model returns `Null` which
655
+ # still allows for nested attribute access, such as to `.id` and `.name` without raising
656
+ # any exceptions; the `Null` singleton also allows for `bool` comparison as shown below:
657
+ assert not model.relates
658
+ assert not model.relates.id
659
+ assert not model.relates.name
660
+
661
+ # There is no limit to the levels of nesting that `NullType` and the `Null` singleton
662
+ # can support, so long as a custom data model or library consistently returns `Null` for
663
+ # cases where the "null-safe" navigation is desired:
664
+
665
+ # model.related.related references 3/C in the data above, so these properties exist
666
+ assert model.related.related.id
667
+ assert model.related.related.name
668
+
669
+ # model.related.relates was not specified in the data above so the Model returns `Null`
670
+ assert not model.related.relates.id
671
+ assert not model.related.relates.name
672
+
673
+ # Ensure the nested property values are as expected
674
+ assert model.related.related.id == 3
675
+ assert model.related.related.name == "C"
676
+
677
+ # These features make it easy to write clearer more expressive code without boilerplate
678
+ # code to check for the availability of nested attributes or entities:
679
+ if isinstance(name := model.related.name, str):
680
+ print("model.related.name => %s" % (name))
681
+
682
+ # No exception is raised here even though model.relates is effectively "null":
683
+ if isinstance(name := model.relates.name, str):
684
+ print("model.relates.name => %s" % (name))
685
+
686
+ # However, there are some caveats as noted with `NullType` and the `Null` singleton as
687
+ # these are a third-party solution so we can only go so far in supplementing null-safe
688
+ # operator behaviour in the language; for example, we cannot perform identity checks to
689
+ # boolean values, True or False, or the actual None singleton value:
690
+ assert not model.relates is True # Notice the `assert not` as `assert` would fail here
691
+ assert not model.relates is False # Notice the `assert not` as `assert` would fail here
692
+
693
+ # Furthermore, we cannot use `None` identity comparison either:
694
+ assert not model.relates is None # Notice the `assert not` as `assert` would fail here
695
+
696
+ # We can however perform an identity check against the `Null` singleton if needed:
697
+ assert model.relates is Null
698
+ ```
699
+
557
700
  ### Unit Tests
558
701
 
559
702
  The Classicist library includes a suite of comprehensive unit tests which ensure that
@@ -1,5 +1,5 @@
1
- classicist/__init__.py,sha256=Ndg3ZbcjOpSzXUfvskrg_VC7xLbyxH7GiSmoV4Yhp2w,1486
2
- classicist/version.txt,sha256=rqWtvvV0eFJzxPOcG3aHz4AZk-DLa_Z4GkFonk7bsgw,5
1
+ classicist/__init__.py,sha256=VeAO1fY3noKmFJDdiCFUABIykF3oXSk_9QXNSaaXIp0,1584
2
+ classicist/version.txt,sha256=nXE_EpedYoeSULwKIDXj71cxWsQlHoUBnSHHXtcmlyA,5
3
3
  classicist/decorators/__init__.py,sha256=Cz1zXWoLV7s63pQiOQX6B0RGDOg3schTbtkq6THz3J8,752
4
4
  classicist/decorators/aliased/__init__.py,sha256=vW1P9jbGkOD_m9GvgEXF0Uni-Dt6rfVXDVF5D4wC1GY,6926
5
5
  classicist/decorators/annotation/__init__.py,sha256=20WwmrXDxT85sItpDiCdC-hZjbyDR6E2mLPMSKQgm8g,1796
@@ -19,9 +19,11 @@ classicist/logging/__init__.py,sha256=LJ-Nih1LacPrO2TvTT6l84So-pgw84AHJ8IhzYKl5r
19
19
  classicist/metaclasses/__init__.py,sha256=mYhR5rM7cnJlaNUlgoQWOo44RQSORteRjYd0y0BajxQ,159
20
20
  classicist/metaclasses/aliased/__init__.py,sha256=grs4Z8dMY6R2fCFn4UCPdCzEJtVaAv-tsWFwY1DCUpI,2033
21
21
  classicist/metaclasses/shadowproof/__init__.py,sha256=d55uNjcaCorD3MdDUv7aRVpk2MlE8JzMjint6Vvf_Yc,1492
22
- classicist-1.0.4.dist-info/licenses/LICENSE.md,sha256=qBmrjPmSCp0YFyaIl2G3FU3rniFD31YC0Yd3MrO1wEg,1070
23
- classicist-1.0.4.dist-info/METADATA,sha256=u7zpR5C-SXv1blBdvr03qu-MTXHPxEiOtzx19P1yqgQ,26888
24
- classicist-1.0.4.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
25
- classicist-1.0.4.dist-info/top_level.txt,sha256=beG3ZuwObnmnY_mgNSN5CaVIWpI2VKszjVdKHPgZBhc,11
26
- classicist-1.0.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
27
- classicist-1.0.4.dist-info/RECORD,,
22
+ classicist/types/__init__.py,sha256=EZE6NnKf051F5MuqxyReJb4oHIzQY2gCgOxC51_64mI,92
23
+ classicist/types/null/__init__.py,sha256=cY7eFop17KuuXO-1eqxXl1RGsAHASFKlpx5f7JXv00E,2829
24
+ classicist-1.0.5.dist-info/licenses/LICENSE.md,sha256=qBmrjPmSCp0YFyaIl2G3FU3rniFD31YC0Yd3MrO1wEg,1070
25
+ classicist-1.0.5.dist-info/METADATA,sha256=n9Dm7Vj8iWqws1XiuvRViMqoqsYiAV2gpCqvAGu0MEc,32691
26
+ classicist-1.0.5.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
27
+ classicist-1.0.5.dist-info/top_level.txt,sha256=beG3ZuwObnmnY_mgNSN5CaVIWpI2VKszjVdKHPgZBhc,11
28
+ classicist-1.0.5.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
29
+ classicist-1.0.5.dist-info/RECORD,,