google/python-fire

Get execution context

ebrehault opened this issue · 2 comments

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?

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.

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

Thanks!