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

Add support for generators #31

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 14 additions & 3 deletions pysnooper/pysnooper.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ def write(s):
return write



def snoop(output=None, variables=(), depth=1, prefix=''):
def snoop(output=None, variables=(), depth=1, prefix='', is_generator=False):
'''
Snoop on the function, writing everything it's doing to stderr.

Expand Down Expand Up @@ -69,8 +68,20 @@ def decorate(function, *args, **kwargs):
with Tracer(target_code_object=target_code_object,
write=write, variables=variables,
depth=depth, prefix=prefix):
return function(*args, **kwargs)
return function(*args, **kwargs)

@decorator.decorator
def generator_decorate(function, *args, **kwargs):
target_code_object = function.__code__
with Tracer(target_code_object=target_code_object,
write=write, variables=variables,
depth=depth, prefix=prefix):
for v in function(*args, **kwargs):
yield v
# yield from function(*args, **kwargs)

if is_generator:
return generator_decorate
return decorate


31 changes: 31 additions & 0 deletions tests/test_pysnooper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Copyright 2019 Ram Rachum.
# This program is distributed under the MIT license.

import inspect
import io
import re
import abc
Expand Down Expand Up @@ -197,3 +198,33 @@ def my_function(foo):
)
)


def test_generator():
string_io = io.StringIO()

@pysnooper.snoop(string_io)
def generator_empty_output():
yield 1

result = generator_empty_output()
assert inspect.isgenerator(result)
assert next(result) == 1
output = string_io.getvalue()
assert_output(output, ())

@pysnooper.snoop(string_io, is_generator=True)
def generator():
yield 1

result = generator()
assert inspect.isgenerator(result)
assert next(result) == 1
output = string_io.getvalue()
assert_output(
output,
(
CallEntry(),
LineEntry('yield 1'),
ReturnEntry('yield 1'),
)
)