google / python-fire

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Other
26.98k stars 1.44k forks source link

Get execution context #458

Closed ebrehault closed 1 year ago

ebrehault commented 1 year ago

When we use a library both directly as dependency in some projects and through Fire, it could be interesting to know if the code is currently executed in Fire context or not. Typically, we might want a given method to return JSON when used via Fire or an actual object if not:

class Whatever():
    def result():
        res = self._get_result()
        if is_fire_context:
            return json.dumps(res, ident=2)
        else:
            return res

Is there any existing way to have this is_fire_context check?

dbieber commented 1 year ago

No, there is no existing method for doing this, and I don't recommend it.

Instead, you could define __str__ on whatever value you're returning so that when it is serialized, it prints the way you want. (This only works if the return type is something you control.)

Another alternative is you can call Fire(serialize=your_fn) passing a serialization function for the serialize argument.

If you really want to figure out if you're in a Fire context or not (and again, I don't recommend this), it should be possible e.g. by inspecting the current stack.

ebrehault commented 1 year ago

Defining __str__ is definitely the most pythonic approach, I like it :)

Thanks!