realpython / codetiming

A flexible, customizable timer for your Python code

Home Page:https://pypi.org/project/codetiming/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Human Friendly timespan

dchess opened this issue · comments

@gahjelle Would it be possible to to add an enhancement that returns the elapsed time using humanfriendly.format_timespan?

@dchess Thanks for the suggestion. That sounds useful!

However, I'm a bit vary of adding a dependency on humanfriendly. Still, I think we can make this work by allowing text to be a callable that returns a formatted text. Then you should be able to do something like:

from codetiming import Timer
from humanfriendly import format_timespan

def format_text(seconds):
    """Custom formatter with humanfriendly formatting of elapsed time"""
    return f"Elapsed time: {format_timespan(seconds)}"

@Timer(text=format_text)
def some_function():
    ...

This should be fairly flexible and allow for other kinds of formatting as well.

I'll have a go at implementing this!

@gahjelle Thanks for your quick response and this proposed solution. This would definitely meet the need!

@dchess Thanks again for the suggestion. I've just released v1.3.0 which adds support for passing a callable to text as in the example above.

For simple formatting you could also get away with passing in format_timespan directly, or possibly using a lambda function:

@Timer(text=format_timespan)
def some_function():
    ...

@Time(text=lambda seconds: f"Elapsed time: {format_timespan(seconds)}")
def some_other_function():
    ...

Take care!