passing a custom type to click python

1.2k Views Asked by At

I have these dataclass

@dataclass
class Param:
      param1: float = 5
      param2: int = 20

and another class

class MyClass:
   def __init__(self, param: Param, plot: bool = True):
          self._param = param
          self._plot = plot

   def run(self):
       pass 

I created a file cli.py where I have

import Myclass
import click
@click.command(name="run")
@click.option("--param", required=False)
@click.option("--plot", required=False)
def run(param, plot):
    myclass = Myclass(param, plot)
    myclass.run()

I want to run it from terminal like this: run --param what_to_pass_here? --plot True

Any Help Thank you

1

There are 1 best solutions below

2
Szabolcs On

Well for your purpose the simplest way is to use a tuple parameter which is already supported by Click:

@click.command(name="run")
@click.option("--param", type=(float, int), required=False)
@click.option("--plot", required=False)
def run(param, plot):
    myclass = MyClass(Param(param[0], param[1]), plot)
    myclass.run()

Then you can call your program like this:

run --param 2.5 12 --plot True

And click will automatically parse it and cast it to the desired types, otherwise will return a nice error message.

You can find more on Click's tuple parameter is here: https://click.palletsprojects.com/en/8.0.x/options/#tuples-as-multi-value-options