Skip to content

Commit

Permalink
checker.py: Check for invalid print syntax
Browse files Browse the repository at this point in the history
New warning added in messages.py to check for invalid
print syntax

Closes #242
  • Loading branch information
ankitxjoshi committed Aug 11, 2018
1 parent e26f3b9 commit 45fc732
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,13 @@ def handleNodeLoad(self, node):
# iteration
continue

if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)

try:
scope[name].used = (self.scope, node)
except KeyError:
Expand Down
4 changes: 4 additions & 0 deletions pyflakes/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,7 @@ def __init__(self, filename, loc, annotation):

class RaiseNotImplemented(Message):
message = "'raise NotImplemented' should be 'raise NotImplementedError'"


class InvalidPrintSyntax(Message):
message = 'use of >> is invalid with print function'
50 changes: 50 additions & 0 deletions pyflakes/test/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -2034,3 +2034,53 @@ def test_raise_notimplemented(self):
self.flakes('''
raise NotImplemented
''', m.RaiseNotImplemented)


class TestIncompatiblePrintOperator(TestCase):
"""
Tests for warning about invalid use of print function.
"""

def test_valid_print(self):
self.flakes('''
print("Hello")
''')

def test_invalid_print_when_imported_from_future(self):
exc = self.flakes('''
from __future__ import print_function
import sys
print >>sys.stderr, "Hello"
''', m.InvalidPrintSyntax).messages[0]

self.assertEqual(exc.lineno, 4)
self.assertEqual(exc.col, 0)

def test_print_function_assignment(self):
"""
A valid assignment, tested for catching false positives.
"""
self.flakes('''
from __future__ import print_function
log = print
log("Hello")
''')

def test_print_in_lambda(self):
self.flakes('''
from __future__ import print_function
a = lambda: print
''')

def test_print_returned_in_function(self):
self.flakes('''
from __future__ import print_function
def a():
return print
''')

def test_print_as_condition_test(self):
self.flakes('''
from __future__ import print_function
if print: pass
''')

0 comments on commit 45fc732

Please sign in to comment.