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

How to support custom types and typing? #41

Open
nh13 opened this issue Mar 13, 2018 · 4 comments
Open

How to support custom types and typing? #41

nh13 opened this issue Mar 13, 2018 · 4 comments

Comments

@nh13
Copy link

nh13 commented Mar 13, 2018

I was trying to figure out from the docs how to support custom types (even pathlib's Path) as well as python's type hints. Any pointers would be very appreciated.

For type hints, it looks like the values after the colon (:) are being used by both clize and the typing library. I also want to use the typing library to indicate something is optional to the API, while also have it exposed with clize on the command line. For example:

from clize import run, Parameter
from typing import Optional

def double(*, number: ('n', Optional[int]) = 2):
    '''
    Doubles the number
    
    :param number: the number to double
    '''
    print(2 * number)

if __name__ == '__main__':
    run(double)
@nh13
Copy link
Author

nh13 commented Mar 14, 2018

Looks like a parser.value_converter will work here. It would be great to natively support any type who has a string constructor. Here's another interesting case:

from clize import run, Parameter

def double(*, number: ('n', int, Parameter.REQUIRED) = 2):
    '''
    Doubles the number
    
    :param number: the number to double
    '''
    print(2 * number)

if __name__ == '__main__':
    run(double)

I would like a short flag n, the type to be an integer int, and the parameter to be required Parameter.REQUIRED. I get the following exception:

...
...python3.6/site-packages/clize/parser.py", line 165, in __init__
    super(ParameterWithSourceEquivalent, self).__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'required'

But this works:

from clize import run, Parameter

def double(number: (int, Parameter.REQUIRED) = 2):
    '''
    Doubles the number
    
    :param number: the number to double
    '''
    print(2 * number)

if __name__ == '__main__':
    run(double)
@bersace
Copy link
Contributor

bersace commented Apr 23, 2018

#24 may help

@mauvilsa
Copy link

You may want to try jsonargparse. It has a very extensive support for complex type hints including Optional. See in the docs type hints and basic-usage.

@epsy
Copy link
Owner

epsy commented Oct 13, 2022

There is now rudimentary support for type annotations in Clize 5.0.0, but there is still a long way to go for it to be seamless: https://github.com/epsy/clize/blob/v5.0.0/examples/typed_cli.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants