Automatic generation of string constants from attribute names with optional handler
Project description
stringconsts
stringconsts is a lightweight Python library for defining immutable string constants in a class. It automatically generates string values for attributes and allows custom handlers and filters for flexible usage.
Installation
pip install stringconsts
The "init_str" value is used to initialize class member constants. Initialization occurs via the metaclass. Only attributes assigned the value "init_str" will be automatically initialized. If the value is already defined, it will not be overridden. init_str is initially set to None - the variable is used for user convenience to make it clear that class members are being auto-generated.
A filter is used to exclude values from auto-processing. The default filter excludes dunder methods (methods beginning with two underscores). default filter:
lambda name, val: not name.startswith("__")
By default, the handler assigns attribute values (for which the class value is assigned equal to init_str) a value equal to the attribute name, with the exception of attributes ending with a single underscore. This exception is made to allow the use of Python keywords such as "class" in a linter-safe manner. default handler:
lambda name: name.rstrip("_") if name.endswith("_") else name
If the user overrides the handler and filter, they control which values are assigned and which are filtered. There's no hidden magic involved. Behavior is fully controlled by user. Therefore, when implementing your own filter, remember to filter dunder methods — they're essential for the proper operation of Python classes.
To use it, simply inherit the "StrConsts" base class. The filter and handler are defined via the __handler__ and __filter__ dunder members, if needed. This class is not intended for instantiation; it should be used as a reference object for string constants.
Usage
from stringconsts import StrConsts, init_str
# Simple example
class Colors(StrConsts):
red = init_str
green = init_str
blue = init_str
class_ = init_str
fixed = "not touched"
c = Colors
print(c.red) # red
print(c.green) # green
print(c.blue) # blue
print(c.class_) # class
print(c.fixed) # not touched
print(c.as_dict()) # {'red': 'red', 'green': 'green', 'blue': 'blue', 'class_': 'class'}
print(c.as_dict().keys()) # dict_keys(['red', 'green', 'blue', 'class_'])
print(c.as_dict().values()) # dict_values(['red', 'green', 'blue', 'class'])
print(c.as_dict().items()) # dict_items([('red', 'red'), ('green', 'green'), ('blue', 'blue'), ('class_', 'class')])
print(c.keys()) # dict_keys(['red', 'green', 'blue', 'class_']) - the same c.as_dict().keys() - the same c.as_dict().keys()
print(c.values()) # dict_values(['red', 'green', 'blue', 'class']) - the same c.as_dict().values() - the same c.as_dict().values()
print(c.items()) # dict_items([('red', 'red'), ('green', 'green'), ('blue', 'blue'), ('class_', 'class')]) - the same c.as_dict().items()
# iteration by keys
for i in c:
print(i, type(i))
# red <class 'str'>
# green <class 'str'>
# blue <class 'str'>
# class_ <class 'str'>
# fixed <class 'str'>
# check value in Str
print("red" in c) # True
print("magenta" in c) # False
# Example explain default handler's
class JSWords(StrConsts):
class_= init_str
display = init_str
style = init_str
__test__ = init_str
print(JSWords.display) # display
print(JSWords.style) # style
print(JSWords.class_) # class - default handler remove last underscore
print(JSWords.__test__) # None (original value preserved, attribute excluded from constants). init_str is None, this key removed by filter.
print(JSWords.as_dict()) # {'class_': 'class', 'display': 'display', 'style': 'style'} - no dunder
for i in JSWords:
print(i)
# class_
# display
# style
# Example explain custom handler and filter
def colonize(name: str) -> str:
return name.rstrip("_") if name.endswith("_") else name.replace("_", ":")
# Default filter excludes dunder attributes automatically.
# User-defined __filter__ can fully control filtering, including dunders.
class Fields(StrConsts):
__handler__ = colonize
__filter__ = lambda name, val: not name.startswith("internal_") and not name.startswith("__") # exclude internal attributes and dunders
some_attr = init_str # automatically generated
other_attr = init_str # automatically generated
class_ = init_str # automatically generated - the standard behavior of removing the last underscore is preserved, since we added this to our custom handler.
internal_attr = init_str # filtered out
fixed_value = "fixed_string" # user-defined fixed value
print(Fields.some_attr) # "some:attr"
print(Fields.other_attr) # "other:attr"
print(Fields.class_) # "class"
print(Fields.fixed_value) # "fixed_string"
print(list(Fields)) # ['some_attr', 'other_attr', 'class_', 'fixed_value']
print(Fields.as_dict()) # {'some_attr': 'some:attr', 'other_attr': 'other:attr', 'class_': 'class', 'fixed_value': 'fixed_string'} ```
Features
- Automatic generation of string constants from attribute names.
- Immutable constants after class creation.
- Custom handler functions to transform attribute names into values.
- Custom filter functions to include or exclude attributes.
- Dictionary-like access:
as_dict(),keys(),values(),items(), iteration, and membership test (in).
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file stringconsts-0.1.0.tar.gz.
File metadata
- Download URL: stringconsts-0.1.0.tar.gz
- Upload date:
- Size: 6.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b858d835f5b86d59fde0f795276a03f9961173e407b8031c0e1012d0f5d93950
|
|
| MD5 |
deb616b6426d136fa2feea3f8272d84c
|
|
| BLAKE2b-256 |
da89c27a73885cfb2c532aad1a4cf62da02ef08ed219493d09d4face2fbc82b1
|
File details
Details for the file stringconsts-0.1.0-py3-none-any.whl.
File metadata
- Download URL: stringconsts-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1e0353cb19536c2494cfaba63bad3bf3b2133ddd21817235387547cf494b8233
|
|
| MD5 |
af57d797a351bc3e03dca989d139c67a
|
|
| BLAKE2b-256 |
b9f81f84ddfaee12de2e1a8f74799cf3396dbd6f97899c111969b696dc7faa58
|