Deepwalker / trafaret

Ultimate transformation library that supports validation, contexts and aiohttp.
http://trafaret.readthedocs.org/en/latest/
BSD 2-Clause "Simplified" License
177 stars 31 forks source link

Casting one element to a list #31

Closed ant5 closed 6 years ago

ant5 commented 6 years ago

Sorry for disturbing again.

I wonder is it possible to convet individually supplied value to a list.

I want to do something like: t = trafaret.List(trafaret.String()) t(['a','b'])

['a','b'] t('a') ['a']

It will be amazingly cosily to pass FieldStorage.getvalue() directly to trafaret.

Deepwalker commented 6 years ago
>>> import trafaret as t
>>> must_be_a_list = lambda trafaret: t.List(trafaret) | trafaret & (lambda x: [x])
>>> must_be_a_list(t.String)('z')
['z']
>>> must_be_a_list(t.String)(['z', 'f'])
['z', 'f']
ant5 commented 6 years ago

Thank you for suggestion. But it seem that in my case the solution does not fit perfectly. I'm reading data specification defined as trafaret from config file and evaluating it to get real trafaret object.

Example config : a = trafaret instance String(min_length=3) b = trafaret instance List(String()) c = trafaret instance Regexp("^\d{15}$")

I get things after words 'trafaret instance' and evaluate it with environment containing 'trafaret' module. Evaluation give me a trafaret object wich I use for data validation.

I still can't understand what to write after words 'trafaret instance' to get a trafaret which convert individual value to List.

Deepwalker commented 6 years ago

Trafaret can not contain all trafarets that you will ever need, so it seems correct way is to create custom one and populate it to your environment to evaluation.

ant5 commented 6 years ago

Probably you are right.