Skip to content

Instantly share code, notes, and snippets.

@DahlitzFlorian
Created April 23, 2019 19:36
Show Gist options
  • Save DahlitzFlorian/6b5f454a4c2c9a076b7be47df90ca8d9 to your computer and use it in GitHub Desktop.
Save DahlitzFlorian/6b5f454a4c2c9a076b7be47df90ca8d9 to your computer and use it in GitHub Desktop.
Article: How To Create Your Own Timing Context Manager
from time import time
class Timer(object):
def __init__(self, description):
self.description = description
def __enter__(self):
self.start = time()
def __exit__(self, type, value, traceback):
self.end = time()
print(f"{self.description}: {self.end - self.start}")
with Timer("List Comprehension Example"):
s = [x for x in range(10_000_000)]
@denpetrov
Copy link

denpetrov commented Nov 1, 2020

Consider adding blank lines[flake8].

Method definitions inside a class are surrounded by a single blank line. [PEP 8]

@DahlitzFlorian
Copy link
Author

Thanks for your reply. Although I’m aware of these things, I won’t add them as there is a clear purpose in leaving them out: This class is embedded in some publications, which do not have proper mobile versions of their website. Therefore, it’s easier for a reader in a small device to follow if certain blank lines are omitted.

Anyway, you are right that one should stick to these code formatting guidelines in their code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment