How to pass a list/array as argument to python fire?

Viewed 6187

I have function like this -

def my_func(my_list_arg=["one", "two"]):

Which I'm trying to call from command line using python-fire.

I have tried several ways -


Attempt 1:

fire_runner.py my_func [one, two]

Results in two separate arguments "[one" and "two]".


Attempt 2:

fire_runner.py my_func ["one", "two"]

which has the same result.


Attempt 3:

fire_runner.py my_func [\"one\", \"two\"]

same result.

5 Answers

Your list will first be parsed by the command line shell. This means you need to force it as a single argument. There are many ways to do this:

  1. No space: [one,two]

  2. Escape the space: [one,\ two]

  3. Quotes: "[one, two]".

Note that you could modify your function to take a list of arguments using the following syntax:

def my_func(*args):

The name args here is convention, but it is just a variable name, so it can be anything. This will allow you to call your function as

fire_runner.py my_func one two

Adding this answer just for a special case.

given that your function is like this:

def my_func(dates: List[str] = []):
    ...

In case you need to send list of dates (or any combination of numbers and characters) from the CLI, the following WON'T work.

fire_runner.py my_func --dates 2021-09-20,
fire_runner.py my_func --dates "[2021-09-20]"
fire_runner.py my_func --dates [2021-09-20]

In all the above cases, dates will be read as one string instead of list of strings. For proper reading of list of strings you can use the following.

fire_runner.py my_func --dates "[\"2021-09-20\"]"
fire_runner.py my_func --dates "[\"2021-09-20\", \"2021-09-76\"]"

Not keeping any space after the comma worked for me.

fire_runner.py my_func [one,two]

Fire converts a comma-separated digit string to tuple as follows:

fire_runner.py my_func  1,2,3

and for a comma-separated string you can use:

fire_runner.py my_func  \'2021-2\',\'20212-3\',\'2023-4\'

Adding a special corner case solution for one element lists, as the above syntaxes did not seem to work (list was parsed as a string starting with [ ):

fire_runner.py my_func "['one']"

Related