hunterMakesPy 0.2.2__py3-none-any.whl → 0.3.0__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.
- hunterMakesPy/__init__.py +2 -5
- hunterMakesPy/coping.py +29 -25
- hunterMakesPy/dataStructures.py +133 -128
- hunterMakesPy/filesystemToolkit.py +55 -1
- hunterMakesPy/tests/test_dataStructures.py +115 -120
- hunterMakesPy/tests/test_filesystemToolkit.py +187 -1
- {huntermakespy-0.2.2.dist-info → huntermakespy-0.3.0.dist-info}/METADATA +4 -14
- {huntermakespy-0.2.2.dist-info → huntermakespy-0.3.0.dist-info}/RECORD +11 -11
- {huntermakespy-0.2.2.dist-info → huntermakespy-0.3.0.dist-info}/WHEEL +0 -0
- {huntermakespy-0.2.2.dist-info → huntermakespy-0.3.0.dist-info}/licenses/LICENSE +0 -0
- {huntermakespy-0.2.2.dist-info → huntermakespy-0.3.0.dist-info}/top_level.txt +0 -0
hunterMakesPy/__init__.py
CHANGED
|
@@ -17,13 +17,10 @@ from hunterMakesPy.parseParameters import (defineConcurrencyLimit as defineConcu
|
|
|
17
17
|
|
|
18
18
|
from hunterMakesPy.filesystemToolkit import (importLogicalPath2Identifier as importLogicalPath2Identifier,
|
|
19
19
|
importPathFilename2Identifier as importPathFilename2Identifier, makeDirsSafely as makeDirsSafely,
|
|
20
|
-
writeStringToHere as writeStringToHere)
|
|
20
|
+
writePython as writePython, writeStringToHere as writeStringToHere)
|
|
21
21
|
|
|
22
22
|
from hunterMakesPy.dataStructures import stringItUp as stringItUp, updateExtendPolishDictionaryLists as updateExtendPolishDictionaryLists
|
|
23
23
|
|
|
24
|
-
import
|
|
25
|
-
|
|
26
|
-
if sys.version_info < (3, 14):
|
|
27
|
-
from hunterMakesPy.dataStructures import autoDecodingRLE as autoDecodingRLE
|
|
24
|
+
from hunterMakesPy.dataStructures import autoDecodingRLE as autoDecodingRLE
|
|
28
25
|
|
|
29
26
|
from hunterMakesPy._theSSOT import settingsPackage
|
hunterMakesPy/coping.py
CHANGED
|
@@ -36,14 +36,14 @@ class PackageSettings:
|
|
|
36
36
|
package identifiers and installation paths if they are not passed to the `class` constructor. Python `dataclasses` are easy to
|
|
37
37
|
subtype and extend.
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
Attributes
|
|
40
40
|
----------
|
|
41
41
|
identifierPackageFALLBACK : str = ''
|
|
42
42
|
Fallback package identifier used only during initialization when automatic discovery fails.
|
|
43
|
-
pathPackage : Path = Path()
|
|
44
|
-
Absolute path to the installed package directory. Automatically resolved from `identifierPackage` if not provided.
|
|
45
43
|
identifierPackage : str = ''
|
|
46
|
-
Canonical name of the package. Automatically extracted from
|
|
44
|
+
Canonical name of the package. Automatically extracted from "pyproject.toml".
|
|
45
|
+
pathPackage : Path = getPathPackageINSTALLING(identifierPackage)
|
|
46
|
+
Absolute path to the installed package directory. Automatically resolved from `identifierPackage` if not provided.
|
|
47
47
|
fileExtension : str = '.py'
|
|
48
48
|
Default file extension.
|
|
49
49
|
|
|
@@ -85,34 +85,39 @@ class PackageSettings:
|
|
|
85
85
|
if self.pathPackage == Path() and self.identifierPackage:
|
|
86
86
|
self.pathPackage = getPathPackageINSTALLING(self.identifierPackage)
|
|
87
87
|
|
|
88
|
-
def raiseIfNone(
|
|
89
|
-
"""
|
|
90
|
-
|
|
91
|
-
(AI generated docstring)
|
|
88
|
+
def raiseIfNone(expression: TypeSansNone | None, errorMessage: str | None = None) -> TypeSansNone:
|
|
89
|
+
"""Convert the `expression` return annotation from '`cerPytainty | None`' to '`cerPytainty`' because `expression` cannot be `None`; `raise` an `Exception` if you're wrong.
|
|
92
90
|
|
|
93
|
-
|
|
91
|
+
The Python interpreter evaluates `expression` to a value: think of a function call or an attribute access. You can use
|
|
92
|
+
`raiseIfNone` for fail early defensive programming. I use it, however, to cure type-checker-nihilism: that's when "or `None`"
|
|
93
|
+
return types cause your type checker to repeatedly say, "You can't do that because the value might be `None`."
|
|
94
94
|
|
|
95
95
|
Parameters
|
|
96
96
|
----------
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
errorMessage : str | None = None
|
|
100
|
-
Custom error message
|
|
97
|
+
expression : TypeSansNone | None
|
|
98
|
+
Python code with a return type that is a `union` of `None` and `TypeSansNone`, which is a stand-in for one or more other types.
|
|
99
|
+
errorMessage : str | None = 'A function unexpectedly returned `None`. Hint: look at the traceback immediately before `raiseIfNone`.'
|
|
100
|
+
Custom error message for the `ValueError` `Exception` if `expression` is `None`.
|
|
101
101
|
|
|
102
102
|
Returns
|
|
103
103
|
-------
|
|
104
|
-
|
|
105
|
-
The
|
|
104
|
+
contentment : TypeSansNone
|
|
105
|
+
The value returned by `expression`, but guaranteed to not be `None`.
|
|
106
106
|
|
|
107
107
|
Raises
|
|
108
108
|
------
|
|
109
109
|
ValueError
|
|
110
|
-
If `
|
|
110
|
+
If the value returned by `expression` is `None`.
|
|
111
111
|
|
|
112
112
|
Examples
|
|
113
113
|
--------
|
|
114
|
-
|
|
114
|
+
Basic usage with attribute access:
|
|
115
|
+
```python
|
|
116
|
+
annotation = raiseIfNone(ast_arg.annotation)
|
|
117
|
+
# Raises ValueError if ast_arg.annotation is None
|
|
118
|
+
```
|
|
115
119
|
|
|
120
|
+
Function return value validation:
|
|
116
121
|
```python
|
|
117
122
|
def findFirstMatch(listItems: list[str], pattern: str) -> str | None:
|
|
118
123
|
for item in listItems:
|
|
@@ -122,28 +127,27 @@ def raiseIfNone(returnTarget: TypeSansNone | None, errorMessage: str | None = No
|
|
|
122
127
|
|
|
123
128
|
listFiles = ['document.txt', 'image.png', 'data.csv']
|
|
124
129
|
filename = raiseIfNone(findFirstMatch(listFiles, '.txt'))
|
|
125
|
-
# Returns 'document.txt'
|
|
130
|
+
# Returns 'document.txt' when match exists
|
|
126
131
|
```
|
|
127
132
|
|
|
128
|
-
|
|
129
|
-
|
|
133
|
+
Dictionary value retrieval with custom message:
|
|
130
134
|
```python
|
|
131
135
|
configurationMapping = {'host': 'localhost', 'port': 8080}
|
|
132
136
|
host = raiseIfNone(configurationMapping.get('host'),
|
|
133
137
|
"Configuration must include 'host' setting")
|
|
134
|
-
# Returns 'localhost'
|
|
138
|
+
# Returns 'localhost' when key exists
|
|
135
139
|
|
|
136
140
|
# This would raise ValueError with custom message:
|
|
137
141
|
# database = raiseIfNone(configurationMapping.get('database'),
|
|
138
|
-
#
|
|
142
|
+
# "Configuration must include 'database' setting")
|
|
139
143
|
```
|
|
140
144
|
|
|
141
145
|
Thanks
|
|
142
146
|
------
|
|
143
|
-
sobolevn, https://github.com/sobolevn, for the seed of
|
|
147
|
+
sobolevn, https://github.com/sobolevn, for the seed of this function. https://github.com/python/typing/discussions/1997#discussioncomment-13108399
|
|
144
148
|
|
|
145
149
|
"""
|
|
146
|
-
if
|
|
150
|
+
if expression is None:
|
|
147
151
|
message = errorMessage or 'A function unexpectedly returned `None`. Hint: look at the traceback immediately before `raiseIfNone`.'
|
|
148
152
|
raise ValueError(message)
|
|
149
|
-
return
|
|
153
|
+
return expression
|
hunterMakesPy/dataStructures.py
CHANGED
|
@@ -6,158 +6,163 @@ from numpy.typing import NDArray
|
|
|
6
6
|
from typing import Any
|
|
7
7
|
import more_itertools
|
|
8
8
|
import re as regex
|
|
9
|
-
import sys
|
|
10
|
-
|
|
11
|
-
if sys.version_info < (3, 14):
|
|
12
|
-
import python_minifier
|
|
13
|
-
|
|
14
|
-
def autoDecodingRLE(arrayTarget: NDArray[integer[Any]], *, assumeAddSpaces: bool = False) -> str:
|
|
15
|
-
"""Transform a NumPy array into a compact, self-decoding run-length encoded string representation.
|
|
16
|
-
|
|
17
|
-
This function converts a NumPy array into a string that, when evaluated as Python code,
|
|
18
|
-
recreates the original array structure. The function employs two compression strategies:
|
|
19
|
-
1. Python's `range` syntax for consecutive integer sequences
|
|
20
|
-
2. Multiplication syntax for repeated elements
|
|
21
|
-
|
|
22
|
-
The resulting string representation is designed to be both human-readable and space-efficient,
|
|
23
|
-
especially for large cartesian mappings with repetitive patterns. When this string is used
|
|
24
|
-
as a data source, Python will automatically decode it into Python `list`, which if used as an
|
|
25
|
-
argument to `numpy.array()`, will recreate the original array structure.
|
|
26
|
-
|
|
27
|
-
Parameters
|
|
28
|
-
----------
|
|
29
|
-
arrayTarget : NDArray[integer[Any]]
|
|
30
|
-
(array2target) The NumPy array to be encoded.
|
|
31
|
-
assumeAddSpaces : bool = False
|
|
32
|
-
(assume2add2spaces) Affects internal length comparison during compression decisions.
|
|
33
|
-
This parameter doesn't directly change output format but influences whether
|
|
34
|
-
`range` or multiplication syntax is preferred in certain cases. The parameter
|
|
35
|
-
exists because the Abstract Syntax Tree (AST) inserts spaces in its string
|
|
36
|
-
representation.
|
|
37
|
-
|
|
38
|
-
Returns
|
|
39
|
-
-------
|
|
40
|
-
rleString : str
|
|
41
|
-
(rle2string) A string representation of the array using run-length encoding that,
|
|
42
|
-
when evaluated as Python code, reproduces the original array structure.
|
|
43
|
-
|
|
44
|
-
Notes
|
|
45
|
-
-----
|
|
46
|
-
The "autoDecoding" feature means that the string representation evaluates directly
|
|
47
|
-
to the desired data structure without explicit decompression steps.
|
|
48
|
-
|
|
49
|
-
"""
|
|
50
|
-
def sliceNDArrayToNestedLists(arraySlice: NDArray[integer[Any]]) -> Any:
|
|
51
|
-
def getLengthOption(optionAsStr: str) -> int:
|
|
52
|
-
"""`assumeAddSpaces` characters: `,` 1; `]*` 2."""
|
|
53
|
-
return assumeAddSpaces * (optionAsStr.count(',') + optionAsStr.count(']*') * 2) + len(optionAsStr)
|
|
54
|
-
|
|
55
|
-
if arraySlice.ndim > 1:
|
|
56
|
-
axisOfOperation = 0
|
|
57
|
-
return [sliceNDArrayToNestedLists(arraySlice[index]) for index in range(arraySlice.shape[axisOfOperation])]
|
|
58
|
-
if arraySlice.ndim == 1:
|
|
59
|
-
arraySliceAsList: list[int | range] = []
|
|
60
|
-
cache_consecutiveGroup_addMe: dict[Iterator[Any], list[int] | list[range]] = {}
|
|
61
|
-
for consecutiveGroup in more_itertools.consecutive_groups(arraySlice.tolist()):
|
|
62
|
-
if consecutiveGroup in cache_consecutiveGroup_addMe:
|
|
63
|
-
addMe = cache_consecutiveGroup_addMe[consecutiveGroup]
|
|
64
|
-
else:
|
|
65
|
-
ImaSerious: list[int] = list(consecutiveGroup)
|
|
66
|
-
ImaRange = [range(ImaSerious[0], ImaSerious[-1] + 1)]
|
|
67
|
-
ImaRangeAsStr = python_minifier.minify(str(ImaRange)).replace('range(0,', 'range(').replace('range', '*range')
|
|
68
9
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
10
|
+
def removeExtraWhitespace(text: str) -> str:
|
|
11
|
+
"""Remove extra whitespace from string representation of Python data structures."""
|
|
12
|
+
# Remove spaces after commas
|
|
13
|
+
text = regex.sub(r',\s+', ',', text)
|
|
14
|
+
# Remove spaces after opening brackets/parens
|
|
15
|
+
text = regex.sub(r'([\[\(])\s+', r'\1', text)
|
|
16
|
+
# Remove spaces before closing brackets/parens
|
|
17
|
+
return regex.sub(r'\s+([\]\)])', r'\1', text)
|
|
73
18
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
lengthOption1 = getLengthOption(option1AsStr)
|
|
19
|
+
def autoDecodingRLE(arrayTarget: NDArray[integer[Any]], *, assumeAddSpaces: bool = False) -> str:
|
|
20
|
+
"""Transform a NumPy array into a compact, self-decoding run-length encoded string representation.
|
|
77
21
|
|
|
78
|
-
|
|
79
|
-
|
|
22
|
+
This function converts a NumPy array into a string that, when evaluated as Python code,
|
|
23
|
+
recreates the original array structure. The function employs two compression strategies:
|
|
24
|
+
1. Python's `range` syntax for consecutive integer sequences
|
|
25
|
+
2. Multiplication syntax for repeated elements
|
|
80
26
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
27
|
+
The resulting string representation is designed to be both human-readable and space-efficient,
|
|
28
|
+
especially for large cartesian mappings with repetitive patterns. When this string is used
|
|
29
|
+
as a data source, Python will automatically decode it into Python `list`, which if used as an
|
|
30
|
+
argument to `numpy.array()`, will recreate the original array structure.
|
|
85
31
|
|
|
86
|
-
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
arrayTarget : NDArray[integer[Any]]
|
|
35
|
+
(array2target) The NumPy array to be encoded.
|
|
36
|
+
assumeAddSpaces : bool = False
|
|
37
|
+
(assume2add2spaces) Affects internal length comparison during compression decisions.
|
|
38
|
+
This parameter doesn't directly change output format but influences whether
|
|
39
|
+
`range` or multiplication syntax is preferred in certain cases. The parameter
|
|
40
|
+
exists because the Abstract Syntax Tree (AST) inserts spaces in its string
|
|
41
|
+
representation.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
rleString : str
|
|
46
|
+
(rle2string) A string representation of the array using run-length encoding that,
|
|
47
|
+
when evaluated as Python code, reproduces the original array structure.
|
|
87
48
|
|
|
88
|
-
|
|
49
|
+
Notes
|
|
50
|
+
-----
|
|
51
|
+
The "autoDecoding" feature means that the string representation evaluates directly
|
|
52
|
+
to the desired data structure without explicit decompression steps.
|
|
89
53
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
54
|
+
"""
|
|
55
|
+
def sliceNDArrayToNestedLists(arraySlice: NDArray[integer[Any]]) -> Any:
|
|
56
|
+
def getLengthOption(optionAsStr: str) -> int:
|
|
57
|
+
"""`assumeAddSpaces` characters: `,` 1; `]*` 2."""
|
|
58
|
+
return assumeAddSpaces * (optionAsStr.count(',') + optionAsStr.count(']*') * 2) + len(optionAsStr)
|
|
59
|
+
|
|
60
|
+
if arraySlice.ndim > 1:
|
|
61
|
+
axisOfOperation = 0
|
|
62
|
+
return [sliceNDArrayToNestedLists(arraySlice[index]) for index in range(arraySlice.shape[axisOfOperation])]
|
|
63
|
+
if arraySlice.ndim == 1:
|
|
64
|
+
arraySliceAsList: list[int | range] = []
|
|
65
|
+
cache_consecutiveGroup_addMe: dict[Iterator[Any], list[int] | list[range]] = {}
|
|
66
|
+
for consecutiveGroup in more_itertools.consecutive_groups(arraySlice.tolist()):
|
|
67
|
+
if consecutiveGroup in cache_consecutiveGroup_addMe:
|
|
68
|
+
addMe = cache_consecutiveGroup_addMe[consecutiveGroup]
|
|
69
|
+
else:
|
|
70
|
+
ImaSerious: list[int] = list(consecutiveGroup)
|
|
71
|
+
ImaRange = [range(ImaSerious[0], ImaSerious[-1] + 1)]
|
|
72
|
+
ImaRangeAsStr = removeExtraWhitespace(str(ImaRange)).replace('range(0,', 'range(').replace('range', '*range')
|
|
73
|
+
|
|
74
|
+
option1 = ImaRange
|
|
75
|
+
option1AsStr = ImaRangeAsStr
|
|
76
|
+
option2 = ImaSerious
|
|
77
|
+
option2AsStr = None
|
|
78
|
+
|
|
79
|
+
# alpha, potential function
|
|
80
|
+
option1AsStr = option1AsStr or removeExtraWhitespace(str(option1))
|
|
81
|
+
lengthOption1 = getLengthOption(option1AsStr)
|
|
82
|
+
|
|
83
|
+
option2AsStr = option2AsStr or removeExtraWhitespace(str(option2))
|
|
84
|
+
lengthOption2 = getLengthOption(option2AsStr)
|
|
85
|
+
|
|
86
|
+
if lengthOption1 < lengthOption2:
|
|
87
|
+
addMe = option1
|
|
95
88
|
else:
|
|
96
|
-
|
|
97
|
-
malkovichAsList = list(more_itertools.run_length.decode([malkovichGrouped]))
|
|
98
|
-
malkovichMalkovich = f"[{malkovichGrouped[0]}]*{lengthMalkovich}"
|
|
89
|
+
addMe = option2
|
|
99
90
|
|
|
100
|
-
|
|
101
|
-
option1AsStr = malkovichMalkovich
|
|
102
|
-
option2 = malkovichAsList
|
|
103
|
-
option2AsStr = None
|
|
91
|
+
cache_consecutiveGroup_addMe[consecutiveGroup] = addMe
|
|
104
92
|
|
|
105
|
-
|
|
106
|
-
option1AsStr = option1AsStr or python_minifier.minify(str(option1))
|
|
107
|
-
lengthOption1 = getLengthOption(option1AsStr)
|
|
93
|
+
arraySliceAsList += addMe
|
|
108
94
|
|
|
109
|
-
|
|
110
|
-
|
|
95
|
+
listRangeAndTuple: list[int | range | tuple[int | range, int]] = []
|
|
96
|
+
cache_malkovichGrouped_addMe: dict[tuple[int | range, int], list[tuple[int | range, int]] | list[int | range]] = {}
|
|
97
|
+
for malkovichGrouped in more_itertools.run_length.encode(arraySliceAsList):
|
|
98
|
+
if malkovichGrouped in cache_malkovichGrouped_addMe:
|
|
99
|
+
addMe = cache_malkovichGrouped_addMe[malkovichGrouped]
|
|
100
|
+
else:
|
|
101
|
+
lengthMalkovich = malkovichGrouped[-1]
|
|
102
|
+
malkovichAsList = list(more_itertools.run_length.decode([malkovichGrouped]))
|
|
103
|
+
malkovichMalkovich = f"[{malkovichGrouped[0]}]*{lengthMalkovich}"
|
|
111
104
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
105
|
+
option1 = [malkovichGrouped]
|
|
106
|
+
option1AsStr = malkovichMalkovich
|
|
107
|
+
option2 = malkovichAsList
|
|
108
|
+
option2AsStr = None
|
|
109
|
+
|
|
110
|
+
# beta, potential function
|
|
111
|
+
option1AsStr = option1AsStr or removeExtraWhitespace(str(option1))
|
|
112
|
+
lengthOption1 = getLengthOption(option1AsStr)
|
|
113
|
+
|
|
114
|
+
option2AsStr = option2AsStr or removeExtraWhitespace(str(option2))
|
|
115
|
+
lengthOption2 = getLengthOption(option2AsStr)
|
|
116
|
+
|
|
117
|
+
if lengthOption1 < lengthOption2:
|
|
118
|
+
addMe = option1
|
|
119
|
+
else:
|
|
120
|
+
addMe = option2
|
|
116
121
|
|
|
117
|
-
|
|
122
|
+
cache_malkovichGrouped_addMe[malkovichGrouped] = addMe
|
|
118
123
|
|
|
119
|
-
|
|
124
|
+
listRangeAndTuple += addMe
|
|
120
125
|
|
|
121
|
-
|
|
122
|
-
|
|
126
|
+
return listRangeAndTuple
|
|
127
|
+
return arraySlice
|
|
123
128
|
|
|
124
|
-
|
|
129
|
+
arrayAsNestedLists = sliceNDArrayToNestedLists(arrayTarget)
|
|
125
130
|
|
|
126
|
-
|
|
131
|
+
arrayAsStr = removeExtraWhitespace(str(arrayAsNestedLists))
|
|
127
132
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
133
|
+
patternRegex = regex.compile(
|
|
134
|
+
"(?<!rang)(?:"
|
|
135
|
+
# Pattern 1: Comma ahead, bracket behind # noqa: ERA001
|
|
136
|
+
"(?P<joinAhead>,)\\((?P<malkovich>\\d+),(?P<multiply>\\d+)\\)(?P<bracketBehind>])|"
|
|
137
|
+
# Pattern 2: Bracket or start ahead, comma behind # noqa: ERA001
|
|
138
|
+
"(?P<bracketOrStartAhead>\\[|^.)\\((?P<malkovichMalkovich>\\d+),(?P<multiplyIDK>\\d+)\\)(?P<joinBehind>,)|"
|
|
139
|
+
# Pattern 3: Bracket ahead, bracket behind # noqa: ERA001
|
|
140
|
+
"(?P<bracketAhead>\\[)\\((?P<malkovichMalkovichMalkovich>\\d+),(?P<multiply_whatever>\\d+)\\)(?P<bracketBehindBracketBehind>])|"
|
|
141
|
+
# Pattern 4: Comma ahead, comma behind # noqa: ERA001
|
|
142
|
+
"(?P<joinAheadJoinAhead>,)\\((?P<malkovichMalkovichMalkovichMalkovich>\\d+),(?P<multiplyOrSomething>\\d+)\\)(?P<joinBehindJoinBehind>,)"
|
|
143
|
+
")"
|
|
144
|
+
)
|
|
140
145
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
146
|
+
def replacementByContext(match: regex.Match[str]) -> str:
|
|
147
|
+
"""Generate replacement string based on context patterns."""
|
|
148
|
+
elephino = match.groupdict()
|
|
149
|
+
joinAhead = elephino.get('joinAhead') or elephino.get('joinAheadJoinAhead')
|
|
150
|
+
malkovich = elephino.get('malkovich') or elephino.get('malkovichMalkovich') or elephino.get('malkovichMalkovichMalkovich') or elephino.get('malkovichMalkovichMalkovichMalkovich')
|
|
151
|
+
multiply = elephino.get('multiply') or elephino.get('multiplyIDK') or elephino.get('multiply_whatever') or elephino.get('multiplyOrSomething')
|
|
152
|
+
joinBehind = elephino.get('joinBehind') or elephino.get('joinBehindJoinBehind')
|
|
148
153
|
|
|
149
|
-
|
|
154
|
+
replaceAhead = "]+[" if joinAhead == "," else "["
|
|
150
155
|
|
|
151
|
-
|
|
156
|
+
replaceBehind = "+[" if joinBehind == "," else ""
|
|
152
157
|
|
|
153
|
-
|
|
158
|
+
return f"{replaceAhead}{malkovich}]*{multiply}{replaceBehind}"
|
|
154
159
|
|
|
155
|
-
|
|
156
|
-
|
|
160
|
+
arrayAsStr = patternRegex.sub(replacementByContext, arrayAsStr)
|
|
161
|
+
arrayAsStr = patternRegex.sub(replacementByContext, arrayAsStr)
|
|
157
162
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
163
|
+
# Replace `range(0,stop)` syntax with `range(stop)` syntax. # noqa: ERA001
|
|
164
|
+
# Add unpack operator `*` for automatic decoding when evaluated.
|
|
165
|
+
return arrayAsStr.replace('range(0,', 'range(').replace('range', '*range')
|
|
161
166
|
|
|
162
167
|
def stringItUp(*scrapPile: Any) -> list[str]:
|
|
163
168
|
"""Convert, if possible, every element in the input data structure to a string.
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
This module provides basic file I/O utilities such as importing callables from modules, safely creating directories, and writing to files or streams (pipes).
|
|
4
4
|
|
|
5
5
|
"""
|
|
6
|
-
|
|
6
|
+
from autoflake import fix_code as autoflake_fix_code
|
|
7
7
|
from hunterMakesPy import identifierDotAttribute
|
|
8
|
+
from isort import code as isort_code
|
|
8
9
|
from os import PathLike
|
|
9
10
|
from pathlib import Path, PurePath
|
|
10
11
|
from typing import Any, TYPE_CHECKING, TypeVar
|
|
@@ -97,6 +98,59 @@ def makeDirsSafely(pathFilename: Any) -> None:
|
|
|
97
98
|
with contextlib.suppress(OSError):
|
|
98
99
|
Path(pathFilename).parent.mkdir(parents=True, exist_ok=True)
|
|
99
100
|
|
|
101
|
+
settings_autoflakeDEFAULT: dict[str, list[str] | bool] = {
|
|
102
|
+
'additional_imports': [],
|
|
103
|
+
'expand_star_imports': True,
|
|
104
|
+
'remove_all_unused_imports': True,
|
|
105
|
+
'remove_duplicate_keys': False,
|
|
106
|
+
'remove_unused_variables': False,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
settings_isortDEFAULT: dict[str, int | str | list[str]] = {
|
|
110
|
+
"combine_as_imports": True,
|
|
111
|
+
"force_alphabetical_sort_within_sections": True,
|
|
112
|
+
"from_first": True,
|
|
113
|
+
"honor_noqa": True,
|
|
114
|
+
"indent": "\t",
|
|
115
|
+
"line_length": 120,
|
|
116
|
+
"lines_after_imports": 1,
|
|
117
|
+
"lines_between_types": 0,
|
|
118
|
+
"multi_line_output": 4,
|
|
119
|
+
"no_sections": True,
|
|
120
|
+
"skip": ["__init__.py"], # TODO think
|
|
121
|
+
"use_parentheses": True,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
def writePython(pythonSource: str, pathFilename: PathLike[Any] | PurePath | io.TextIOBase, settings: dict[str, dict[str, Any]] | None = None) -> None:
|
|
125
|
+
"""Format and write Python source code to a file or text stream.
|
|
126
|
+
|
|
127
|
+
(AI generated docstring)
|
|
128
|
+
|
|
129
|
+
This function processes Python source code through autoflake and isort formatters before writing to the specified destination.
|
|
130
|
+
The formatters remove unused imports, sort imports, and apply consistent code style according to the provided or default
|
|
131
|
+
settings.
|
|
132
|
+
|
|
133
|
+
Parameters
|
|
134
|
+
----------
|
|
135
|
+
pythonSource : str
|
|
136
|
+
The Python source code to format and write.
|
|
137
|
+
pathFilename : PathLike[Any] | PurePath | io.TextIOBase
|
|
138
|
+
The target destination: either a file path or an open text stream.
|
|
139
|
+
settings : dict[str, dict[str, Any]] | None = None
|
|
140
|
+
Configuration for the formatters. Keys are `'autoflake'` and `'isort'`, each mapping to a dictionary of formatter-specific
|
|
141
|
+
settings. If `None`, default settings are used for both formatters.
|
|
142
|
+
|
|
143
|
+
"""
|
|
144
|
+
if settings is None:
|
|
145
|
+
settings = {}
|
|
146
|
+
|
|
147
|
+
settings_autoflake: dict[str, Any] = settings.get('autoflake', settings_autoflakeDEFAULT)
|
|
148
|
+
pythonSource = autoflake_fix_code(pythonSource, **settings_autoflake)
|
|
149
|
+
|
|
150
|
+
settings_isort: dict[str, Any] = settings.get('isort', settings_isortDEFAULT)
|
|
151
|
+
pythonSource = isort_code(pythonSource, **settings_isort)
|
|
152
|
+
writeStringToHere(pythonSource + '\n', pathFilename)
|
|
153
|
+
|
|
100
154
|
def writeStringToHere(this: str, pathFilename: PathLike[Any] | PurePath | io.TextIOBase) -> None:
|
|
101
155
|
"""Write a string to a file or text stream.
|
|
102
156
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
from collections.abc import Callable, Iterable, Iterator
|
|
3
3
|
from decimal import Decimal
|
|
4
4
|
from fractions import Fraction
|
|
5
|
-
from hunterMakesPy import stringItUp, updateExtendPolishDictionaryLists
|
|
5
|
+
from hunterMakesPy import autoDecodingRLE, stringItUp, updateExtendPolishDictionaryLists
|
|
6
6
|
from hunterMakesPy.tests.conftest import standardizedEqualTo
|
|
7
7
|
from numpy.typing import NDArray
|
|
8
8
|
from typing import Any, Literal
|
|
@@ -11,9 +11,6 @@ import numpy
|
|
|
11
11
|
import pytest
|
|
12
12
|
import sys
|
|
13
13
|
|
|
14
|
-
if sys.version_info < (3, 14):
|
|
15
|
-
from hunterMakesPy import autoDecodingRLE
|
|
16
|
-
|
|
17
14
|
class CustomIterable:
|
|
18
15
|
def __init__(self, items: Iterable[Any]) -> None: self.items = items
|
|
19
16
|
def __iter__(self) -> Iterator[Any]: return iter(self.items)
|
|
@@ -99,27 +96,26 @@ def testUpdateExtendPolishDictionaryLists(description: str, value_dictionaryList
|
|
|
99
96
|
|
|
100
97
|
# ruff: noqa: RUF005
|
|
101
98
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
standardizedEqualTo(expected, autoDecodingRLE, value_arrayTarget)
|
|
99
|
+
@pytest.mark.parametrize("description,value_arrayTarget,expected", [
|
|
100
|
+
("One range", numpy.array(list(range(50,60))), "[*range(50,60)]"),
|
|
101
|
+
("Value, range", numpy.array([123]+list(range(71,81))), "[123,*range(71,81)]"),
|
|
102
|
+
("range, value", numpy.array(list(range(91,97))+[101]), "[*range(91,97),101]"),
|
|
103
|
+
("Value, range, value", numpy.array([151]+list(range(163,171))+[181]), "[151,*range(163,171),181]"),
|
|
104
|
+
("Repeat values", numpy.array([191, 191, 191]), "[191]*3"),
|
|
105
|
+
("Value with repeat", numpy.array([211, 223, 223, 223]), "[211]+[223]*3"),
|
|
106
|
+
("Range with repeat", numpy.array(list(range(251,257))+[271, 271, 271]), "[*range(251,257)]+[271]*3"),
|
|
107
|
+
("Value, range, repeat", numpy.array([281]+list(range(291,297))+[307, 307]), "[281,*range(291,297)]+[307]*2"),
|
|
108
|
+
("repeat, value", numpy.array([313, 313, 313, 331, 331, 349]), "[313]*3+[331]*2+[349]"),
|
|
109
|
+
("repeat, range", numpy.array([373, 373, 373]+list(range(383,389))), "[373]*3+[*range(383,389)]"),
|
|
110
|
+
("repeat, range, value", numpy.array(7*[401]+list(range(409,415))+[421]), "[401]*7+[*range(409,415),421]"),
|
|
111
|
+
("Repeated primes", numpy.array([431, 431, 431, 443, 443, 457]), "[431]*3+[443]*2+[457]"),
|
|
112
|
+
("Two Ranges", numpy.array(list(range(461,471))+list(range(479,487))), "[*range(461,471),*range(479,487)]"),
|
|
113
|
+
("2D array primes", numpy.array([[491, 499, 503], [509, 521, 523]]), "[[491,499,503],[509,521,523]]"),
|
|
114
|
+
("3D array primes", numpy.array([[[541, 547], [557, 563]], [[569, 571], [577, 587]]]), "[[[541,547],[557,563]],[[569,571],[577,587]]]"),
|
|
115
|
+
], ids=lambda x: x if isinstance(x, str) else "")
|
|
116
|
+
def testAutoDecodingRLE(description: str, value_arrayTarget: NDArray[numpy.integer[Any]], expected: str) -> None:
|
|
117
|
+
"""Test autoDecodingRLE with various input arrays."""
|
|
118
|
+
standardizedEqualTo(expected, autoDecodingRLE, value_arrayTarget)
|
|
123
119
|
|
|
124
120
|
# Helper functions for generating RLE test data
|
|
125
121
|
def generateCartesianMapping(dimensions: tuple[int, int], formula: Callable[[int, int], int]) -> NDArray[Any]:
|
|
@@ -228,98 +224,97 @@ def generateAlternatingColumns(dimensions: tuple[int, int], blockSize: int = 1)
|
|
|
228
224
|
|
|
229
225
|
return generateCartesianMapping(dimensions, columnFormula)
|
|
230
226
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
assert encodedLength <= rawStrLength, f"RLE encoded string ({encodedLength}) should be shorter than raw string ({rawStrLength})"
|
|
227
|
+
@pytest.mark.parametrize("description,value_arrayTarget", [
|
|
228
|
+
# Basic test cases with simple patterns
|
|
229
|
+
("Simple range", numpy.array(list(range(50,60)))),
|
|
230
|
+
|
|
231
|
+
# Chessboard patterns
|
|
232
|
+
("Small chessboard", generateChessboard((8, 8))),
|
|
233
|
+
|
|
234
|
+
# Alternating columns - creates patterns with good RLE opportunities
|
|
235
|
+
("Alternating columns", generateAlternatingColumns((5, 20), 2)),
|
|
236
|
+
|
|
237
|
+
# Step pattern - creates horizontal runs
|
|
238
|
+
("Step pattern", generateStepPattern((6, 30), 3)),
|
|
239
|
+
|
|
240
|
+
# Repeating zones - creates horizontal bands
|
|
241
|
+
("Repeating zones", generateRepeatingZones((40, 40), 8)),
|
|
242
|
+
|
|
243
|
+
# Tile pattern - creates complex repeating regions
|
|
244
|
+
("Tile pattern", generateTilePattern((15, 15), 5)),
|
|
245
|
+
|
|
246
|
+
# Signed quadratic function - includes negative values
|
|
247
|
+
("Signed quadratic", generateSignedQuadraticFunction((10, 10))),
|
|
248
|
+
|
|
249
|
+
# Prime modulo matrix - periodic patterns
|
|
250
|
+
("Prime modulo", generatePrimeModuloMatrix((12, 12), 7)),
|
|
251
|
+
|
|
252
|
+
# Wave pattern - smooth gradients
|
|
253
|
+
("Wave pattern", generateWavePattern((20, 20))),
|
|
254
|
+
|
|
255
|
+
# Spiral pattern - complex pattern with good RLE potential
|
|
256
|
+
("Spiral pattern", generateSpiralPattern((15, 15), 2)),
|
|
257
|
+
], ids=lambda x: x if isinstance(x, str) else "")
|
|
258
|
+
def testAutoDecodingRLEWithRealisticData(description: str, value_arrayTarget: NDArray[numpy.integer[Any]]) -> None:
|
|
259
|
+
"""Test autoDecodingRLE with more realistic data patterns."""
|
|
260
|
+
# Here we test the function behavior rather than expected string output
|
|
261
|
+
resultRLE = autoDecodingRLE(value_arrayTarget)
|
|
262
|
+
|
|
263
|
+
# Test that the result is a valid string
|
|
264
|
+
assert isinstance(resultRLE, str)
|
|
265
|
+
|
|
266
|
+
# Test that the result contains the expected syntax elements
|
|
267
|
+
assert "[" in resultRLE, f"Result should contain list syntax: {resultRLE}"
|
|
268
|
+
assert "]" in resultRLE, f"Result should contain list syntax: {resultRLE}"
|
|
269
|
+
|
|
270
|
+
# Check that the result is more compact than the raw string representation
|
|
271
|
+
rawStrLength = len(str(value_arrayTarget.tolist()))
|
|
272
|
+
encodedLength = len(resultRLE)
|
|
273
|
+
assert encodedLength <= rawStrLength, f"Encoded string ({encodedLength}) should be shorter than raw string ({rawStrLength})"
|
|
274
|
+
|
|
275
|
+
@pytest.mark.parametrize("description,addSpaces", [
|
|
276
|
+
("With spaces", True),
|
|
277
|
+
("Without spaces", False),
|
|
278
|
+
], ids=lambda x: x if isinstance(x, str) else "")
|
|
279
|
+
def testAutoDecodingRLEWithSpaces(description: str, addSpaces: bool) -> None:
|
|
280
|
+
"""Test that the addSpaces parameter affects the internal comparison logic.
|
|
281
|
+
|
|
282
|
+
Note: addSpaces doesn't directly change the output format, it just changes
|
|
283
|
+
the comparison when measuring the length of the string representation.
|
|
284
|
+
The feature exists because `ast` inserts spaces in its string representation.
|
|
285
|
+
"""
|
|
286
|
+
# Create a pattern that has repeated sequences to trigger the RLE logic
|
|
287
|
+
arrayTarget = generateRepeatingZones((10, 10), 2)
|
|
288
|
+
|
|
289
|
+
# Test both configurations
|
|
290
|
+
resultWithSpacesFlag = autoDecodingRLE(arrayTarget, assumeAddSpaces=addSpaces)
|
|
291
|
+
resultNoSpacesFlag = autoDecodingRLE(arrayTarget, assumeAddSpaces=False)
|
|
292
|
+
|
|
293
|
+
# When addSpaces=True, the internal length comparisons change
|
|
294
|
+
# but the actual output format doesn't necessarily differ
|
|
295
|
+
# Just verify the function runs without errors in both cases
|
|
296
|
+
assert isinstance(resultWithSpacesFlag, str)
|
|
297
|
+
assert isinstance(resultNoSpacesFlag, str)
|
|
298
|
+
|
|
299
|
+
def testAutoDecodingRLELargeCartesianMapping() -> None:
|
|
300
|
+
"""Test autoDecodingRLE with a large (100x100) cartesian mapping."""
|
|
301
|
+
dimensions = (100, 100)
|
|
302
|
+
|
|
303
|
+
# Generate a large cartesian mapping with a complex pattern
|
|
304
|
+
def complexFormula(x: int, y: int) -> int:
|
|
305
|
+
return ((x * 17) % 11 + (y * 13) % 7) % 10
|
|
306
|
+
|
|
307
|
+
arrayMapping = generateCartesianMapping(dimensions, complexFormula)
|
|
308
|
+
|
|
309
|
+
# Verify the function works with large arrays
|
|
310
|
+
resultRLE = autoDecodingRLE(arrayMapping)
|
|
311
|
+
|
|
312
|
+
# The result should be a valid string representation
|
|
313
|
+
assert isinstance(resultRLE, str)
|
|
314
|
+
assert "[" in resultRLE
|
|
315
|
+
assert "]" in resultRLE
|
|
316
|
+
|
|
317
|
+
# The RLE encoding should be more compact than the raw representation
|
|
318
|
+
rawStrLength = len(str(arrayMapping.tolist()))
|
|
319
|
+
encodedLength = len(resultRLE)
|
|
320
|
+
assert encodedLength <= rawStrLength, f"RLE encoded string ({encodedLength}) should be shorter than raw string ({rawStrLength})"
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# pyright: standard
|
|
2
|
-
from hunterMakesPy import
|
|
2
|
+
from hunterMakesPy import (
|
|
3
|
+
importLogicalPath2Identifier, importPathFilename2Identifier, makeDirsSafely, writePython, writeStringToHere)
|
|
3
4
|
from hunterMakesPy.tests.conftest import standardizedEqualTo
|
|
4
5
|
import io
|
|
5
6
|
import math
|
|
@@ -261,3 +262,188 @@ def testImportPathFilename2IdentifierWithValidFileInvalidIdentifier(
|
|
|
261
262
|
identifierTarget
|
|
262
263
|
)
|
|
263
264
|
|
|
265
|
+
|
|
266
|
+
@pytest.mark.parametrize(
|
|
267
|
+
"pythonSourceTarget, expectedFormattedContent",
|
|
268
|
+
[
|
|
269
|
+
(
|
|
270
|
+
"import sys\nimport os\nimport math\n\ndef fibonacciFunction():\n return 13\n",
|
|
271
|
+
"\ndef fibonacciFunction():\n return 13\n\n"
|
|
272
|
+
),
|
|
273
|
+
(
|
|
274
|
+
"from pathlib import Path\nimport sys\nimport os\n\ndef primeFunction():\n return 17\n",
|
|
275
|
+
"\ndef primeFunction():\n return 17\n\n"
|
|
276
|
+
),
|
|
277
|
+
(
|
|
278
|
+
"import unused\nimport sys\n\nvalueCardinal = sys.version\n",
|
|
279
|
+
"import sys\n\nvalueCardinal = sys.version\n\n"
|
|
280
|
+
),
|
|
281
|
+
(
|
|
282
|
+
"import math\n\nvalueFibonacci = math.sqrt(21)\n",
|
|
283
|
+
"import math\n\nvalueFibonacci = math.sqrt(21)\n\n"
|
|
284
|
+
),
|
|
285
|
+
]
|
|
286
|
+
)
|
|
287
|
+
def testWritePythonFormatsAndWritesToFile(
|
|
288
|
+
pathTmpTesting: pathlib.Path,
|
|
289
|
+
pythonSourceTarget: str,
|
|
290
|
+
expectedFormattedContent: str
|
|
291
|
+
) -> None:
|
|
292
|
+
"""Test that writePython formats Python source code and writes it to files."""
|
|
293
|
+
pathFilenameTarget = pathTmpTesting / "formattedModule.py"
|
|
294
|
+
writePython(pythonSourceTarget, pathFilenameTarget)
|
|
295
|
+
|
|
296
|
+
assert pathFilenameTarget.exists(), (
|
|
297
|
+
f"\nTesting: `writePython(..., {pathFilenameTarget})`\n"
|
|
298
|
+
f"Expected: File {pathFilenameTarget} to exist\n"
|
|
299
|
+
f"Got: exists={pathFilenameTarget.exists()}"
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
contentActual = pathFilenameTarget.read_text(encoding="utf-8")
|
|
303
|
+
assert contentActual == expectedFormattedContent, (
|
|
304
|
+
f"\nTesting: `writePython(...)`\n"
|
|
305
|
+
f"Expected content:\n{repr(expectedFormattedContent)}\n"
|
|
306
|
+
f"Got content:\n{repr(contentActual)}"
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@pytest.mark.parametrize(
|
|
311
|
+
"pythonSourceTarget, expectedFormattedContent",
|
|
312
|
+
[
|
|
313
|
+
(
|
|
314
|
+
"import sys\nimport unused\n\ndef cardinalFunction():\n return sys.version\n",
|
|
315
|
+
"import sys\n\ndef cardinalFunction():\n return sys.version\n\n"
|
|
316
|
+
),
|
|
317
|
+
(
|
|
318
|
+
"from pathlib import Path\nfrom os import getcwd\nimport math\n\nvalueSequence = getcwd()\n",
|
|
319
|
+
"from os import getcwd\n\nvalueSequence = getcwd()\n\n"
|
|
320
|
+
),
|
|
321
|
+
]
|
|
322
|
+
)
|
|
323
|
+
def testWritePythonFormatsAndWritesToStream(
|
|
324
|
+
pythonSourceTarget: str,
|
|
325
|
+
expectedFormattedContent: str
|
|
326
|
+
) -> None:
|
|
327
|
+
"""Test that writePython formats Python source code and writes it to IO streams."""
|
|
328
|
+
streamMemory = io.StringIO()
|
|
329
|
+
writePython(pythonSourceTarget, streamMemory)
|
|
330
|
+
|
|
331
|
+
contentActual = streamMemory.getvalue()
|
|
332
|
+
assert contentActual == expectedFormattedContent, (
|
|
333
|
+
f"\nTesting: `writePython(..., StringIO)`\n"
|
|
334
|
+
f"Expected content:\n{repr(expectedFormattedContent)}\n"
|
|
335
|
+
f"Got content:\n{repr(contentActual)}"
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@pytest.mark.parametrize(
|
|
340
|
+
"pythonSourceTarget, settingsCustom, expectedFormattedContent",
|
|
341
|
+
[
|
|
342
|
+
(
|
|
343
|
+
"import math\nimport unused\n\nvalueFibonacci = 34\n\ndef fibonacciFunction():\n return math.sqrt(13)\n",
|
|
344
|
+
{'autoflake': {'remove_all_unused_imports': True, 'remove_unused_variables': False}},
|
|
345
|
+
"import math\n\nvalueFibonacci = 34\n\ndef fibonacciFunction():\n return math.sqrt(13)\n\n"
|
|
346
|
+
),
|
|
347
|
+
(
|
|
348
|
+
"from pathlib import Path\nimport sys\n\nvaluePrime = Path.cwd()\n",
|
|
349
|
+
{'isort': {'force_alphabetical_sort_within_sections': False, 'from_first': False}},
|
|
350
|
+
"from pathlib import Path\n\nvaluePrime = Path.cwd()\n\n"
|
|
351
|
+
),
|
|
352
|
+
]
|
|
353
|
+
)
|
|
354
|
+
def testWritePythonWithCustomSettings(
|
|
355
|
+
pathTmpTesting: pathlib.Path,
|
|
356
|
+
pythonSourceTarget: str,
|
|
357
|
+
settingsCustom: dict[str, dict[str, object]],
|
|
358
|
+
expectedFormattedContent: str
|
|
359
|
+
) -> None:
|
|
360
|
+
"""Test that writePython respects custom formatter settings."""
|
|
361
|
+
pathFilenameTarget = pathTmpTesting / "customFormattedModule.py"
|
|
362
|
+
writePython(pythonSourceTarget, pathFilenameTarget, settingsCustom)
|
|
363
|
+
|
|
364
|
+
contentActual = pathFilenameTarget.read_text(encoding="utf-8")
|
|
365
|
+
assert contentActual == expectedFormattedContent, (
|
|
366
|
+
f"\nTesting: `writePython(..., custom settings)`\n"
|
|
367
|
+
f"Expected content:\n{repr(expectedFormattedContent)}\n"
|
|
368
|
+
f"Got content:\n{repr(contentActual)}"
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@pytest.mark.parametrize(
|
|
373
|
+
"pythonSourceTarget",
|
|
374
|
+
[
|
|
375
|
+
"import math\nimport sys\n\nvalueFibonacci = 34\n",
|
|
376
|
+
"from pathlib import Path\n\nvalueCardinal = 'SW'\n",
|
|
377
|
+
"def primeFunction():\n return 37\n",
|
|
378
|
+
]
|
|
379
|
+
)
|
|
380
|
+
def testWritePythonCreatesNestedDirectories(
|
|
381
|
+
pathTmpTesting: pathlib.Path,
|
|
382
|
+
pythonSourceTarget: str
|
|
383
|
+
) -> None:
|
|
384
|
+
"""Test that writePython creates nested directories when writing to files."""
|
|
385
|
+
pathFilenameTarget = pathTmpTesting / "nested" / "directories" / "module.py"
|
|
386
|
+
writePython(pythonSourceTarget, pathFilenameTarget)
|
|
387
|
+
|
|
388
|
+
assert pathFilenameTarget.exists(), (
|
|
389
|
+
f"\nTesting: `writePython(..., {pathFilenameTarget})`\n"
|
|
390
|
+
f"Expected: File {pathFilenameTarget} to exist\n"
|
|
391
|
+
f"Got: exists={pathFilenameTarget.exists()}"
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
assert pathFilenameTarget.parent.exists(), (
|
|
395
|
+
f"\nTesting: `writePython(..., {pathFilenameTarget})`\n"
|
|
396
|
+
f"Expected: Parent directory {pathFilenameTarget.parent} to exist\n"
|
|
397
|
+
f"Got: exists={pathFilenameTarget.parent.exists()}"
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@pytest.mark.parametrize(
|
|
402
|
+
"pythonSourceTarget, expectedContainsImport",
|
|
403
|
+
[
|
|
404
|
+
("import math\n\nvaluePrime = math.sqrt(41)\n", "import math"),
|
|
405
|
+
("from os import getcwd\n\nvalueSequence = getcwd()\n", "from os import getcwd"),
|
|
406
|
+
("import sys\n\nvalueFibonacci = sys.version\n", "import sys"),
|
|
407
|
+
]
|
|
408
|
+
)
|
|
409
|
+
def testWritePythonPreservesUsedImports(
|
|
410
|
+
pathTmpTesting: pathlib.Path,
|
|
411
|
+
pythonSourceTarget: str,
|
|
412
|
+
expectedContainsImport: str
|
|
413
|
+
) -> None:
|
|
414
|
+
"""Test that writePython preserves imports that are actually used in the code."""
|
|
415
|
+
pathFilenameTarget = pathTmpTesting / "preservedImports.py"
|
|
416
|
+
writePython(pythonSourceTarget, pathFilenameTarget)
|
|
417
|
+
|
|
418
|
+
contentActual = pathFilenameTarget.read_text(encoding="utf-8")
|
|
419
|
+
assert expectedContainsImport in contentActual, (
|
|
420
|
+
f"\nTesting: `writePython(...)` preserves used imports\n"
|
|
421
|
+
f"Expected content to contain: {expectedContainsImport}\n"
|
|
422
|
+
f"Got content:\n{contentActual}"
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@pytest.mark.parametrize(
|
|
427
|
+
"pythonSourceTarget, expectedNotContainsImport",
|
|
428
|
+
[
|
|
429
|
+
("import math\nimport unused\n\nvaluePrime = 43\n", "import unused"),
|
|
430
|
+
("from os import getcwd, unused\n\nvalueSequence = getcwd()\n", "unused"),
|
|
431
|
+
("import sys\nimport collections\n\nvalueFibonacci = sys.version\n", "import collections"),
|
|
432
|
+
]
|
|
433
|
+
)
|
|
434
|
+
def testWritePythonRemovesUnusedImports(
|
|
435
|
+
pathTmpTesting: pathlib.Path,
|
|
436
|
+
pythonSourceTarget: str,
|
|
437
|
+
expectedNotContainsImport: str
|
|
438
|
+
) -> None:
|
|
439
|
+
"""Test that writePython removes imports that are not used in the code."""
|
|
440
|
+
pathFilenameTarget = pathTmpTesting / "removedImports.py"
|
|
441
|
+
writePython(pythonSourceTarget, pathFilenameTarget)
|
|
442
|
+
|
|
443
|
+
contentActual = pathFilenameTarget.read_text(encoding="utf-8")
|
|
444
|
+
assert expectedNotContainsImport not in contentActual, (
|
|
445
|
+
f"\nTesting: `writePython(...)` removes unused imports\n"
|
|
446
|
+
f"Expected content to NOT contain: {expectedNotContainsImport}\n"
|
|
447
|
+
f"Got content:\n{contentActual}"
|
|
448
|
+
)
|
|
449
|
+
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: hunterMakesPy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Easy Python functions making making functional Python functions easier.
|
|
5
5
|
Author-email: Hunter Hogan <HunterHogan@pm.me>
|
|
6
6
|
License: CC-BY-NC-4.0
|
|
@@ -9,7 +9,7 @@ Project-URL: Homepage, https://github.com/hunterhogan/hunterMakesPy
|
|
|
9
9
|
Project-URL: Issues, https://github.com/hunterhogan/hunterMakesPy/issues
|
|
10
10
|
Project-URL: Repository, https://github.com/hunterhogan/hunterMakesPy
|
|
11
11
|
Keywords: attribute loading,concurrency limit,configuration,defensive programming,dictionary merging,directory creation,dynamic import,error propagation,file system utilities,input validation,integer parsing,module loading,nested data structures,package settings,parameter validation,pytest,string extraction,test utilities
|
|
12
|
-
Classifier: Development Status ::
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
13
|
Classifier: Environment :: Console
|
|
14
14
|
Classifier: Framework :: Pytest
|
|
15
15
|
Classifier: Intended Audience :: Developers
|
|
@@ -30,13 +30,12 @@ Classifier: Typing :: Typed
|
|
|
30
30
|
Requires-Python: >=3.11
|
|
31
31
|
Description-Content-Type: text/markdown
|
|
32
32
|
License-File: LICENSE
|
|
33
|
+
Requires-Dist: autoflake
|
|
33
34
|
Requires-Dist: charset_normalizer
|
|
35
|
+
Requires-Dist: isort
|
|
34
36
|
Requires-Dist: more_itertools
|
|
35
37
|
Requires-Dist: numpy
|
|
36
|
-
Requires-Dist: python_minifier; python_version < "3.14"
|
|
37
38
|
Provides-Extra: development
|
|
38
|
-
Requires-Dist: mypy; extra == "development"
|
|
39
|
-
Requires-Dist: pyupgrade; extra == "development"
|
|
40
39
|
Requires-Dist: setuptools-scm; extra == "development"
|
|
41
40
|
Provides-Extra: testing
|
|
42
41
|
Requires-Dist: pytest; extra == "testing"
|
|
@@ -165,13 +164,4 @@ def test_myFunction(nameOfTest, callablePytest):
|
|
|
165
164
|
[](https://HunterThinks.com/support)
|
|
166
165
|
[](https://www.youtube.com/@HunterHogan)
|
|
167
166
|
|
|
168
|
-
## How to code
|
|
169
|
-
|
|
170
|
-
Coding One Step at a Time:
|
|
171
|
-
|
|
172
|
-
0. WRITE CODE.
|
|
173
|
-
1. Don't write stupid code that's hard to revise.
|
|
174
|
-
2. Write good code.
|
|
175
|
-
3. When revising, write better code.
|
|
176
|
-
|
|
177
167
|
[](https://creativecommons.org/licenses/by-nc/4.0/)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
hunterMakesPy/__init__.py,sha256=
|
|
1
|
+
hunterMakesPy/__init__.py,sha256=5UWFiB9YCTei76LfMCYipSFSIMVspw2jhcca_NmynGI,1431
|
|
2
2
|
hunterMakesPy/_theSSOT.py,sha256=lkLOG3oTIWNKD_ULX55chlUGNqCHgqVIrBvolvK1vbQ,153
|
|
3
|
-
hunterMakesPy/coping.py,sha256=
|
|
4
|
-
hunterMakesPy/dataStructures.py,sha256=
|
|
5
|
-
hunterMakesPy/filesystemToolkit.py,sha256=
|
|
3
|
+
hunterMakesPy/coping.py,sha256=7NBwaGutEr6Q-2mIz65M69NkrbpG24u1I5HXx6VaAWI,6057
|
|
4
|
+
hunterMakesPy/dataStructures.py,sha256=WC6MO0LjrhCEv0prd5hlC9efG4DuL9lEm-fWlhHUVUw,11509
|
|
5
|
+
hunterMakesPy/filesystemToolkit.py,sha256=loBn6GcScIucrMpjopGdZu6ja3nTkyBfcSiH9_P4cxY,6773
|
|
6
6
|
hunterMakesPy/parseParameters.py,sha256=1mwGNVIZ1x23k_di3lhOhQb8QMXMUCHgt7xw3NRzDXs,11814
|
|
7
7
|
hunterMakesPy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
8
|
hunterMakesPy/pytestForYourUse.py,sha256=GiN1C1gTTM0ZunRPEMnrKlLQLMdH0wF_ZGr_RPgRjjA,500
|
|
@@ -10,11 +10,11 @@ hunterMakesPy/theTypes.py,sha256=C2d0uLn1VIx6_2CK41it3IP7iplSQqe51tzWc-RT320,306
|
|
|
10
10
|
hunterMakesPy/tests/__init__.py,sha256=C_FzfKDi_VrGVxlenWHyOYtKShAKlt3KW14jeRx1mQI,224
|
|
11
11
|
hunterMakesPy/tests/conftest.py,sha256=NZQPRiwvGhP16hJ6WGGm9eKLxfQArYV8E9X12YzSpP0,2827
|
|
12
12
|
hunterMakesPy/tests/test_coping.py,sha256=mH89TUAL6fJanBLlhdVlCNNQqm5OpdcQMP_p5W2JJwo,9860
|
|
13
|
-
hunterMakesPy/tests/test_dataStructures.py,sha256=
|
|
14
|
-
hunterMakesPy/tests/test_filesystemToolkit.py,sha256=
|
|
13
|
+
hunterMakesPy/tests/test_dataStructures.py,sha256=OouddHjN-Km26U92jYwnjYeP6_Y2DrJLgq3qD_8GvGw,16393
|
|
14
|
+
hunterMakesPy/tests/test_filesystemToolkit.py,sha256=_CoSMzstJwWZ_tkNyIqclOIIqTaY2tYfUIgxGFfC0Jk,15335
|
|
15
15
|
hunterMakesPy/tests/test_parseParameters.py,sha256=80npsoWcCackjxvoW2dMXMpHeale7fuRXyXp78MibLs,14037
|
|
16
|
-
huntermakespy-0.
|
|
17
|
-
huntermakespy-0.
|
|
18
|
-
huntermakespy-0.
|
|
19
|
-
huntermakespy-0.
|
|
20
|
-
huntermakespy-0.
|
|
16
|
+
huntermakespy-0.3.0.dist-info/licenses/LICENSE,sha256=NxH5Y8BdC-gNU-WSMwim3uMbID2iNDXJz7fHtuTdXhk,19346
|
|
17
|
+
huntermakespy-0.3.0.dist-info/METADATA,sha256=SNJ2cKtyLw97-NGIsvCQsqllBJ82DW9Ipxntx2Qvmzk,6290
|
|
18
|
+
huntermakespy-0.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
huntermakespy-0.3.0.dist-info/top_level.txt,sha256=Uh4bj8EDTdsRpqY1VlK_his_B4HDfZ6Tqrwhoj75P_w,14
|
|
20
|
+
huntermakespy-0.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|