Skip to content
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

Optional import stub #1

Open
ringerc opened this issue Jun 7, 2019 · 2 comments
Open

Optional import stub #1

ringerc opened this issue Jun 7, 2019 · 2 comments

Comments

@ringerc
Copy link

ringerc commented Jun 7, 2019

Hi, thanks for the convenient little library.

I wanted it to be optional so I wrote the following little import stub. Consider adding it to your README for the convenience of others.

Instead of:

from timer_cm import Timer

I stub out the API if the import fails with:

try:
    from timer_cm import Timer
except ImportError as ex:
    # You should pip3 install timer_cm
    # see https://github.com/mherrmann/timer-cm/blob/master/timer_cm.py
    # But we provide a dummy to reduce dependencies
    class Timer:
        def __init__(self, name, print_results=None):
            pass
        def __enter__(self):
            return self
        def __exit__(self, *_):
            pass
        def child(self, name):
            return self
        def print_results(self):
            pass

that way with Timer('foo'): etc all work as expected and just do nothing.

@mherrmann
Copy link
Owner

Thanks! Why do you want it to be optional?

@micahjsmith
Copy link

@ringerc nice idea to share your solution back to this project. I think since this is a common pattern and totally dependent on the user's project, it's not necessary to update the readme.

can also do:

from contextlib import contextmanager
@contextmanager
def Timer(*args, **kwargs):
    yield None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants