Advanced usage#
aliased_argument#
Create an argument that supports shorthand aliases for specific constant values
refer to aliased_argument()
class MyArgs(AbstractParser):
level: str = aliased_argument( # [1]
'--level',
aliases={'--low': 'low', '--high': 'high'}, # [2]
choices=['low', 'medium', 'high'], # [3]
help='Set the difficulty level'
)
def run(self):
print(f"Level selected: {self.level}")
This defines a primary
--leveloption that accepts a value like--level mediumThe
aliasesmap defines shorthand flags like--lowand--high, which are treated as constant presets and internally rewritten as--level=lowand--level=highThe
choicesparameter limits valid values to a predefined set, ensuring that even aliased values are validated properly
run the script with
$ python script.py --low
output
Level selected: low
you can also run
$ python script.py --level medium
output
Level selected: medium
pass options between classes#
When working with structured data or shared configurations, you may want to copy values
into an argument parser class without redefining or parsing them again.
Cloneable provides an __init__ that accepts an AbstractParser,
Cloneable, or dict, then reads and sets all matched arguments or keys.
Keyword arguments can also be used to overwrite individual fields during initialisation.
refer to Cloneable and underlying copy_argument()
from argclz import Cloneable, argument
class Config(Cloneable):
path: str = argument('--path')
debug: bool = argument('--debug')
# Copy from another instance
src = Config(path='/data/file', debug=True)
dst = Config(src)
assert dst.path == '/data/file'
assert dst.debug is True
# Overwrite a field at copy time
dst2 = Config(src, debug=False)
assert dst2.debug is False
If polars is installed, Cloneable also accepts a single-row
pl.DataFrame or a plain dict row, which is useful for iterating a dataframe:
import polars as pl
from argclz import Cloneable, argument
class Config(Cloneable):
type: str = argument('--type')
path: str = argument('--path')
src = pl.DataFrame([{'type': 'file', 'path': '123.txt'}])
dst = Config(src)
assert dst.type == 'file'
assert dst.path == '123.txt'
# Multi-row dataframe
for row in df.iter_rows(named=True):
config = Config(row)
...