Lets say you want all names to be capitalized, but you're happy to be flexible on input. Ie Joe, joe, JOE and even jOe should all be understood as Joe Just use attrs converters...
import attr
from clime import clime
@attr.s(auto_attribs=True)
class Dude:
name: str = attr.ib(converter=str.capitalize)
def introduce(self):
print(f"hi! my name is {self.name}")
def main():
clime(Dude).introduce()
if __name__ == "__main__":
main()
$ python main.py joe
hi! my name is Joe
When using an explicit converter, Clime will not try to convert the input into the annotated type. That means you can do whatever you want with as long as it starts with a string. Here, we input a date:
import attr
from clime import clime
import datetime
def year_month_day_to_date(year_month_day) -> datetime.date:
"""
'2000-11-22' ->
:param year_month_day:
:return:
"""
return datetime.datetime.strptime(year_month_day, "%Y-%m-%d").date()
@attr.s
class Dude:
birthday: datetime.date = attr.ib(converter=year_month_day_to_date)
# attributes with explicity converters will be taken with argument parser as strings
# you can do whatver you want with them!
def print_my_birthday(self):
print(f"My birthday is {self.birthday}")
def main():
clime(Dude).print_my_birthday()
if __name__ == "__main__":
main()
Try it!
$ python \docs_src\supercharge_with_attrib\tutorial_003.py 2000-11-22
My birthday is 2000-11-22
But what if the date is invalid?
Lets check...
$ python \docs_src\supercharge_with_attrib\tutorial_003.py 2000-13-22
Traceback (most recent call last):
File "\docs_src\supercharge_with_attrib\tutorial_003.py", line 29, in <module>
main()
File "\docs_src\supercharge_with_attrib\tutorial_003.py", line 25, in main
clime(Dude).print_my_birthday()
File "\clime\clime.py", line 100, in clime
return attrs_decorated_class(**args.__dict__)
File "<attrs generated init __main__.Dude>", line 2, in __init__
File "\docs_src\supercharge_with_attrib\tutorial_003.py", line 14, in year_month_day_to_date
return datetime.datetime.strptime(year_month_day, '%Y-%m-%d').date()
File "C:\Program Files\Python38\lib\_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Program Files\Python38\lib\_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2000-13-22' does not match format '%Y-%m-%d'
In other words, the conversion acts as an implicit validator.
Amazing!