-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support the option to provide a user-defined output formatter #74
Comments
Thanks for raising this issue. Some brainstorming around the possible ways to approach this:
Related note:
|
Objects that implement a custom |
(sorry to comment on an old closed issue, I just didn't want to make issue duplicates) @dbieber I do love that fire uses the Basically, If I want to format a nested dictionary so that the second level wasn't a single line dict and was, for example indented json or yaml (or something completely different, like filter certain keys, idk), I don't want to have to subclass If you're using basic functions with fire, you can just use a wrapper function to do what you need, but you can't easily do that with object methods especially once you start going down multiple levels of attributes (any recursive class wrapper would have to imitate attributes and I think just a really simple function that gets called right before the built-in formatter would be amazing because then you can provide custom formatting without having to inject CLI-specific code into the function or class that you're wrapping because that's really what the beauty of For example def my_formatter(obj): # idk if you could include the parsed cli chain too or something
'''Makes nested dictionaries output as indented json'''
if isinstance(obj, dict):
# returns an object that will be handled by the default formatter
# if you don't want the default formatter to do anything, you'd return a string.
return {
k: json.dumps(v, indent=4) if isinstance(v, dict) else v
for k, v in obj.items()
}
return obj
import fire
fire.Fire(formatter=my_formatter)
# somewhere deep inside fire
def some_fire_result_handler(..., formatter=None):
result = func(*a, **kw)
...
# +++
if formatter:
result = formatter(result)
# +++
print(builtin_formatter(result) And another useful thing would be an exception formatter but idk the best way to handle that |
On trying out fire, one of the first things I wanted was a method to define an output formatter.
At the moment it appears there is a single static formatter defined in
_PrintResult()
.Consider making an option in Fire:
fire.Fire(OBJECT, formatter=myformatter)
The text was updated successfully, but these errors were encountered: