icecream
icecream copied to clipboard
how to use formatting options on the output printed by ```ic```?
I would like to apply some formatting outputs to what is printed by ic.
For example, I like to print large int numbers using separators (some other people may want to apply another kind of formatting, for examples, scientific notation formatting or similar, so a general solution would be welcome):
large_int = 123456789
print(f"large_int with separator: {large_int:,}")
prints something like:
large_int with separator: 123,456,789
now if I have an ic
command, I would like to be able to do something like:
from icecream import ic
ic.configureOutput(prefix='', outputFunction=print)
large_int = 123456789
ic(large_int, ":,")
or (reproducing only the last line):
ic(large_int, format=":,")
or something like this.
Is there any simple / easy way to do so? If not, is this something that could be implementable? :)
You can make a custom function which takes any number of argument and then these argument would use the format function to separate the large INT value, then append the modified args list as to print it later on using IC. `from icecream import ic
Define a custom output function to format large integers with separators
def custom_output(*args, **kwargs): new_args = [] for arg in args: if isinstance(arg, int) and abs(arg) > 1000: # Check if arg is a large integer arg = format(arg, ",") # Format large integers with commas new_args.append(arg) ic._print(*new_args, **kwargs)
Set the custom output function
ic.configureOutput(prefix='IC| ', outputFunction=custom_output)
Test the custom output function
ic(123456789) # This will output the formatted large integer with separators ic("Hello", 987654321) # This will also format the large integer with separators ` @jerabaul29 Kindly have a look at the proposed solution and close the issue. Thank you
Thanks for the comment. I see how this works / can work, but honestly this feels like a bit much ceremony to get this done - in this case, it is faster to use print with f-strings. I wonder if there would be a simple way to directly forward simple formatting instructions instead, that would be much lighter to use :) .
pprint.pformat
has the underscore_numbers keyword, which outputs numbers with _ in between, like
123_456_789
This can be used with icecream by creating a custom argToString function:
ic.configureOutput(argToStringFunction=lambda *args: pprint.pformat(*args, underscore_numbers=True))
Note that this will only work for Python >=3.10 !