Xonsh and Empty Arguments

I’m using xonsh for three years now, but I still find little conundrums:

I had written a helper script which calls different command line tools with various arguments depending on some conditions. (Perfect use of xonsh!)

In this scenario I used one command, let’s name it find_optimum and I had to call it with a description file problem.txt as argument and sometimes with an option --cache-results:

find_optimum --cache-results problem.txt

At other time the script had to call the command just as

find_optimum --cache-results problem.txt

My approach in the script was something like this:

extra_opt = '--cache-results' if can_cache else ''
find_optimum @(extra_opt) problem.txt

This is nice and concise xonsh syntax, right? True indeed, apart from the fact that it doesn’t work. From the find_optimum command I always got the mysterious error Can’t find file .

It took me a while to understand that in the case can_cahe=True the @-expression @('') is in subprocess mode converted to an empty, but existing argument — and the called command find_optimum obediently gets this empty string as its own separate argument and tries to find a file with the empty string as name instead of the file problem.txt.

The solution becomes clear when you know that the empty list evaluates in the @-expression (@([])) to nothing indeed (and not the empty string). So use as fallback place holder for extra_opt the empty list:

extra_opt = '--cache-results' if can_cache else []
find_optimum @(extra_opt) problem.txt

Now it works like a charm! Aaah, xonsh has it quirks, but at least these quirks are reasonably easy to think through. Love it!