pycraftbox-core 4.0.0__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.
@@ -0,0 +1,131 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ .vscode/*
6
+ !.vscode/extensions.json
7
+ !.vscode/tasks.json
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ pip-wheel-metadata/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ .python-version
88
+
89
+ # pipenv
90
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
92
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
93
+ # install all needed dependencies.
94
+ #Pipfile.lock
95
+
96
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
97
+ __pypackages__/
98
+
99
+ # Celery stuff
100
+ celerybeat-schedule
101
+ celerybeat.pid
102
+
103
+ # SageMath parsed files
104
+ *.sage.py
105
+
106
+ # Environments
107
+ .env
108
+ .venv
109
+ env/
110
+ venv/
111
+ ENV/
112
+ env.bak/
113
+ venv.bak/
114
+
115
+ # Spyder project settings
116
+ .spyderproject
117
+ .spyproject
118
+
119
+ # Rope project settings
120
+ .ropeproject
121
+
122
+ # mkdocs documentation
123
+ /site
124
+
125
+ # mypy
126
+ .mypy_cache/
127
+ .dmypy.json
128
+ dmypy.json
129
+
130
+ # Pyre type checker
131
+ .pyre/
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.5
2
+ Name: pycraftbox-core
3
+ Version: 4.0.0
4
+ Summary: Dependency-free core utilities for pycraftbox
5
+ Project-URL: Homepage, https://gitlab.com/erch/pycraftbox
6
+ Project-URL: Repository, https://gitlab.com/erch/pycraftbox
7
+ Project-URL: Issues, https://gitlab.com/erch/pycraftbox/-/issues
8
+ Requires-Python: >=3.12
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "pycraftbox-core"
3
+ version = "4.0.0"
4
+ description = "Dependency-free core utilities for pycraftbox"
5
+ requires-python = ">=3.12"
6
+ dependencies = []
7
+
8
+ [project.urls]
9
+ Homepage = "https://gitlab.com/erch/pycraftbox"
10
+ Repository = "https://gitlab.com/erch/pycraftbox"
11
+ Issues = "https://gitlab.com/erch/pycraftbox/-/issues"
12
+
13
+ [build-system]
14
+ requires = ["hatchling"]
15
+ build-backend = "hatchling.build"
16
+
17
+ [tool.hatch.build]
18
+ dev-mode-dirs = ["src"]
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["src/pycraftbox"]
@@ -0,0 +1,6 @@
1
+ """Dependency-free utilities shared by pycraftbox packages."""
2
+
3
+ from .attr_dict import AttrDict
4
+ from .utils import OSType, SysUtil, Utils
5
+
6
+ __all__ = ["AttrDict", "OSType", "SysUtil", "Utils"]
@@ -0,0 +1,172 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Iterator, Mapping
5
+ from typing import Any, Optional
6
+
7
+
8
+ class AttrDict:
9
+ """
10
+ class which properties can be accessed like a dict or like a propertie (.x) and vis/versa:
11
+ if used like a Dict to set a value , if the key contains dots (.) it creates a hierarchy of AttrDict object.
12
+
13
+ Takes advantage of the internal __dict__ attribute of a class instance where are stored all the instance attributes.
14
+ The example bellow show that we can set and read attribute with the dot notation but also through the __dict__ attribute:
15
+
16
+ class tt:
17
+ def __init__(self):
18
+ self.a =2
19
+
20
+ vt = tt()
21
+ print(vt.__dict__) # {'a': 2}
22
+ vt.b = 3
23
+ print(vt.__dict__) # {'a': 2, 'b': 3}
24
+ vt.__dict__["c"] = 4
25
+ print(vt.__dict__) # {'a': 2, 'b': 3, 'c': 4}
26
+
27
+
28
+ class Test(AttrDict):
29
+ def __init__(self):
30
+ self.var1 = "var1"
31
+ self.__dict__["vardict"] = "vardict"
32
+ t = Test()
33
+ print (f"t['vardict'] = {t['vardict']}") # t['vardict'] = vardict
34
+ print (f"t.vardict = {t.vardict}") # t.vardict = vardict
35
+ print (f"t['var1'] = {t['var1']}") # t['var1'] = var1
36
+ print (f"t.var1 = {t.var1}") # t.var1 = var1
37
+
38
+ t.var2 = "var2"
39
+ print (f"t['var2'] = {t['var2']}") # t['var2'] = var2
40
+ print (f"t.var2 = {t.var2}") # t.var2 = var2
41
+
42
+ t["var3"] = "var3"
43
+ print (f"t['var3'] = {t['var3']}") # t['var3'] = var3
44
+ print (f"t.var3 = {t.var3}") # t.var3 = var3
45
+
46
+ t["a1.a2"] = "complexval"
47
+ print (f"t['a1'] = {t['a1']}") # t['a1'] = {'a2': 'complexval'}
48
+ print (f"t.a1 = {t.a1}") # t.a1 = {'a2': 'complexval'}
49
+ """
50
+
51
+ _logger = logging.getLogger(__name__)
52
+
53
+ def __init__(self, init: Optional[Mapping[Any, Any]] = None) -> None:
54
+ if init is not None:
55
+ self.__dict__.update(init)
56
+
57
+ def __contains__(self, key: Any) -> bool:
58
+ try:
59
+ eval(f"self['{key}']")
60
+ except Exception:
61
+ return False
62
+ return True
63
+
64
+ def __getitem__(self, key: Any) -> Any:
65
+ """
66
+ Called to implement evaluation of self[key]
67
+ attributes with dots in their name are read in sub AttrDict Objects.
68
+ """
69
+ if isinstance(key, slice):
70
+ raise KeyError("slices are not supported")
71
+ parts = key.split(".")
72
+ curpart = parts[0]
73
+
74
+ if len(curpart.strip()) == 0:
75
+ raise AttributeError(f"bad attribute name: {key}")
76
+ elif len(parts) > 1:
77
+ if curpart in self.__dict__:
78
+ sub_attr = self.__dict__[curpart]
79
+ else:
80
+ raise AttributeError(f"key {curpart} not set")
81
+ return sub_attr[".".join(parts[1:])]
82
+ else:
83
+ return self.__dict__[curpart]
84
+
85
+ def __setitem__(self, key: Any, value: Any) -> None:
86
+ """
87
+ Called to implement assignment to self[key].
88
+ attributes with dots in their name are put in sub AttrDict Objects.
89
+ """
90
+ if isinstance(key, slice):
91
+ raise KeyError("slices are not supported")
92
+ parts = key.split(".")
93
+ curpart = parts[0]
94
+
95
+ if len(curpart.strip()) == 0:
96
+ raise AttributeError(f"bad attribute name: {key}")
97
+ elif len(parts) > 1:
98
+ if curpart in self.__dict__:
99
+ sub_attr = self.__dict__[curpart]
100
+ else:
101
+ sub_attr = AttrDict()
102
+ self.__dict__[curpart] = sub_attr
103
+ sub_attr[".".join(parts[1:])] = value
104
+ else:
105
+ self.__dict__[curpart] = value
106
+
107
+ def __delitem__(self, key: Any) -> None:
108
+ """Called to implement deletion of self[key]."""
109
+ del self.__dict__[key]
110
+
111
+ def __len__(self) -> int:
112
+ """Called to implement the built-in function len()"""
113
+ return len(self.__dict__)
114
+
115
+ def __iter__(self) -> Iterator:
116
+ """This method is called when an iterator is required for a container."""
117
+ return self.__dict__.__iter__()
118
+
119
+ def update(self, other: Mapping[Any, Any], override: bool = False) -> None:
120
+ if override:
121
+ res = self.__dict__ | other # type: ignore
122
+ else:
123
+ res = other | self.__dict__ # type: ignore
124
+ self.__dict__ = res
125
+
126
+ def to_dict(self, recursive: bool = True) -> dict[Any, Any]:
127
+ """
128
+ Return a copy of the AttrDict as a dictionary.
129
+ create a recursive copy if recursive is True (default): nested AttrDict are also converted to dict.
130
+ if recursive is False, nested AttrDict are not converted to dict and are returned as is.
131
+ """
132
+ d = {}
133
+ for k, v in self.__dict__.items():
134
+ if issubclass(type(v), AttrDict):
135
+ d[k] = v.to_dict(recursive=recursive) if recursive else v
136
+ else:
137
+ d[k] = v
138
+ return d
139
+
140
+ def has_value(self, key: str | None) -> bool:
141
+ """
142
+ Check if the AttrDict has a value for the given key.
143
+ The key can be a dotted path to access nested AttrDict.
144
+ """
145
+ if key is None:
146
+ return False
147
+ try:
148
+ _ = self[key]
149
+ return True
150
+ except Exception:
151
+ return False
152
+
153
+ def _repr_with_ident(self, indent: int) -> list[str]:
154
+ res = []
155
+ indent_str = "\t" * indent
156
+ for n, v in self.__dict__.items():
157
+ if issubclass(self.__class__, type(v)):
158
+ res.append(f"{indent_str}{n} :")
159
+ res.extend(v._repr_with_ident(indent + 1))
160
+ else:
161
+ res.append("{}{} : {}".format(indent_str, n, v))
162
+ return res
163
+
164
+ def __repr__(self) -> str:
165
+ res = self._repr_with_ident(0)
166
+ return "\n".join(res)
167
+
168
+ def __str__(self) -> str:
169
+ return self.__repr__()
170
+
171
+ def clone(self) -> AttrDict:
172
+ return AttrDict(self.__dict__)
@@ -0,0 +1,149 @@
1
+ from __future__ import annotations
2
+
3
+ from calendar import calendar
4
+ import logging
5
+ from collections.abc import MutableMapping, Mapping, Sequence, Generator
6
+ from collections import OrderedDict
7
+ from datetime import date, datetime, timedelta, tzinfo
8
+ from enum import Enum
9
+ from socket import AF_ECONET
10
+ from typing import (
11
+ Any,
12
+ Optional,
13
+ Union,
14
+ get_origin,
15
+ Callable,
16
+ Protocol,
17
+ )
18
+ import sys
19
+ import platform
20
+ from enum import Enum, auto
21
+
22
+
23
+ class Utils:
24
+ """A class grouping various utility methods"""
25
+
26
+ _logger = logging.getLogger(__name__)
27
+
28
+ @classmethod
29
+ def is_sequence(cls, obj: Any) -> bool:
30
+ try:
31
+ len(obj)
32
+ obj[0:0]
33
+ return not isinstance(obj, str)
34
+ except KeyError:
35
+ return False
36
+ except TypeError:
37
+ return False # TypeError: object is not iterable
38
+
39
+ @classmethod
40
+ def is_primitive(cls, obj: Any) -> bool:
41
+ primitives = (bool, str, int, float, type(None))
42
+ return type(obj) in primitives
43
+
44
+ @classmethod
45
+ def is_dict(cls, obj: Any) -> bool:
46
+ return isinstance(obj, Mapping)
47
+
48
+ @classmethod
49
+ def get_datetime_str(cls, py_date: Union[date, datetime]) -> str:
50
+ if isinstance(py_date, datetime):
51
+ return py_date.strftime("%Y-%m-%dT%H%M")
52
+ else:
53
+ return f"{py_date.strftime('%Y-%m-%d')}T0000"
54
+
55
+ @classmethod
56
+ def date_convertor(cls, x: str | datetime) -> datetime | None:
57
+ """
58
+ A date convertor that can handle empty strings as None
59
+ Args:
60
+ x (str | datetime): The input value
61
+ Returns:
62
+ datetime | None: The converted value
63
+ """
64
+ if isinstance(x, datetime):
65
+ return x
66
+ elif isinstance(x, str) and x == "":
67
+ return None
68
+ elif isinstance(x, str) and x != "":
69
+ date_str, _, _ = x.partition(" ")
70
+ return datetime.strptime(date_str, "%d/%m/%Y")
71
+ else:
72
+ raise Exception(f"expected str or datetime , got {type(x)}")
73
+
74
+ @classmethod
75
+ def date_of_days_of_week(
76
+ cls,
77
+ day_of_week: int,
78
+ *,
79
+ from_date: Optional[date] = None,
80
+ last_date: Optional[date] = None,
81
+ ) -> Generator[date, None, None]:
82
+ if from_date is None:
83
+ now = date.today()
84
+ from_date = date(now.year, 1, 1)
85
+ from_date_week_day = from_date.isoweekday()
86
+ delta = (day_of_week + 7 - from_date_week_day) % 7
87
+ this_looking_day = from_date + timedelta(days=delta)
88
+
89
+ if not last_date:
90
+ last_date = date(from_date.year + 1, 1, 1)
91
+ while this_looking_day <= last_date:
92
+ yield this_looking_day
93
+ this_looking_day += timedelta(days=7)
94
+
95
+ @classmethod
96
+ def new_obj(cls, obj_type: str, attrs: Mapping[str, Any] = {}) -> object:
97
+ return type(obj_type, (), attrs)() # type: ignore
98
+
99
+ @classmethod
100
+ def keys_exists(
101
+ cls, element: Any, *keys: Any, allow_none: bool = False, allow_empty: bool = True
102
+ ) -> bool:
103
+ """
104
+ Check if *keys (nested) exists in `element` (dict).
105
+ """
106
+ _element = element
107
+ for key in keys:
108
+ try:
109
+ _element = _element[key]
110
+ except KeyError:
111
+ return False
112
+ if not allow_none and _element is None:
113
+ return False
114
+ elif not allow_empty and hasattr(_element, "__len__"):
115
+ return len(_element) > 0
116
+ else:
117
+ return True
118
+
119
+
120
+ class OSType(Enum):
121
+ LINUX = "linux"
122
+ MAC = "mac"
123
+ WIN = "win"
124
+ UNKNOWN = "unknown"
125
+
126
+
127
+ class SysUtil:
128
+ @classmethod
129
+ def get_os_name(cls) -> OSType:
130
+ pl = sys.platform
131
+ if pl == "linux" or pl == "linux2":
132
+ return OSType.LINUX
133
+ elif pl == "darwin":
134
+ return OSType.MAC
135
+ elif pl == "win32" or pl == "cygwin":
136
+ return OSType.WIN
137
+ else:
138
+ return OSType.UNKNOWN
139
+
140
+ @classmethod
141
+ def get_os_architecture(cls) -> int:
142
+ if platform.machine().endswith("64"):
143
+ return 64
144
+ else:
145
+ return 32
146
+
147
+ @classmethod
148
+ def get_os_type(cls) -> str:
149
+ return f"{cls.get_os_name()}{cls.get_os_architecture()}"