3 Data Science Tips That You Might Have Missed 3
3 Data Science Tips That You Might Have Missed 3
def time_func(func):
def wrapper(*args, **kwargs):
start_time = time()
func(*args, **kwargs)
end_time = time()
print(
f"""It takes {round(end_time - start_time, 3)} seconds
to execute the function"""
)
return wrapper
@time_func
def test_func1():
sleep(1)
test_func1()
Output:
In the code below, adding @decorator to a function turns it into a decorator. As the
result, the code used to create a decorator is simpler and easier to read.
@decorator
def time_func_with_decorator(func, *args, **kwargs):
start_time = time()
func(*args, **kwargs)
end_time = time()
print(
f"""It takes {round(end_time - start_time, 3)} seconds
to execute the function"""
)
@time_func_with_decorator
def test_func2():
sleep(1)
Output:
For example, in the code below, I use pytest to test my assumption about the output
of the text. When running pytest file_name.py, pytest will run the functions that
start with test_.
text = TextBlob(text)
return text.sentiment.polarity
def test_extract_sentiment_negative():
sentiment = extract_sentiment(text)
Output:
________________________________ test_extract_sentiment_negative
________________________________
def test_extract_sentiment_negative():
sentiment = extract_sentiment(text)
pytest_example.py:17: AssertionError