Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Casting one element to a list #31

Closed
ant5 opened this issue Feb 26, 2018 · 4 comments
Closed

Casting one element to a list #31

ant5 opened this issue Feb 26, 2018 · 4 comments

Comments

@ant5
Copy link

ant5 commented Feb 26, 2018

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
Copy link
Owner

>>> 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
Copy link
Author

ant5 commented Feb 27, 2018

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
Copy link
Owner

Deepwalker commented Feb 27, 2018

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
Copy link
Author

ant5 commented Feb 27, 2018

Probably you are right.

@ant5 ant5 closed this as completed Feb 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants