Thursday 22 October 2020

Python Fire hyphen vs underscore

The python package Fire is very useful for launching python scripts from command line. One common thing is to have arguments made of multiple words, for instance name of cat that can be written in 3 commons way :

  • nameofcat
  • name_of_cat
  • name-of-cat

While the first one is compatible with pretty much everything, the second one should be avoided in bash (Should command line options in POSIX-style operating systems be underscore style?) and the third one in python (Why does python disallow usage of hyphens within function and variable names?).

The problem here is that by default fire will take arguments name from the python code, which means that if my python code looks like this:

script.py:

import fire
def main(name_of_cat='Steve'):
    print(f'The name of the cast is {name_of_cat}')
if __name__ == '__main__':
    fire.Fire(main)

then to call it from the command line (or from a bash script), one would do

python script.py --name_of_cat Bob

This is the way I'm using it at the moment, but this feels suboptimal. Any idea on what the best practice is here ?

PS : python script.py --name-of-cat Bob would be impossible since python can't have hyphen in variable names.



from Python Fire hyphen vs underscore

No comments:

Post a Comment