Typed Python tools that make your type checker more useful, validate parameters, and show which call failed a test.
- Type checking: remove
Nonefrom a return type, and require a function to have a name. - Parameters: validate integers, calculate a number of workers, and read
True,False, orNonefrom text. - Tests: put the call, its result, and the expected result in the failure message.
- Data: collect strings from nested data, merge dictionaries of lists, and write a NumPy array as short Python code.
- Files and imports: write Python files without unused imports, and import an object from a Python file.
- Package settings: find the name and directory of your package.
- Readable code and output: give a reason for each
1and-1, and color text in the terminal.
The dependencies are autoflake, isort, and NumPy.
I want raiseIfNone and CallableFunction to make your type checker more useful. I'm not trying to suppress errors or hide problems.
I use raiseIfNone to cure type-checker-nihilism: that's when "or None" return types cause your type checker to repeatedly say, "You can't do that because the value might be None."
raiseIfNone checks the value when your code runs. If the value is None, it raises a ValueError with your message. Otherwise, it returns the value, and your type checker knows that the value isn't None.
from hunterMakesPy import raiseIfNone
import re as regex
match = raiseIfNone(regex.search(r"\d+", "port 8080"), "I need a port number.")
match.group() # "8080"Not every Callable has a __name__. For example, a functools.partial object doesn't have one. Type checkers handle this gap between reality and type checking in different ways:
- Some pretend that every
Callablehas a name. That's a lie, and it could give you runtime errors that you didn't expect. - Some say that they can't guarantee the name. You have to guarantee it yourself, which defeats the purpose of a type checker.
CallableFunction tries to bridge the gap. You write the signature as you would for Callable, but the annotation also requires __name__ and __qualname__. Your code can use the name, and your type checker can find callers that pass something without one.
from hunterMakesPy import CallableFunction
from math import factorial
def reportCall(function: CallableFunction[[int], int], number: int) -> str:
return f"{function.__name__}({number}) = {function(number)}"
reportCall(factorial, 5) # "factorial(5) = 120"intInnit converts a collection to a list of integers. Each element can be text, a float, UTF-8 bytes, or another type, but its value must be an integer. intInnit never rounds a number, and it rejects True and False.
from hunterMakesPy.parseParameters import intInnit
ports = intInnit(["8080", 443, "22"], "server_ports")
print(ports) # [8080, 443, 22]
intInnit(["8080", 443.5], "server_ports")The last line raises an error that names the value and your parameter:
ValueError: I received `allegedInt = 443.5` of type `float` as an element in a `list`, but `server_ports` must have integers in type(s) `<class 'list'>`.
With defineConcurrencyLimit, one parameter can be the number of workers, the fraction of CPUs to use, or the CPUs to leave free.
from hunterMakesPy.parseParameters import defineConcurrencyLimit
workers = defineConcurrencyLimit(limit=0.75)On a computer with 8 CPUs:
limit |
Workers |
|---|---|
0.75 |
6 |
4 |
4 |
-2 |
6 |
-0.25 |
6 |
True |
1 |
False, None, or 0 |
8 |
The result is always at least 1. On Windows, it is at most 61, which is the limit of ProcessPoolExecutor.
oopsieKwargsie ignores capitalization and surrounding whitespace. It returns other strings unchanged.
from hunterMakesPy.parseParameters import oopsieKwargsie
oopsieKwargsie("True") # True
oopsieKwargsie("none") # None
oopsieKwargsie("hello") # "hello"assertEqualTo puts the function, its arguments, the result, and the expected result on one line. In this example, the expected result, 5, is wrong on purpose:
from hunterMakesPy.parseParameters import defineConcurrencyLimit
from hunterMakesPy.tests import assertEqualTo
assertEqualTo(defineConcurrencyLimit(limit=-2, cpuTotal=8), 5, defineConcurrencyLimit.__name__, limit=-2, cpuTotal=8)AssertionError: defineConcurrencyLimit(limit=-2, cpuTotal=8) = 6, but expected = 5.
assert_approx compares numbers within tolerances. assert_array_equal and assert_allclose compare the values, shapes, and dtypes of NumPy arrays. To use hunterMakesPy.tests, you also need pytest, which isn't a dependency of hunterMakesPy.
stringItUp puts the text from nested containers in one list, including the keys of dictionaries. It converts numbers to strings and uses the names of functions.
from hunterMakesPy.dataStructures import stringItUp
strings = stringItUp({"users": ["alice"], "config": {"host": "localhost"}})
# ["users", "alice", "config", "host", "localhost"]updateExtendPolishDictionaryLists combines the lists that have the same key and returns a new dictionary. It can also remove duplicates and sort each list.
from hunterMakesPy.dataStructures import updateExtendPolishDictionaryLists
merged = updateExtendPolishDictionaryLists(
{"servers": ["chicago"]},
{"servers": ["tokyo", "chicago"]},
destroyDuplicates=True,
)
# {"servers": ["chicago", "tokyo"]}autoDecodingRLE encodes an array of integers as a Python expression. You can paste the expression into source code, and you don't need a decoder. Its value is the same as array.tolist(), so it doesn't include the dtype.
from hunterMakesPy.dataStructures import autoDecodingRLE
import numpy
autoDecodingRLE(numpy.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 13, 13, 13, 13, 13, 21]))
# "[*range(10)]+[9]*3+[13]*5+[21]"If your code generates Python, use writePython to remove unused imports, sort the other imports, and write the file. importPathFilename2Identifier runs a Python file and returns one object from it. The file doesn't need to be in a package.
from hunterMakesPy.kitFilesystem import importPathFilename2Identifier, writePython
from pathlib import Path
pythonSource = """
import os
import math
def areaCircle(radius):
return math.pi * radius ** 2
"""
pathFilename = writePython(pythonSource, Path("generated/geometry.py")) # Removes `import os`
areaCircle = importPathFilename2Identifier(pathFilename, "areaCircle")
areaCircle(2) # 12.566370614359172writePython and writeStringToHere replace an existing file. appendStringToHere adds text to the end of a file. All three create missing parent directories. To import from a module by its name, use importLogicalPath2Identifier, such as importLogicalPath2Identifier("math", "gcd").
With PackageSettings, you don't need to make paths from __file__. If your package is installed, its name comes from the installed metadata, so a pyproject.toml in the current working directory can't change it. hunterMakesPy uses PackageSettings for its own settings:
from hunterMakesPy import PackageSettings
settingsPackage = PackageSettings(identifierPackageFALLBACK="hunterMakesPy")
settingsPackage.identifierPackage # "hunterMakesPy"
settingsPackage.pathPackage # The directory of the installed package, as a `Path`PackageSettings is a dataclass, so you can add your own settings in a subclass.
In range(1, diceSides + 1), the reader has to work out why the second 1 is there. These names give the reason:
from hunterMakesPy import decreasing, inclusive, zeroIndexed
diceSides = 6
[*range(1, diceSides + inclusive)] # [1, 2, 3, 4, 5, 6]
[*range(3, 0, decreasing)] # [3, 2, 1]
ports = [22, 443, 8080]
ports[len(ports) - zeroIndexed] # 8080decreasing is -1. inclusive, oneIndexed, and zeroIndexed are 1. errorL33T is 31212012, an error value that is easier to notice than -1.
ansiColor has 21 high-contrast pairs of text and background colors. ansiColorReset restores the default colors.
from hunterMakesPy import ansiColor, ansiColorReset
print(f"{ansiColor.GreenOnBlack}Success{ansiColorReset}")pip install hunterMakesPyThe docstrings explain parameters, defaults, and special cases. Read them in your editor or in the source code. To report a problem, open an issue.
By law, authors retain their copyrights unless they grant exceptions. The Creative Commons Attribution-NonCommercial 4.0 International Deed outlines how you may use this work.
The restriction on commercial use (without a license) limits advantage-taking, unjust enrichment, and exploitation. You would be morally wrong if you were to enrich yourself by using this work while I am denied healthcare, housing, security of property, and the safety of my person.
To obtain and retain the right to use this work, you incur the cost of attributing the work to me. Your nominal cost might accrue as a benefit that mitigates my suffering or saves my life.