PKoHjvvpyflakes/api.py""" API for the command-line I{pyflakes} tool. """ from __future__ import with_statement import sys import os import _ast from pyflakes import checker, __version__ from pyflakes import reporter as modReporter __all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main'] def check(codeString, filename, reporter=None): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: The number of warnings emitted. @rtype: C{int} """ if reporter is None: reporter = modReporter._makeDefaultReporter() # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text if checker.PYPY: if text is None: lines = codeString.splitlines() if len(lines) >= lineno: text = lines[lineno - 1] if sys.version_info >= (3, ) and isinstance(text, bytes): try: text = text.decode('ascii') except UnicodeDecodeError: text = None offset -= 1 # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(filename, 'problem decoding source') else: reporter.syntaxError(filename, msg, lineno, offset, text) return 1 except Exception: reporter.unexpectedError(filename, 'problem decoding source') return 1 # Okay, it's syntactically valid. Now check it. w = checker.Checker(tree, filename) w.messages.sort(key=lambda m: m.lineno) for warning in w.messages: reporter.flake(warning) return len(w.messages) def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: # in Python 2.6, compile() will choke on \r\n line endings. In later # versions of python it's smarter, and we want binary mode to give # compile() the best opportunity to do the right thing WRT text # encodings. if sys.version_info < (2, 7): mode = 'rU' else: mode = 'rb' with open(filename, mode) as f: codestr = f.read() if sys.version_info < (2, 7): codestr += '\n' # Work around for Python <= 2.6 except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter) def iterSourceCode(paths): """ Iterate over all Python source files in C{paths}. @param paths: A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is. """ for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith('.py'): yield os.path.join(dirpath, filename) else: yield path def checkRecursive(paths, reporter): """ Recursively check all source files in C{paths}. @param paths: A list of paths to Python source files and directories containing Python source files. @param reporter: A L{Reporter} where all of the warnings and errors will be reported to. @return: The number of warnings found. """ warnings = 0 for sourcePath in iterSourceCode(paths): warnings += checkPath(sourcePath, reporter) return warnings def _exitOnSignal(sigName, message): """Handles a signal with sys.exit. Some of these signals (SIGPIPE, for example) don't exist or are invalid on Windows. So, ignore errors that might arise. """ import signal try: sigNumber = getattr(signal, sigName) except AttributeError: # the signal constants defined in the signal module are defined by # whether the C library supports them or not. So, SIGPIPE might not # even be defined. return def handler(sig, f): sys.exit(message) try: signal.signal(sigNumber, handler) except ValueError: # It's also possible the signal is defined, but then it's invalid. In # this case, signal.signal raises ValueError. pass def main(prog=None, args=None): """Entry point for the script "pyflakes".""" import optparse # Handle "Keyboard Interrupt" and "Broken pipe" gracefully _exitOnSignal('SIGINT', '... stopped') _exitOnSignal('SIGPIPE', 1) parser = optparse.OptionParser(prog=prog, version=__version__) (__, args) = parser.parse_args(args=args) reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '', reporter) raise SystemExit(warnings > 0) PKhUHo88pyflakes/reporter.pyc 98Vc@sAdZddlZddlZdefdYZdZdS(s Provide the Reporter class. iNtReportercBs2eZdZdZdZdZdZRS(s: Formats the results of pyflakes checks to users. cCs||_||_dS(s Construct a L{Reporter}. @param warningStream: A file-like object where warnings will be written to. The stream's C{write} method must accept unicode. C{sys.stdout} is a good value. @param errorStream: A file-like object where error output will be written to. The stream's C{write} method must accept unicode. C{sys.stderr} is a good value. N(t_stdoutt_stderr(tselft warningStreamt errorStream((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pyt__init__s cCs|jjd||fdS(s An unexpected error occurred trying to process C{filename}. @param filename: The path to a file that we could not process. @ptype filename: C{unicode} @param msg: A message explaining the problem. @ptype msg: C{unicode} s%s: %s N(Rtwrite(Rtfilenametmsg((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pytunexpectedErrors cCs|jd}|d k r]|t|t|}|jjd|||d|fn|jjd|||f|jj||jjd|d k r|jjtjdd|| dnd S( s0 There was a syntax error in C{filename}. @param filename: The path to the file with the syntax error. @ptype filename: C{unicode} @param msg: An explanation of the syntax error. @ptype msg: C{unicode} @param lineno: The line number where the syntax error occurred. @ptype lineno: C{int} @param offset: The column on which the syntax error occurred, or None. @ptype offset: C{int} @param text: The source code containing the syntax error. @ptype text: C{unicode} is %s:%d:%d: %s is %s:%d: %s s s\St s^ N(t splitlinestNonetlenRRtretsub(RRR tlinenotoffsetttexttline((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pyt syntaxError's   cCs*|jjt||jjddS(sp pyflakes found something wrong with the code. @param: A L{pyflakes.messages.Message}. s N(RRtstr(Rtmessage((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pytflakeCs(t__name__t __module__t__doc__RR RR(((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pyR s   cCsttjtjS(sI Make a reporter that can be used when no reporter is specified. (Rtsyststdouttstderr(((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pyt_makeDefaultReporterMs(RRRtobjectRR(((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/reporter.pyts  DPKpaHM;pyflakes/messages.py""" Provide the class Message and its subclasses. """ class Message(object): message = '' message_args = () def __init__(self, filename, loc): self.filename = filename self.lineno = loc.lineno self.col = getattr(loc, 'col_offset', 0) def __str__(self): return '%s:%s: %s' % (self.filename, self.lineno, self.message % self.message_args) class UnusedImport(Message): message = '%r imported but unused' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,) class RedefinedWhileUnused(Message): message = 'redefinition of unused %r from line %r' def __init__(self, filename, loc, name, orig_loc): Message.__init__(self, filename, loc) self.message_args = (name, orig_loc.lineno) class RedefinedInListComp(Message): message = 'list comprehension redefines %r from line %r' def __init__(self, filename, loc, name, orig_loc): Message.__init__(self, filename, loc) self.message_args = (name, orig_loc.lineno) class ImportShadowedByLoopVar(Message): message = 'import %r from line %r shadowed by loop variable' def __init__(self, filename, loc, name, orig_loc): Message.__init__(self, filename, loc) self.message_args = (name, orig_loc.lineno) class ImportStarNotPermitted(Message): message = "'from %s import *' only allowed at module level" def __init__(self, filename, loc, modname): Message.__init__(self, filename, loc) self.message_args = (modname,) class ImportStarUsed(Message): message = "'from %s import *' used; unable to detect undefined names" def __init__(self, filename, loc, modname): Message.__init__(self, filename, loc) self.message_args = (modname,) class ImportStarUsage(Message): message = "%s may be undefined, or defined from star imports: %s" def __init__(self, filename, loc, name, from_list): Message.__init__(self, filename, loc) self.message_args = (name, from_list) class UndefinedName(Message): message = 'undefined name %r' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,) class DoctestSyntaxError(Message): message = 'syntax error in doctest' def __init__(self, filename, loc, position=None): Message.__init__(self, filename, loc) if position: (self.lineno, self.col) = position self.message_args = () class UndefinedExport(Message): message = 'undefined name %r in __all__' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,) class UndefinedLocal(Message): message = ('local variable %r (defined in enclosing scope on line %r) ' 'referenced before assignment') def __init__(self, filename, loc, name, orig_loc): Message.__init__(self, filename, loc) self.message_args = (name, orig_loc.lineno) class DuplicateArgument(Message): message = 'duplicate argument %r in function definition' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,) class LateFutureImport(Message): message = 'from __future__ imports must occur at the beginning of the file' def __init__(self, filename, loc, names): Message.__init__(self, filename, loc) self.message_args = () class FutureFeatureNotDefined(Message): """An undefined __future__ feature name was imported.""" message = 'future feature %s is not defined' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,) class UnusedVariable(Message): """ Indicates that a variable has been explicitly assigned to but not actually used. """ message = 'local variable %r is assigned to but never used' def __init__(self, filename, loc, names): Message.__init__(self, filename, loc) self.message_args = (names,) class ReturnWithArgsInsideGenerator(Message): """ Indicates a return statement with arguments inside a generator. """ message = '\'return\' with argument inside generator' class ReturnOutsideFunction(Message): """ Indicates a return statement outside of a function/method. """ message = '\'return\' outside function' class YieldOutsideFunction(Message): """ Indicates a yield or yield from statement outside of a function/method. """ message = '\'yield\' outside function' # For whatever reason, Python gives different error messages for these two. We # match the Python error message exactly. class ContinueOutsideLoop(Message): """ Indicates a continue statement outside of a while or for loop. """ message = '\'continue\' not properly in loop' class BreakOutsideLoop(Message): """ Indicates a break statement outside of a while or for loop. """ message = '\'break\' outside loop' class ContinueInFinally(Message): """ Indicates a continue statement in a finally block in a while or for loop. """ message = '\'continue\' not supported inside \'finally\' clause' class DefaultExceptNotLast(Message): """ Indicates an except: block as not the last exception handler. """ message = 'default \'except:\' must be last' class TwoStarredExpressions(Message): """ Two or more starred expressions in an assignment (a, *b, *c = d). """ message = 'two starred expressions in assignment' class TooManyExpressionsInStarredAssignment(Message): """ Too many expressions in an assignment with star-unpacking """ message = 'too many expressions in star-unpacking assignment' class AssertTuple(Message): """ Assertion test is a tuple, which are always True. """ message = 'assertion is always true, perhaps remove parentheses?' PKHPwpLNNpyflakes/checker.py""" Main module. Implement the central Checker class. Also, it models the Bindings and Scopes. """ import __future__ import doctest import os import sys PY2 = sys.version_info < (3, 0) PY32 = sys.version_info < (3, 3) # Python 2.5 to 3.2 PY33 = sys.version_info < (3, 4) # Python 2.5 to 3.3 try: sys.pypy_version_info PYPY = True except AttributeError: PYPY = False builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins')) try: import ast except ImportError: # Python 2.5 import _ast as ast if 'decorator_list' not in ast.ClassDef._fields: # Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from pyflakes import messages if PY2: def getNodeType(node_class): # workaround str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper() # Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally) if PY32: def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept): return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] else: def getAlternatives(n): if isinstance(n, ast.If): return [n.body] if isinstance(n, ast.Try): return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] class _FieldsOrder(dict): """Fix order of AST node fields.""" def _get_fields(self, node_class): # handle iter before target, and generators before element fields = node_class._fields if 'iter' in fields: key_first = 'iter'.find elif 'generators' in fields: key_first = 'generators'.find else: key_first = 'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class] = fields = self._get_fields(node_class) return fields def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name in _fields_order[node.__class__]: if name == omit: continue field = getattr(node, name, None) if isinstance(field, ast.AST): yield field elif isinstance(field, list): for item in field: yield item class Binding(object): """ Represents the binding of a value to a name. The checker uses this to keep track of which names have been bound and which names have not. See L{Assignment} for a special type of binding that is checked with stricter rules. @ivar used: pair of (L{Scope}, node) indicating the scope and the node that this binding was last used. """ def __init__(self, name, source): self.name = name self.source = source self.used = False def __str__(self): return self.name def __repr__(self): return '<%s object %r from line %r at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self, other): return isinstance(other, Definition) and self.name == other.name class Definition(Binding): """ A binding that defines a function or a class. """ class Importation(Definition): """ A binding created by an import statement. @ivar fullName: The complete name given to the import statement, possibly including multiple dotted components. @type fullName: C{str} """ def __init__(self, name, source, full_name=None): self.fullName = full_name or name self.redefined = [] super(Importation, self).__init__(name, source) def redefines(self, other): if isinstance(other, SubmoduleImportation): # See note in SubmoduleImportation about RedefinedWhileUnused return self.fullName == other.fullName return isinstance(other, Definition) and self.name == other.name def _has_alias(self): """Return whether importation needs an as clause.""" return not self.fullName.split('.')[-1] == self.name @property def source_statement(self): """Generate a source statement equivalent to the import.""" if self._has_alias(): return 'import %s as %s' % (self.fullName, self.name) else: return 'import %s' % self.fullName def __str__(self): """Return import full name with alias.""" if self._has_alias(): return self.fullName + ' as ' + self.name else: return self.fullName class SubmoduleImportation(Importation): """ A binding created by a submodule import statement. A submodule import is a special case where the root module is implicitly imported, without an 'as' clause, and the submodule is also imported. Python does not restrict which attributes of the root module may be used. This class is only used when the submodule import is without an 'as' clause. pyflakes handles this case by registering the root module name in the scope, allowing any attribute of the root module to be accessed. RedefinedWhileUnused is suppressed in `redefines` unless the submodule name is also the same, to avoid false positives. """ def __init__(self, name, source): # A dot should only appear in the name when it is a submodule import assert '.' in name and (not source or isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name def redefines(self, other): if isinstance(other, Importation): return self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName @property def source_statement(self): return 'import ' + self.fullName class ImportationFrom(Importation): def __init__(self, name, source, module, real_name=None): self.module = module self.real_name = real_name or name full_name = module + '.' + self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self): """Return import full name with alias.""" if self.real_name != self.name: return self.fullName + ' as ' + self.name else: return self.fullName @property def source_statement(self): if self.real_name != self.name: return 'from %s import %s as %s' % (self.module, self.real_name, self.name) else: return 'from %s import %s' % (self.module, self.name) class StarImportation(Importation): """A binding created by an 'from x import *' statement.""" def __init__(self, name, source): super(StarImportation, self).__init__('*', source) # Each star importation needs a unique name, and # may not be the module name otherwise it will be deemed imported self.name = name + '.*' self.fullName = name @property def source_statement(self): return 'from ' + self.fullName + ' import *' def __str__(self): return self.name class FutureImportation(ImportationFrom): """ A binding created by a from `__future__` import statement. `__future__` imports are implicitly used. """ def __init__(self, name, source, scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used = (scope, source) class Argument(Binding): """ Represents binding a name as an argument. """ class Assignment(Binding): """ Represents binding a name with an explicit assignment. The checker will raise warnings for any Assignment that isn't used. Also, the checker does not consider assignments in tuple/list unpacking to be Assignments, rather it treats them as simple Bindings. """ class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class ExportBinding(Binding): """ A binding created by an C{__all__} assignment. If the names in the list can be determined statically, they will be treated as names for export and additional checking applied to them. The only C{__all__} assignment that can be recognized is one which takes the value of a literal list containing literal strings. For example:: __all__ = ["foo", "bar"] Names which are imported and not otherwise used but appear in the value of C{__all__} will not have an unused import warning reported for them. """ def __init__(self, name, source, scope): if '__all__' in scope and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names = [] if isinstance(source.value, (ast.List, ast.Tuple)): for node in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred = False # set to True when import * is found def __repr__(self): scope_cls = self.__class__.__name__ return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope): """ I represent a name scope for a function. @ivar globals: Names declared 'global' in this function. """ usesLocals = False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() # Simplify: manage the special locals as globals self.globals = self.alwaysUsed.copy() self.returnValue = None # First non-empty return self.isGenerator = False # Detect a generator def unusedAssignments(self): """ Return a generator for the assignments which have not been used. """ for name, binding in self.items(): if (not binding.used and name not in self.globals and not self.usesLocals and isinstance(binding, Assignment)): yield name, binding class GeneratorScope(Scope): pass class ModuleScope(Scope): """Scope for a module.""" _futures_allowed = True class DoctestScope(ModuleScope): """Scope for a doctest.""" # Globally defined names which are not attributes of the builtins module, or # are only present on some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): # Returns node.id, or node.name, or None if hasattr(node, 'id'): # One of the many nodes with an id return node.id if hasattr(node, 'name'): # an ExceptHandler node return node.name class Checker(object): """ I check the cleanliness and sanity of Python code. @ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements of the list are two-tuples. The first element is the callable passed to L{deferFunction}. The second element is a copy of the scope stack at the time L{deferFunction} was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for callables which are deferred assignment checks. """ nodeDepth = 0 offset = None traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {} self._deferredFunctions = [] self._deferredAssignments = [] self.deadScopes = [] self.messages = [] self.filename = filename if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers = [()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None so that deferFunction will fail # noisily if called after we've run through the deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None so that deferAssignment will fail # noisily if called after we've run through the deferred assignments. self._deferredAssignments = None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable): """ Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When `callable` is called, the scope at the time this is called will be restored, however it will contain any new bindings added to it. """ self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable): """ Schedule an assignment handler to be called just after deferred function handlers. """ self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred): """ Run the callables in C{deferred} using their associated scope stack. """ for handler, scope, offset in deferred: self.scopeStack = scope self.offset = offset handler() def _in_doctest(self): return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for scope in self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert value is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property def scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): """ Look at scopes which have been fully examined and report names in them which were imported but unused. """ for scope in self.deadScopes: # imports in classes are public members if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if all_binding and not isinstance(all_binding, ExportBinding): all_binding = None if all_binding: all_names = set(all_binding.names) undefined = all_names.difference(scope) else: all_names = undefined = [] if undefined: if not scope.importStarred and \ os.path.basename(self.filename) != '__init__.py': # Look for possible mistakes in the export list for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all import '*' as used by the undefined in __all__ if scope.importStarred: for binding in scope.values(): if isinstance(binding, StarImportation): binding.used = all_binding # Look for imported names that aren't used. for value in scope.values(): if isinstance(value, Importation): used = value.used or value.name in all_names if not used: messg = messages.UnusedImport self.report(messg, value.source, str(value)) for node in value.redefined: if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif used: continue else: messg = messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node): # Lookup the first parent which is not Tuple, List or Starred while True: node = node.parent if not hasattr(node, 'elts') and not hasattr(node, 'ctx'): return node def getCommonAncestor(self, lnode, rnode, stop): if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return None if lnode is rnode: return lnode if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node, ancestors, stop): for a in ancestors: if self.getCommonAncestor(node, a, stop): return True return False def differentForks(self, lnode, rnode): """True, if lnode and rnode are located on different forks of IF/TRY""" ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if parts: for items in parts: if self.descendantOf(lnode, items, ancestor) ^ \ self.descendantOf(rnode, items, ancestor): return True return False def addBinding(self, node, value): """ Called when a binding is altered. - `node` is the statement responsible for the change - `value` is the new value, a Binding instance """ # assert value.source in (node, node.parent): for scope in self.scopeStack[::-1]: if value.name in scope: break existing = scope.get(value.name) if existing and not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope is self.scope: if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if value.name in self.scope: # then assume the rebound name is used as a global or within a loop value.used = self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self, nodeType) return handler def handleNodeLoad(self, node): name = getNodeName(node) if not name: return in_generators = None importStarred = None # try enclosing function scopes and global scope for scope in self.scopeStack[-1::-1]: # only generators used in a class scope can access the names # of the class. this is skipped during the first iteration if in_generators is False and isinstance(scope, ClassScope): continue try: scope[name].used = (self.scope, node) except KeyError: pass else: return importStarred = importStarred or scope.importStarred if in_generators is not False: in_generators = isinstance(scope, GeneratorScope) # look in the built-ins if name in self.builtIns: return if importStarred: from_list = [] for scope in self.scopeStack[-1::-1]: for binding in scope.values(): if isinstance(binding, StarImportation): # mark '*' imports as used for each scope binding.used = (self.scope, node) from_list.append(binding.fullName) # report * usage, with a list of possible sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return if name == '__path__' and os.path.basename(self.filename) == '__init__.py': # the special name __path__ is valid only in packages return # protected with a NameError handler? if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node): name = getNodeName(node) if not name: return # if the name hasn't already been defined in the current scope if isinstance(self.scope, FunctionScope) and name not in self.scope: # for each function or module scope above us for scope in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)): continue # if the name was defined in that scope, and the name has # been accessed already in the current scope, and hasn't # been declared global used = name in scope and scope[name].used if used and used[0] is self.scope and name not in self.scope.globals: # then it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif name == '__all__' and isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent, self.scope) else: binding = Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self, node): def on_conditional_branch(): """ Return `True` if node is part of a conditional body. """ current = getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None) return False name = getNodeName(node) if not name: return if on_conditional_branch(): # We can not predict if this conditional branch is going to # be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self, tree, omit=None): for node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for child in node.targets + [node.value]: if not hasattr(child, 'elts'): return False return True def isDocstring(self, node): """ Determine if the given node is a docstring, as long as it is at the correct place in the node tree. """ return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self, node): if isinstance(node, ast.Expr): node = node.value if not isinstance(node, ast.Str): return (None, None) if PYPY: doctest_lineno = node.lineno - 1 else: # Computed incorrectly if the docstring has backslash doctest_lineno = node.lineno - node.s.count('\n') - 1 return (node.s, doctest_lineno) def handleNode(self, node, parent): if node is None: return if self.offset and getattr(node, 'lineno', None) is not None: node.lineno += self.offset[0] node.col_offset += self.offset[1] if self.traceTree: print(' ' * self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth += 1 node.depth = self.nodeDepth node.parent = parent try: handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1 if self.traceTree: print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node): try: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g. line 6 of the docstring for has inconsistent # leading whitespace: ... return if not examples: return # Place doctest in module scope saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset = self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for example in examples: try: tree = compile(example.source, "", "exec", ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1] if PYPY: e.offset += 1 position = (node_lineno + example.lineno + e.lineno, example.indent + 4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset = (node_offset[0] + node_lineno + example.lineno, node_offset[1] + example.indent + 4) self.handleChildren(tree) self.offset = node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def ignore(self, node): pass # "stmt" type nodes DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \ ASYNCWITH = ASYNCWITHITEM = RAISE = TRYFINALLY = EXEC = \ EXPR = ASSIGN = handleChildren PASS = ignore # "expr" type nodes BOOLOP = BINOP = UNARYOP = IFEXP = DICT = SET = \ COMPARE = CALL = REPR = ATTRIBUTE = SUBSCRIPT = \ STARRED = NAMECONSTANT = handleChildren NUM = STR = BYTES = ELLIPSIS = ignore # "slice" type nodes SLICE = EXTSLICE = INDEX = handleChildren # expression contexts are node instances too, though being constants LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore # same for operators AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \ BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \ EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \ MATMULT = ignore # additional node types COMPREHENSION = KEYWORD = FORMATTEDVALUE = handleChildren def ASSERT(self, node): if isinstance(node.test, ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node): """ Keep track of globals declarations. """ global_scope_index = 1 if self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index] # Ignore 'global' statement in global scope. if self.scope is not global_scope: # One 'global' statement can bind multiple (comma-delimited) names. for node_name in node.names: node_value = Assignment(node_name, node) # Remove UndefinedName messages already reported for this name. # TODO: if the global is not used in this scope, it does not # become a globally defined name. See test_unused_global. self.messages = [ m for m in self.messages if not isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name] # Bind name to global scope if it doesn't exist already. global_scope.setdefault(node_name, node_value) # Bind name to non-global scopes, but as already "used". node_value.used = (global_scope, node) for scope in self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value NONLOCAL = GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if PY2 else GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP def NAME(self, node): """ Handle occurrence of Name (which can be a load/store/delete access.) """ # Locate the name in locals / function / globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): # we are doing locals() call in current scope self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must be a Param context -- this only happens for names in function # arguments, but these aren't dispatched through here raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) def CONTINUE(self, node): # Walk the tree up until we see a loop (OK), a function or class # definition (not OK), for 'continue', a finally block (not OK), or # the top module scope (not OK) n = node while hasattr(n, 'parent'): n, n_child = n.parent, n if isinstance(n, (ast.While, ast.For)): # Doesn't apply unless it's in the loop itself if n_child not in n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally difference in Python < and >= 3.3 if hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if ( node.value and hasattr(self.scope, 'returnValue') and not self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value, node) def YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT = YIELDFROM = YIELD def FUNCTIONDEF(self, node): for deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does not process doctest within a doctest, # or in nested functions. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node): args = [] annotations = [] if PY2: def addArgs(arglist): for arg in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else: for arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults # Only for Python3 FunctionDefs is_py3_func = hasattr(node, 'returns') for arg_name in ('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name) if not wildcard: continue args.append(wildcard if PY33 else wildcard.arg) if is_py3_func: if PY33: # Python 2.5 to 3.3 argannotation = arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args): for (idx, arg) in enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child in annotations + defaults: if child: self.handleNode(child, node) def runFunction(): self.pushScope() for name in args: self.addBinding(node, Argument(name, node)) if isinstance(node.body, list): # case for FunctionDefs for stmt in node.body: self.handleNode(stmt, node) else: # case for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): """ Check to see if any assignments have not been used. """ for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): """ Check to see if there is any return statement with arguments but the function is a generator. """ if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): """ Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope. """ for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within a doctest # classes within classes are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self, node): if not PY2 and isinstance(node.ctx, ast.Store): # Python 3 advanced tuple unpacking: a, *b, c = d. # Only one starred expression is allowed, and no more than 1<<8 # assignments are allowed before a stared expression. There is # also a limit of 1<<24 expressions after the starred expression, # which is impossible to test due to memory restrictions, but we # add it here anyway has_starred = False star_loc = -1 for i, n in enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't distinguish two from more # than two. break has_starred = True star_loc = i if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE def IMPORT(self, node): for alias in node.names: if '.' in alias.name and not alias.asname: importation = SubmoduleImportation(alias.name, node) else: name = alias.asname or alias.name importation = Importation(name, node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node): if node.module == '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n in node.names]) else: self.futuresAllowed = False for alias in node.names: name = alias.asname or alias.name if node.module == '__future__': importation = FutureImportation(name, node, self.scope) if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name == '*': # Only Python 2, local import * is a SyntaxWarning if not PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, node.module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node, node.module) importation = StarImportation(node.module, node) else: importation = ImportationFrom(name, node, node.module, alias.name) self.addBinding(node, importation) def TRY(self, node): handler_names = [] # List the exception handlers for i, handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None and i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the except handlers and process the body self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process the other nodes: "except:", "else:", "finally:" self.handleChildren(node, omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self, node): if PY2 or node.name is None: self.handleChildren(node) return # 3.x: the name of the exception, which is not a Name node, but # a simple string, creates a local that is only bound within the scope # of the except: block. for scope in self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined = True break else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: # See discussion on https://github.com/pyflakes/pyflakes/pull/59. # We're removing the local name since it's being unbound # after leaving the except: block and it's always unbound # if the except: block is never entered. This will cause an # "undefined name" error raised if the checked code tries to # use the name afterwards. # # Unless it's been removed already. Then do nothing. try: del self.scope[node.name] except KeyError: pass PKhUHfpyflakes/__init__.pyc $+Wc@s dZdS(s1.2.1N(t __version__(((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/__init__.pytsPKq7EjHi~~pyflakes/__main__.pyfrom pyflakes.api import main # python -m pyflakes (with Python >= 2.7) if __name__ == '__main__': main(prog='pyflakes') PKhUH<pyflakes/checker.pyc *+Wc@s>dZddlZddlZddlZddlZejd<kZejd=kZejd>kZyej e Z Wne k re Z nXeeerdndZyddlZWnSek rddlZdejjkrd?ej_ed ej_qnXdd lmZer4d Zn d ZerOd Zn dZdefdYZdedZ de!fdYZ"de"fdYZ#de#fdYZ$de$fdYZ%de$fdYZ&de$fdYZ'de&fdYZ(d e"fd!YZ)d"e"fd#YZ*d$e#fd%YZ+d&e#fd'YZ,d(e"fd)YZ-d*efd+YZ.d,e.fd-YZ/d.e.fd/YZ0d0e.fd1YZ1d2e.fd3YZ2d4e2fd5YZ3d6d7d8gZ4d9Z5d:e!fd;YZ6dS(@s] Main module. Implement the central Checker class. Also, it models the Bindings and Scopes. iNiiit __builtin__tbuiltinstdecorator_listcCs|jS(N(t decorators(ts((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyts(tmessagescCstt|jjS(N(tstrtunicodet__name__tupper(t node_class((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt getNodeType%scCs |jjS(N(R R (R ((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR )scCsit|tjtjfr%|jgSt|tjre|j|jgg|jD]}|g^qQSdS(N(t isinstancetasttIft TryFinallytbodyt TryExcepttorelsethandlers(tnthdl((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytgetAlternatives.s cCs`t|tjr|jgSt|tjr\|j|jgg|jD]}|g^qHSdS(N(R RRRtTryRR(RR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR4s t _FieldsOrdercBs eZdZdZdZRS(sFix order of AST node fields.cCs^|j}d|kr!dj}n!d|kr9dj}n dj}tt|d|dtS(Ntitert generatorstvaluetkeytreverse(t_fieldstfindttupletsortedtTrue(tselfR tfieldst key_first((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt _get_fields>s      cCs|j|||<}|S(N(R'(R$R R%((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt __missing__Is(R t __module__t__doc__R'R((((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s ccsx{||jD]l}||kr&qnt||d}t|tjrR|Vqt|trx|D] }|VqhWqqWdS(s Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. N(t __class__tgetattrtNoneR RtASTtlist(tnodetomitt _fields_ordertnametfieldtitem((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytiter_child_nodesNs  tBindingcBs2eZdZdZdZdZdZRS(sr Represents the binding of a value to a name. The checker uses this to keep track of which names have been bound and which names have not. See L{Assignment} for a special type of binding that is checked with stricter rules. @ivar used: pair of (L{Scope}, node) indicating the scope and the node that this binding was last used. cCs||_||_t|_dS(N(R3tsourcetFalsetused(R$R3R8((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt__init__js  cCs|jS(N(R3(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt__str__oscCs)d|jj|j|jjt|fS(Ns#<%s object %r from line %r at 0x%x>(R+R R3R8tlinenotid(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt__repr__rs  cCst|to|j|jkS(N(R t DefinitionR3(R$tother((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt redefinesxs(R R)R*R;R<R?RB(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR7^s     R@cBseZdZRS(s7 A binding that defines a function or a class. (R R)R*(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR@|st ImportationcBsDeZdZddZdZdZedZdZ RS(s A binding created by an import statement. @ivar fullName: The complete name given to the import statement, possibly including multiple dotted components. @type fullName: C{str} cCs5|p ||_g|_tt|j||dS(N(tfullNamet redefinedtsuperRCR;(R$R3R8t full_name((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s cCs>t|tr|j|jkSt|to=|j|jkS(N(R tSubmoduleImportationRDR@R3(R$RA((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRBscCs|jjdd|jk S(s.Return whether importation needs an as clause.t.i(RDtsplitR3(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt _has_aliasscCs/|jr d|j|jfSd|jSdS(s5Generate a source statement equivalent to the import.simport %s as %ss import %sN(RKRDR3(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytsource_statements cCs)|jr|jd|jS|jSdS(s#Return import full name with alias.s as N(RKRDR3(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR<s N( R R)R*R-R;RBRKtpropertyRLR<(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRCs    RHcBs8eZdZdZdZdZedZRS(s A binding created by a submodule import statement. A submodule import is a special case where the root module is implicitly imported, without an 'as' clause, and the submodule is also imported. Python does not restrict which attributes of the root module may be used. This class is only used when the submodule import is without an 'as' clause. pyflakes handles this case by registering the root module name in the scope, allowing any attribute of the root module to be accessed. RedefinedWhileUnused is suppressed in `redefines` unless the submodule name is also the same, to avoid false positives. cCsdd|kr%| s+t|tjs+t|jdd}tt|j||||_dS(NRIi( R RtImporttAssertionErrorRJRFRHR;RD(R$R3R8t package_name((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s+cCs5t|tr|j|jkStt|j|S(N(R RCRDRFRHRB(R$RA((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRBscCs|jS(N(RD(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR<scCs d|jS(Nsimport (RD(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRLs(R R)R*R;RBR<RMRL(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRHs    tImportationFromcBs,eZddZdZedZRS(cCsI||_|p||_|d|j}tt|j|||dS(NRI(tmodulet real_nameRFRQR;(R$R3R8RRRSRG((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s cCs/|j|jkr$|jd|jS|jSdS(s#Return import full name with alias.s as N(RSR3RD(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR<scCsD|j|jkr,d|j|j|jfSd|j|jfSdS(Nsfrom %s import %s as %ssfrom %s import %s(RSR3RR(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRLs   N(R R)R-R;R<RMRL(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRQs  tStarImportationcBs/eZdZdZedZdZRS(s4A binding created by an 'from x import *' statement.cCs3tt|jd||d|_||_dS(Nt*s.*(RFRTR;R3RD(R$R3R8((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s cCsd|jdS(Nsfrom s import *(RD(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRLscCs|jS(N(R3(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR<s(R R)R*R;RMRLR<(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRTs tFutureImportationcBseZdZdZRS(ss A binding created by a from `__future__` import statement. `__future__` imports are implicitly used. cCs/tt|j||d||f|_dS(Nt __future__(RFRVR;R:(R$R3R8tscope((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s(R R)R*R;(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRVstArgumentcBseZdZRS(s3 Represents binding a name as an argument. (R R)R*(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRYst AssignmentcBseZdZRS(s Represents binding a name with an explicit assignment. The checker will raise warnings for any Assignment that isn't used. Also, the checker does not consider assignments in tuple/list unpacking to be Assignments, rather it treats them as simple Bindings. (R R)R*(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRZ stFunctionDefinitioncBseZRS((R R)(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR[stClassDefinitioncBseZRS((R R)(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR\st ExportBindingcBseZdZdZRS(s A binding created by an C{__all__} assignment. If the names in the list can be determined statically, they will be treated as names for export and additional checking applied to them. The only C{__all__} assignment that can be recognized is one which takes the value of a literal list containing literal strings. For example:: __all__ = ["foo", "bar"] Names which are imported and not otherwise used but appear in the value of C{__all__} will not have an unused import warning reported for them. cCsd|kr7t|tjr7t|dj|_n g|_t|jtjtjfrx?|jjD].}t|tj rk|jj |j qkqkWnt t |j||dS(Nt__all__(R Rt AugAssignR/tnamesRtListtTupleteltstStrtappendRRFR]R;(R$R3R8RXR0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;-s (R R)R*R;(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR]s tScopecBseZeZdZRS(cCs,|jj}d|t|tj|fS(Ns<%s at 0x%x %s>(R+R R>tdictR?(R$t scope_cls((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR?<s (R R)R9t importStarredR?(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRf9st ClassScopecBseZRS((R R)(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRjAst FunctionScopecBs;eZdZeZedddgZdZdZRS(sp I represent a name scope for a function. @ivar globals: Names declared 'global' in this function. t__tracebackhide__t__traceback_info__t__traceback_supplement__cCs;tt|j|jj|_d|_t|_ dS(N( RFRkR;t alwaysUsedtcopytglobalsR-t returnValueR9t isGenerator(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;Os ccsaxZ|jD]L\}}|j r ||jkr |j r t|tr ||fVq q WdS(sR Return a generator for the assignments which have not been used. N(titemsR:Rqt usesLocalsR RZ(R$R3tbinding((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytunusedAssignmentsVs  ( R R)R*R9RutsetRoR;Rw(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRkEs  tGeneratorScopecBseZRS((R R)(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRyast ModuleScopecBseZdZeZRS(sScope for a module.(R R)R*R#t_futures_allowed(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRzest DoctestScopecBseZdZRS(sScope for a doctest.(R R)R*(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR|jst__file__t __builtins__t WindowsErrorcCs0t|dr|jSt|dr,|jSdS(NR>R3(thasattrR>R3(R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt getNodeNamesstCheckercBseZdZdZd2ZeZee j e Z e jjdZerde jejdn[dd2de jkdZdZdZd Zd Zed Zejd Zed ZdZdZedZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)d2dZ*dZ+dZ,dZ-dZ.e/j0j1Z2d Z3d!Z4e*Z5Z6Z7Z8Z9Z:Z;Z<Z=Z>Z?Z@ZAZBZCe4ZDe*ZEZFZGZHZIZJZKZLZMZNZOZPZQe4ZRZSZTZUe*ZVZWZXe4ZYZZZ[Z\Z]Z^e4Z_Z`ZaZbZcZdZeZfZgZhZiZjZkZlZmZnZoZpZqZrZsZtZuZvZwZxZyZzZ{e*Z|Z}Z~d"Zd#ZeZd$Zere*neZeZZd%Zd&ZeZd'Zd(ZeZZd)ZeZd*Zd+Zd,Zd-ZeZd.Zd/Zd0ZeZd1ZRS(3s I check the cleanliness and sanity of Python code. @ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements of the list are two-tuples. The first element is the callable passed to L{deferFunction}. The second element is a copy of the scope stack at the time L{deferFunction} was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for callables which are deferred assignment checks. itPYFLAKES_BUILTINSt,s(none)tPYFLAKES_DOCTESTcCsi|_g|_g|_g|_g|_||_|rT|jj||_n||_t g|_ dg|_ ||_ |j ||j|jd|_|j|jd|_|j d3|j|jdS(Ni((t _nodeHandlerst_deferredFunctionst_deferredAssignmentst deadScopesRtfilenametbuiltInstuniont withDoctestRzt scopeStacktexceptHandlerstrootthandleChildrent runDeferredR-tpopScopetcheckDeadScopes(R$ttreeRRR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR;s(              cCs$|jj||j|jfdS(s{ Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When `callable` is called, the scope at the time this is called will be restored, however it will contain any new bindings added to it. N(RReRtoffset(R$tcallable((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt deferFunctions cCs$|jj||j|jfdS(sl Schedule an assignment handler to be called just after deferred function handlers. N(RReRR(R$R((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytdeferAssignmentscCs7x0|D](\}}}||_||_|qWdS(sV Run the callables in C{deferred} using their associated scope stack. N(RR(R$tdeferredthandlerRXR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRs  cCs)t|jdko(t|jdtS(Nii(tlenRR R|(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt _in_doctestscCs'td|jDstS|jjS(Ncss|]}t|tVqdS(N(R Rz(t.0RX((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pys s(tallRR9RXR{(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytfuturesAlloweds cCs7|tkstt|jtr3t|j_ndS(N(R9ROR RXRzR{(R$R((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRscCs |jdS(Ni(R(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRXscCs|jj|jjdS(N(RReRtpop(R$((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRsc Csx|jD]}t|tr%q n|jd}|rSt|t rSd}n|rzt|j}|j|}n g}}|r!|j rt j j |j dkrx.|D]#}|jtj|dj|qWn|j r!x2|jD]!}t|tr||_qqWq!nx|jD]}t|tr.|jpX|j|k}|stj} |j| |jt|nxl|jD]^} t|j| tjrtj} n|rqn tj} |j| | |j|jqWq.q.Wq WdS(s Look at scopes which have been fully examined and report names in them which were imported but unused. R^s __init__.pyN(RR RjtgetR]R-RxR`t differenceRitostpathtbasenameRtreportRtUndefinedExportR8tvaluesRTR:RCR3t UnusedImportRREt getParentRtFortImportShadowedByLoopVartRedefinedWhileUnused( R$RXt all_bindingt all_namest undefinedR3RvRR:tmessgR0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRsB         cCs|jj|dS(N(RRe(R$t scopeClass((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt pushScopescOs#|jj||j||dS(N(RReR(R$t messageClasstargstkwargs((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRscCs>x7tr9|j}t|d rt|d r|SqWdS(NRctctx(R#tparentR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRs   cCs|||fks1t|do-t|d r5dS||krE|S|j|jkrm|j|j||S|j|jkr|j||j|S|j|j|j|S(NR(RR-tdepthtgetCommonAncestorR(R$tlnodetrnodetstop((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR s! cCs.x'|D]}|j|||rtSqWtS(N(RR#R9(R$R0t ancestorsRta((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt descendantOf-s cCsn|j|||j}t|}|rjx=|D]2}|j||||j|||Ar1tSq1WntS(sATrue, if lnode and rnode are located on different forks of IF/TRY(RRRRR#R9(R$RRtancestortpartsRt((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytdifferentForks3s   cCsx1|jdddD]}|j|krPqqW|j|j}|r|j||j r|j|j}t|trt|tj r|j t j ||j|jq||j kr`t|tjr"t|j|jtj tjf r"|j t j||j|jq|j r|j|r|j t j||j|jqqt|tr|j|r|jj|qn|j|j kr|j |jj|_n||j |js.!   cCsMy|j|SWntk r.t|}nXt|||j|<}|S(N(RtKeyErrorR R,(R$R tnodeTypeR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytgetNodeHandleres  cCst|}|sdSd}d}x|jdddD]}|tkr`t|tr`q9ny|j|f||_Wntk rnXdS|p|j }|tk r9t|t }q9q9W||j krdS|rg}xi|jdddD]Q}xH|j D]:}t|t r |j|f|_|j|jq q WqWdjt|}|jtj|||dS|dkrtjj|jdkrdSd|jdkr|jtj||ndS(Nis, t__path__s __init__.pyt NameError(RR-RR9R RjRXR:RRiRyRRRTReRDtjoinR"RRtImportStarUsageRRRRRt UndefinedName(R$R0R3t in_generatorsRiRXt from_listRv((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pythandleNodeLoadms@   'cCst|}|sdSt|jtr||jkrx|jd D]}t|ttfsfqEn||ko|||j}|rE|d|jkrE||jjkrE|jt j ||jd|||j PqEqEWn|j |}t|t jt jfs)||jkr;|j| r;t||}nH|dkrtt|jtrtt||j|j}nt||}|j||dS(NiiiR^(RR RXRkRRzR:RqRRtUndefinedLocalR8RRRRRtisLiteralTupleUnpackingR7R]RZR(R$R0R3RXR:RRv((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pythandleNodeStores* !+  csfd}t}|s%dS|r2dSt|jtrl||jjkrl|jjj|n8y|j|=Wn'tk r|jtj |nXdS(NcsZtdd}xA|rUt|tjtjtjfr@tSt|dd}qWtS(sN Return `True` if node is part of a conditional body. RN( R,R-R RRtWhiletIfExpR#R9(tcurrent(R0(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyton_conditional_branchs  !( RR RXRkRqtremoveRRRR(R$R0RR3((R0sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pythandleNodeDeletes  $ cCs1x*t|d|D]}|j||qWdS(NR1(R6t handleNode(R$RR1R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRscCsKt|tjrGx.|j|jgD]}t|ds&tSq&WtSdS(NRc(R RtAssignttargetsRRR9R#(R$R0tchild((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRs cCs7t|tjp6t|tjo6t|jtjS(s} Determine if the given node is a docstring, as long as it is at the correct place in the node tree. (R RRdtExprR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt isDocstrings$cCstt|tjr|j}nt|tjs4dStrJ|jd}n|j|jj dd}|j|fS(Nis (NN( R RRRRdR-tPYPYR=Rtcount(R$R0tdoctest_lineno((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt getDocstrings cCs:|dkrdS|jr`t|dddk r`|j|jd7_|j|jd7_n|jrd|j|jjGHn|j rt |t j p|j | rt|_ n|jd7_|j|_||_z |j|j}||Wd|jd8_X|jr6d|jd|jjGHndS(NR=iis send (R-RR,R=t col_offsett traceTreet nodeDepthR+R RR Rt ImportFromRR9RRR(R$R0RR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRs& !     c Csy5|j|jd\}}|o1|j|}Wnttfk rOdSX|sZdS|j}|jdg|_|jpd}|jtd|j k}|s|j j dnx|D]}yt |j ddt j} Wn}tk retjd} tr| jd7_n||j| j|jd| jpEdf} |jtj|| qX|d||j|d|jdf|_|j| ||_qW|s|j jdn|j||_dS(Nit_s texecii(ii(RRt_getDoctestExamplest ValueErrort IndexErrorRRRR|RtaddtcompileR8Rt PyCF_ONLY_ASTt SyntaxErrortsystexc_infoRR=tindentRRtDoctestSyntaxErrorRRR( R$R0t docstringt node_linenotexamplest saved_stackt node_offsettunderscore_in_builtinstexampleRtetposition((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pythandleDoctestss@       cCsdS(N((R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytignore@scCsNt|jtjr=|jjgkr=|jtj|n|j|dS(N( R ttestRRbRcRRt AssertTupleR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytASSERT`s'cCs|jrdnd}|j|}|j|k rx|jD]}t||}g|jD]2}t|tj s|jd|kr]|^q]|_|j ||||f|_ x#|j|dD]}|||WndS(s5 Keep track of globals declarations. iiN( RRRXR`RZRR Rt message_argst setdefaultR:(R$R0tglobal_scope_indext global_scopet node_namet node_valuetmRX((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytGLOBALes "cCs(|jt|j||jdS(N(RRyRR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt GENERATOREXPs  cCst|jtjtjfrs|j||jdkrt|jtrt|j tj rt |j_ qnit|jtj tjfr|j|n;t|jtjr|j|ntd|jfdS(sV Handle occurrence of Name (which can be a load/store/delete access.) tlocalss%Got impossible expression context: %rN(R RRtLoadtAugLoadRR>RXRkRtCallR#RutStoretAugStoreRtDelRt RuntimeError(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytNAMEs !cCs|}xt|dr|j|}}t|tjtjfrY||jkrYdSnt|tjtjfrxPnt|dr t|tj r ||j kr|j t j |dSq q Wt|tj r|j t j|n|j t j|dS(NRt finalbody(RRR RRRRt FunctionDeftClassDeftContinueRRRtContinueInFinallytContinueOutsideLooptBreakOutsideLoop(R$R0Rtn_child((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytCONTINUEs! cCst|jttfr/|jtj|dS|jrit|jdri|jj ri|j|j_ n|j |j|dS(NRr( R RXRjRzRRtReturnOutsideFunctionRRRrR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytRETURNs  cCsRt|jttfr/|jtj|dSt|j_|j |j |dS(N( R RXRjRzRRtYieldOutsideFunctionR#RsRR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytYIELDs  csx!jD]}j|q Wjjtjjrj rtj t  rj fdndS(Ncs jS(N(R((R0R$(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRs( RRtLAMBDARR[R3RRR RXRkR(R$R0tdeco((R0R$sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt FUNCTIONDEFs   c s gg}trCfdjjjj}nWx>jjjjD]&}j|j|j|jqZWjjjj}td}xdD]}t j|}|sqnjt r|n|j|rt r"|d}|jt j|q5|j|jqqW|rR|jj nt t t krxFtD]5\} }|| kr}jtj|q}q}Wnx+||D]} | rj| qqWfd} j| dS(NcsGx@|D]8}t|tjr/|jqj|jqWdS(N(R RRbRcReR>(targlisttarg(taddArgsR(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR+s treturnstvarargtkwargt annotationcsjx'D]}jt|qWtjtrmx7jD]}j|qPWnjjfd}j|trfd}j|nj dS(Ncs=x6jjD]%\}}jtj|j|qWdS(sU Check to see if any assignments have not been used. N(RXRwRRtUnusedVariableR8(R3Rv(R$(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytcheckUnusedAssignmentsscs8jjr4jjr4jtjjjndS(s Check to see if there is any return statement with arguments but the function is a generator. N(RXRsRrRRtReturnWithArgsInsideGenerator((R$(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt&checkReturnWithArgumentInsideGenerator$s ( RRRYR RR/RRtPY32R(R3tstmtR1R3(RR0R$(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt runFunctions   (R-R.(tPY2Rtdefaultst kwonlyargsReR*R/t kw_defaultsRR,tPY33R,RRxt enumerateRRtDuplicateArgumentRR( R$R0t annotationsR8R*t is_py3_functarg_nametwildcardt argannotationtidxRR6((R+RR0R$sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR&s@   !csx!jD]}j|q Wx!jD]}j|q.Wtsux$jD]}j|qXWnjtjrj rt j t  rj fdnx!j D]}j|qWjjtjdS(s Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope. cs jS(N(R((R0R$(sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyRDsN(RRtbasesR7tkeywordsRRjRRR RXRkRRRRR\R3(R$R0R'tbaseNodet keywordNodeR5((R0R$sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytCLASSDEF1s     cCs:|j|j|j|j||j|j|dS(N(RttargetRR(R$R0((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt AUGASSIGNJscCst rt|jtjrt}d}x[t|jD]J\}}t|tjr8|rs|j t j |Pnt }|}q8q8W|dkst |j|ddkr|j t j|qn|j|dS(Niiiiii(R7R RRRR9R<RctStarredRRtTwoStarredExpressionsR#Rt%TooManyExpressionsInStarredAssignmentR(R$R0t has_starredtstar_loctiR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytTUPLEOs )cCs}xv|jD]k}d|jkr>|j r>t|j|}n'|jpM|j}t|||j}|j||q WdS(NRI(R`R3tasnameRHRCR(R$R0taliast importationR3((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytIMPORThs cCs|jdkrM|jsV|jtj|g|jD]}|j^q1qVn t|_x%|jD]}|jpu|j}|jdkrt |||j }|jt j krj|jtj ||jqjn|jdkrOt rt|j t r|jtj||jq`nt|j _|jtj||jt|j|}nt|||j|j}|j||q`WdS(NRWRU(RRRRRtLateFutureImportR`R3R9RRRVRXRWtall_feature_namestFutureFeatureNotDefinedR7R RztImportStarNotPermittedR#RitImportStarUsedRTRQR(R$R0RRSR3RT((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt IMPORTFROMqs.  )      cCs g}xt|jD]\}}t|jtjrdxL|jjD]}|jt|qDWn"|jr|jt|jn|jdkr|t |jdkr|j t j |qqW|jj|x!|jD]}|j||qW|jj|j|dddS(NiR1R(R<RR ttypeRRbRcReRR-RRRtDefaultExceptNotLastRRRRR(R$R0t handler_namesRPRtexc_typeR((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytTRYs ( cCsts|jdkr&|j|dSx=|jdddD]}|j|kr=t}Pq=q=Wt}|j||j||s|j|j=ndS(Ni( R7R3R-RRR#R9RRX(R$R0RXtis_name_previously_defined((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyt EXCEPTHANDLERs   N(R R)R*RR-RR9RRxt builtin_varsRt_MAGIC_GLOBALSRRtenvironRt_customBuiltInstupdateRJR;RRRRRMRtsetterRXRRRkRRRRRRRRRRRRRRRRtdoctestt DocTestParsert get_examplesRRRtDELETEtPRINTtFORtASYNCFORtWHILEtIFtWITHtWITHITEMt ASYNCWITHt ASYNCWITHITEMtRAISEt TRYFINALLYtEXECtEXPRtASSIGNtPASStBOOLOPtBINOPtUNARYOPtIFEXPtDICTtSETtCOMPAREtCALLtREPRt ATTRIBUTEt SUBSCRIPTtSTARREDt NAMECONSTANTtNUMtSTRtBYTEStELLIPSIStSLICEtEXTSLICEtINDEXtLOADtSTOREtDELtAUGLOADtAUGSTOREtPARAMtANDtORtADDtSUBtMULTtDIVtMODtPOWtLSHIFTtRSHIFTtBITORtBITXORtBITANDtFLOORDIVtINVERTtNOTtUADDtUSUBtEQtNOTEQtLTtLTEtGTtGTEtIStISNOTtINtNOTINtMATMULTt COMPREHENSIONtKEYWORDtFORMATTEDVALUERRtNONLOCALRR7tLISTCOMPtDICTCOMPtSETCOMPRR!tBREAKR#R%tAWAITt YIELDFROMR(tASYNCFUNCTIONDEFR&RHRJRQtLISTRUR[R`t TRYEXCEPTRb(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pyR{s     2     '  6        ' >6v          Q     (ii(ii(ii((7R*RWRiRRt version_infoR7R4R;tpypy_version_infoR#RtAttributeErrorR9tdirt __import__RcRt ImportErrort_astRRRRMRtpyflakesRR RRgRR-R6tobjectR7R@RCRHRQRTRVRYRZR[R\R]RfRjRkRyRzR|RdRR(((sN/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/checker.pytsd              (%   PKhUHb>11pyflakes/messages.pyc uVc@sFdZdefdYZdefdYZdefdYZdefdYZd efd YZd efd YZd efdYZdefdYZ defdYZ defdYZ defdYZ defdYZ defdYZdefdYZdefdYZdefd YZd!efd"YZd#efd$YZd%efd&YZd'efd(YZd)efd*YZd+efd,YZd-efd.YZd/efd0YZd1efd2YZd3efd4YZd5S(6s/ Provide the class Message and its subclasses. tMessagecBs&eZdZdZdZdZRS(tcCs.||_|j|_t|dd|_dS(Nt col_offseti(tfilenametlinenotgetattrtcol(tselfRtloc((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyt__init__ s  cCs!d|j|j|j|jfS(Ns %s:%s: %s(RRtmessaget message_args(R((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyt__str__s((t__name__t __module__R R R R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRs t UnusedImportcBseZdZdZRS(s%r imported but unusedcCs#tj||||f|_dS(N(RR R (RRRtname((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR s(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRstRedefinedWhileUnusedcBseZdZdZRS(s&redefinition of unused %r from line %rcCs)tj|||||jf|_dS(N(RR RR (RRRRtorig_loc((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR s(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRstRedefinedInListCompcBseZdZdZRS(s,list comprehension redefines %r from line %rcCs)tj|||||jf|_dS(N(RR RR (RRRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR 's(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR$stImportShadowedByLoopVarcBseZdZdZRS(s0import %r from line %r shadowed by loop variablecCs)tj|||||jf|_dS(N(RR RR (RRRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR /s(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR,stImportStarNotPermittedcBseZdZdZRS(s/'from %s import *' only allowed at module levelcCs#tj||||f|_dS(N(RR R (RRRtmodname((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR 7s(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR4stImportStarUsedcBseZdZdZRS(s9'from %s import *' used; unable to detect undefined namescCs#tj||||f|_dS(N(RR R (RRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR ?s(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR<stImportStarUsagecBseZdZdZRS(s5%s may be undefined, or defined from star imports: %scCs&tj|||||f|_dS(N(RR R (RRRRt from_list((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR Gs(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRDst UndefinedNamecBseZdZdZRS(sundefined name %rcCs#tj||||f|_dS(N(RR R (RRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR Os(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRLstDoctestSyntaxErrorcBseZdZddZRS(ssyntax error in doctestcCs;tj||||r.|\|_|_nd|_dS(N((RR RRR (RRRtposition((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR WsN(R RR tNoneR (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRTstUndefinedExportcBseZdZdZRS(sundefined name %r in __all__cCs#tj||||f|_dS(N(RR R (RRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR as(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR^stUndefinedLocalcBseZdZdZRS(sVlocal variable %r (defined in enclosing scope on line %r) referenced before assignmentcCs)tj|||||jf|_dS(N(RR RR (RRRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR js(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyRfstDuplicateArgumentcBseZdZdZRS(s,duplicate argument %r in function definitioncCs#tj||||f|_dS(N(RR R (RRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR rs(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR ostLateFutureImportcBseZdZdZRS(s?from __future__ imports must occur at the beginning of the filecCs tj|||d|_dS(N((RR R (RRRtnames((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR zs(R RR R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR!wstFutureFeatureNotDefinedcBseZdZdZdZRS(s2An undefined __future__ feature name was imported.s future feature %s is not definedcCs#tj||||f|_dS(N(RR R (RRRR((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR s(R Rt__doc__R R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR#stUnusedVariablecBseZdZdZdZRS(s^ Indicates that a variable has been explicitly assigned to but not actually used. s/local variable %r is assigned to but never usedcCs#tj||||f|_dS(N(RR R (RRRR"((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR s(R RR$R R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR%stReturnWithArgsInsideGeneratorcBseZdZdZRS(sI Indicates a return statement with arguments inside a generator. s''return' with argument inside generator(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR&stReturnOutsideFunctioncBseZdZdZRS(sD Indicates a return statement outside of a function/method. s'return' outside function(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR'stYieldOutsideFunctioncBseZdZdZRS(sQ Indicates a yield or yield from statement outside of a function/method. s'yield' outside function(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR(stContinueOutsideLoopcBseZdZdZRS(sH Indicates a continue statement outside of a while or for loop. s'continue' not properly in loop(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR)stBreakOutsideLoopcBseZdZdZRS(sE Indicates a break statement outside of a while or for loop. s'break' outside loop(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR*stContinueInFinallycBseZdZdZRS(sS Indicates a continue statement in a finally block in a while or for loop. s0'continue' not supported inside 'finally' clause(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR+stDefaultExceptNotLastcBseZdZdZRS(sG Indicates an except: block as not the last exception handler. sdefault 'except:' must be last(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR,stTwoStarredExpressionscBseZdZdZRS(sK Two or more starred expressions in an assignment (a, *b, *c = d). s%two starred expressions in assignment(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR-st%TooManyExpressionsInStarredAssignmentcBseZdZdZRS(sC Too many expressions in an assignment with star-unpacking s1too many expressions in star-unpacking assignment(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR.st AssertTuplecBseZdZdZRS(s; Assertion test is a tuple, which are always True. s5assertion is always true, perhaps remove parentheses?(R RR$R (((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyR/sN(R$tobjectRRRRRRRRRRRRR R!R#R%R&R'R(R)R*R+R,R-R.R/(((sO/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/messages.pyts4     PKhUHuqqpyflakes/api.pyc :FVc@sdZddlmZddlZddlZddlZddlmZmZddlm Z dddd d gZ dd Z dd Zd ZdZdZdddZdS(s, API for the command-line I{pyflakes} tool. i(twith_statementN(tcheckert __version__(treportertcheckt checkPathtcheckRecursivetiterSourceCodetmainc Cs|d krtj}nyt||dtj}WnGtk r_tjd}|j d}|j |j |j }}}t jr#|d kr|j} t| |kr| |d}tjd krt|try|jd}Wqtk r d }qXqqn|d8}n|d krB|j|dn|j|||||dStk r|j|ddSXt j||} | jjddx| jD]} |j| qWt| jS( s Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: The number of warnings emitted. @rtype: C{int} texeciiitasciisproblem decoding sourcetkeycSs|jS(N(tlineno(tm((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pytFsN(i(tNonet modReportert_makeDefaultReportertcompilet_astt PyCF_ONLY_ASTt SyntaxErrortsystexc_infotargsR toffsetttextRtPYPYt splitlinestlent version_infot isinstancetbytestdecodetUnicodeDecodeErrortunexpectedErrort syntaxErrort ExceptiontCheckertmessagestsorttflake( t codeStringtfilenameRttreetvaluetmsgR RRtlinestwtwarning((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyRs>          cCs|dkrtj}nybtjd kr6d}nd}t||}|j}WdQXtjd kr||d7}nWnZtk r|j|ddSt k rtj d}|j||j ddSXt |||S( s Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed iitrUtrbNs sproblem decoding sourcei(ii(ii( RRRRRtopentreadt UnicodeErrorR#tIOErrorRRR(R+RtmodetftcodestrR.((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyRLs$    ccsx|D]z}tjj|r|x_tj|D]F\}}}x4|D],}|jdrEtjj||VqEqEWq/Wq|VqWdS(s Iterate over all Python source files in C{paths}. @param paths: A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is. s.pyN(tostpathtisdirtwalktendswithtjoin(tpathsR<tdirpathtdirnamest filenamesR+((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyRos  "cCs4d}x't|D]}|t||7}qW|S(s; Recursively check all source files in C{paths}. @param paths: A list of paths to Python source files and directories containing Python source files. @param reporter: A L{Reporter} where all of the warnings and errors will be reported to. @return: The number of warnings found. i(RR(RARtwarningst sourcePath((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyRs csoddl}yt||}Wntk r3dSXfd}y|j||Wntk rjnXdS(sHandles a signal with sys.exit. Some of these signals (SIGPIPE, for example) don't exist or are invalid on Windows. So, ignore errors that might arise. iNcstjdS(N(Rtexit(tsigR9(tmessage(sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pythandlers(tsignaltgetattrtAttributeErrort ValueError(tsigNameRIRKt sigNumberRJ((RIsJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyt _exitOnSignals   cCsddl}tddtdd|jd|dt}|jd |\}}tj}|rzt||}ntt j j d |}t |d kdS( s&Entry point for the script "pyflakes".iNtSIGINTs ... stoppedtSIGPIPEitprogtversionRsi( toptparseRQt OptionParserRt parse_argsRRRRRtstdinR5t SystemExit(RTRRVtparsert__RRE((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyRs    (t__doc__t __future__RRR;RtpyflakesRRRRt__all__RRRRRRQR(((sJ/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/api.pyts    < #   PKXjcGafi i pyflakes/reporter.py""" Provide the Reporter class. """ import re import sys class Reporter(object): """ Formats the results of pyflakes checks to users. """ def __init__(self, warningStream, errorStream): """ Construct a L{Reporter}. @param warningStream: A file-like object where warnings will be written to. The stream's C{write} method must accept unicode. C{sys.stdout} is a good value. @param errorStream: A file-like object where error output will be written to. The stream's C{write} method must accept unicode. C{sys.stderr} is a good value. """ self._stdout = warningStream self._stderr = errorStream def unexpectedError(self, filename, msg): """ An unexpected error occurred trying to process C{filename}. @param filename: The path to a file that we could not process. @ptype filename: C{unicode} @param msg: A message explaining the problem. @ptype msg: C{unicode} """ self._stderr.write("%s: %s\n" % (filename, msg)) def syntaxError(self, filename, msg, lineno, offset, text): """ There was a syntax error in C{filename}. @param filename: The path to the file with the syntax error. @ptype filename: C{unicode} @param msg: An explanation of the syntax error. @ptype msg: C{unicode} @param lineno: The line number where the syntax error occurred. @ptype lineno: C{int} @param offset: The column on which the syntax error occurred, or None. @ptype offset: C{int} @param text: The source code containing the syntax error. @ptype text: C{unicode} """ line = text.splitlines()[-1] if offset is not None: offset = offset - (len(text) - len(line)) self._stderr.write('%s:%d:%d: %s\n' % (filename, lineno, offset + 1, msg)) else: self._stderr.write('%s:%d: %s\n' % (filename, lineno, msg)) self._stderr.write(line) self._stderr.write('\n') if offset is not None: self._stderr.write(re.sub(r'\S', ' ', line[:offset]) + "^\n") def flake(self, message): """ pyflakes found something wrong with the code. @param: A L{pyflakes.messages.Message}. """ self._stdout.write(str(message)) self._stdout.write('\n') def _makeDefaultReporter(): """ Make a reporter that can be used when no reporter is specified. """ return Reporter(sys.stdout, sys.stderr) PKGH" pyflakes/__init__.py__version__ = '1.2.2' PKoH {{{pyflakes/test/test_other.py""" Tests for various Pyflakes behavior. """ from sys import version_info from pyflakes import messages as m from pyflakes.test.harness import TestCase, skip, skipIf class Test(TestCase): def test_duplicateArgs(self): self.flakes('def fu(bar, bar): pass', m.DuplicateArgument) def test_localReferencedBeforeAssignment(self): self.flakes(''' a = 1 def f(): a; a=1 f() ''', m.UndefinedLocal, m.UnusedVariable) @skipIf(version_info >= (3,), 'in Python 3 list comprehensions execute in a separate scope') def test_redefinedInListComp(self): """ Test that shadowing a variable in a list comprehension raises a warning. """ self.flakes(''' a = 1 [1 for a, b in [(1, 2)]] ''', m.RedefinedInListComp) self.flakes(''' class A: a = 1 [1 for a, b in [(1, 2)]] ''', m.RedefinedInListComp) self.flakes(''' def f(): a = 1 [1 for a, b in [(1, 2)]] ''', m.RedefinedInListComp) self.flakes(''' [1 for a, b in [(1, 2)]] [1 for a, b in [(1, 2)]] ''') self.flakes(''' for a, b in [(1, 2)]: pass [1 for a, b in [(1, 2)]] ''') def test_redefinedInGenerator(self): """ Test that reusing a variable in a generator does not raise a warning. """ self.flakes(''' a = 1 (1 for a, b in [(1, 2)]) ''') self.flakes(''' class A: a = 1 list(1 for a, b in [(1, 2)]) ''') self.flakes(''' def f(): a = 1 (1 for a, b in [(1, 2)]) ''', m.UnusedVariable) self.flakes(''' (1 for a, b in [(1, 2)]) (1 for a, b in [(1, 2)]) ''') self.flakes(''' for a, b in [(1, 2)]: pass (1 for a, b in [(1, 2)]) ''') @skipIf(version_info < (2, 7), "Python >= 2.7 only") def test_redefinedInSetComprehension(self): """ Test that reusing a variable in a set comprehension does not raise a warning. """ self.flakes(''' a = 1 {1 for a, b in [(1, 2)]} ''') self.flakes(''' class A: a = 1 {1 for a, b in [(1, 2)]} ''') self.flakes(''' def f(): a = 1 {1 for a, b in [(1, 2)]} ''', m.UnusedVariable) self.flakes(''' {1 for a, b in [(1, 2)]} {1 for a, b in [(1, 2)]} ''') self.flakes(''' for a, b in [(1, 2)]: pass {1 for a, b in [(1, 2)]} ''') @skipIf(version_info < (2, 7), "Python >= 2.7 only") def test_redefinedInDictComprehension(self): """ Test that reusing a variable in a dict comprehension does not raise a warning. """ self.flakes(''' a = 1 {1: 42 for a, b in [(1, 2)]} ''') self.flakes(''' class A: a = 1 {1: 42 for a, b in [(1, 2)]} ''') self.flakes(''' def f(): a = 1 {1: 42 for a, b in [(1, 2)]} ''', m.UnusedVariable) self.flakes(''' {1: 42 for a, b in [(1, 2)]} {1: 42 for a, b in [(1, 2)]} ''') self.flakes(''' for a, b in [(1, 2)]: pass {1: 42 for a, b in [(1, 2)]} ''') def test_redefinedFunction(self): """ Test that shadowing a function definition with another one raises a warning. """ self.flakes(''' def a(): pass def a(): pass ''', m.RedefinedWhileUnused) def test_redefinedClassFunction(self): """ Test that shadowing a function definition in a class suite with another one raises a warning. """ self.flakes(''' class A: def a(): pass def a(): pass ''', m.RedefinedWhileUnused) def test_redefinedIfElseFunction(self): """ Test that shadowing a function definition twice in an if and else block does not raise a warning. """ self.flakes(''' if True: def a(): pass else: def a(): pass ''') def test_redefinedIfFunction(self): """ Test that shadowing a function definition within an if block raises a warning. """ self.flakes(''' if True: def a(): pass def a(): pass ''', m.RedefinedWhileUnused) def test_redefinedTryExceptFunction(self): """ Test that shadowing a function definition twice in try and except block does not raise a warning. """ self.flakes(''' try: def a(): pass except: def a(): pass ''') def test_redefinedTryFunction(self): """ Test that shadowing a function definition within a try block raises a warning. """ self.flakes(''' try: def a(): pass def a(): pass except: pass ''', m.RedefinedWhileUnused) def test_redefinedIfElseInListComp(self): """ Test that shadowing a variable in a list comprehension in an if and else block does not raise a warning. """ self.flakes(''' if False: a = 1 else: [a for a in '12'] ''') @skipIf(version_info >= (3,), 'in Python 3 list comprehensions execute in a separate scope') def test_redefinedElseInListComp(self): """ Test that shadowing a variable in a list comprehension in an else (or if) block raises a warning. """ self.flakes(''' if False: pass else: a = 1 [a for a in '12'] ''', m.RedefinedInListComp) def test_functionDecorator(self): """ Test that shadowing a function definition with a decorated version of that function does not raise a warning. """ self.flakes(''' from somewhere import somedecorator def a(): pass a = somedecorator(a) ''') def test_classFunctionDecorator(self): """ Test that shadowing a function definition in a class suite with a decorated version of that function does not raise a warning. """ self.flakes(''' class A: def a(): pass a = classmethod(a) ''') @skipIf(version_info < (2, 6), "Python >= 2.6 only") def test_modernProperty(self): self.flakes(""" class A: @property def t(self): pass @t.setter def t(self, value): pass @t.deleter def t(self): pass """) def test_unaryPlus(self): """Don't die on unary +.""" self.flakes('+1') def test_undefinedBaseClass(self): """ If a name in the base list of a class definition is undefined, a warning is emitted. """ self.flakes(''' class foo(foo): pass ''', m.UndefinedName) def test_classNameUndefinedInClassBody(self): """ If a class name is used in the body of that class's definition and the name is not already defined, a warning is emitted. """ self.flakes(''' class foo: foo ''', m.UndefinedName) def test_classNameDefinedPreviously(self): """ If a class name is used in the body of that class's definition and the name was previously defined in some other way, no warning is emitted. """ self.flakes(''' foo = None class foo: foo ''') def test_classRedefinition(self): """ If a class is defined twice in the same module, a warning is emitted. """ self.flakes(''' class Foo: pass class Foo: pass ''', m.RedefinedWhileUnused) def test_functionRedefinedAsClass(self): """ If a function is redefined as a class, a warning is emitted. """ self.flakes(''' def Foo(): pass class Foo: pass ''', m.RedefinedWhileUnused) def test_classRedefinedAsFunction(self): """ If a class is redefined as a function, a warning is emitted. """ self.flakes(''' class Foo: pass def Foo(): pass ''', m.RedefinedWhileUnused) def test_classWithReturn(self): """ If a return is used inside a class, a warning is emitted. """ self.flakes(''' class Foo(object): return ''', m.ReturnOutsideFunction) def test_moduleWithReturn(self): """ If a return is used at the module level, a warning is emitted. """ self.flakes(''' return ''', m.ReturnOutsideFunction) def test_classWithYield(self): """ If a yield is used inside a class, a warning is emitted. """ self.flakes(''' class Foo(object): yield ''', m.YieldOutsideFunction) def test_moduleWithYield(self): """ If a yield is used at the module level, a warning is emitted. """ self.flakes(''' yield ''', m.YieldOutsideFunction) @skipIf(version_info < (3, 3), "Python >= 3.3 only") def test_classWithYieldFrom(self): """ If a yield from is used inside a class, a warning is emitted. """ self.flakes(''' class Foo(object): yield from range(10) ''', m.YieldOutsideFunction) @skipIf(version_info < (3, 3), "Python >= 3.3 only") def test_moduleWithYieldFrom(self): """ If a yield from is used at the module level, a warning is emitted. """ self.flakes(''' yield from range(10) ''', m.YieldOutsideFunction) def test_continueOutsideLoop(self): self.flakes(''' continue ''', m.ContinueOutsideLoop) self.flakes(''' def f(): continue ''', m.ContinueOutsideLoop) self.flakes(''' while True: pass else: continue ''', m.ContinueOutsideLoop) self.flakes(''' while True: pass else: if 1: if 2: continue ''', m.ContinueOutsideLoop) self.flakes(''' while True: def f(): continue ''', m.ContinueOutsideLoop) self.flakes(''' while True: class A: continue ''', m.ContinueOutsideLoop) def test_continueInsideLoop(self): self.flakes(''' while True: continue ''') self.flakes(''' for i in range(10): continue ''') self.flakes(''' while True: if 1: continue ''') self.flakes(''' for i in range(10): if 1: continue ''') self.flakes(''' while True: while True: pass else: continue else: pass ''') self.flakes(''' while True: try: pass finally: while True: continue ''') def test_continueInFinally(self): # 'continue' inside 'finally' is a special syntax error self.flakes(''' while True: try: pass finally: continue ''', m.ContinueInFinally) self.flakes(''' while True: try: pass finally: if 1: if 2: continue ''', m.ContinueInFinally) # Even when not in a loop, this is the error Python gives self.flakes(''' try: pass finally: continue ''', m.ContinueInFinally) def test_breakOutsideLoop(self): self.flakes(''' break ''', m.BreakOutsideLoop) self.flakes(''' def f(): break ''', m.BreakOutsideLoop) self.flakes(''' while True: pass else: break ''', m.BreakOutsideLoop) self.flakes(''' while True: pass else: if 1: if 2: break ''', m.BreakOutsideLoop) self.flakes(''' while True: def f(): break ''', m.BreakOutsideLoop) self.flakes(''' while True: class A: break ''', m.BreakOutsideLoop) self.flakes(''' try: pass finally: break ''', m.BreakOutsideLoop) def test_breakInsideLoop(self): self.flakes(''' while True: break ''') self.flakes(''' for i in range(10): break ''') self.flakes(''' while True: if 1: break ''') self.flakes(''' for i in range(10): if 1: break ''') self.flakes(''' while True: while True: pass else: break else: pass ''') self.flakes(''' while True: try: pass finally: while True: break ''') self.flakes(''' while True: try: pass finally: break ''') self.flakes(''' while True: try: pass finally: if 1: if 2: break ''') def test_defaultExceptLast(self): """ A default except block should be last. YES: try: ... except Exception: ... except: ... NO: try: ... except: ... except Exception: ... """ self.flakes(''' try: pass except ValueError: pass ''') self.flakes(''' try: pass except ValueError: pass except: pass ''') self.flakes(''' try: pass except: pass ''') self.flakes(''' try: pass except ValueError: pass else: pass ''') self.flakes(''' try: pass except: pass else: pass ''') self.flakes(''' try: pass except ValueError: pass except: pass else: pass ''') def test_defaultExceptNotLast(self): self.flakes(''' try: pass except: pass except ValueError: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass except ValueError: pass ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass else: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except: pass else: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass else: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass except ValueError: pass else: pass ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass except ValueError: pass finally: pass ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass else: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except: pass else: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass else: pass finally: pass ''', m.DefaultExceptNotLast) self.flakes(''' try: pass except: pass except ValueError: pass except: pass except ValueError: pass else: pass finally: pass ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast) @skipIf(version_info < (3,), "Python 3 only") def test_starredAssignmentNoError(self): """ Python 3 extended iterable unpacking """ self.flakes(''' a, *b = range(10) ''') self.flakes(''' *a, b = range(10) ''') self.flakes(''' a, *b, c = range(10) ''') self.flakes(''' (a, *b) = range(10) ''') self.flakes(''' (*a, b) = range(10) ''') self.flakes(''' (a, *b, c) = range(10) ''') self.flakes(''' [a, *b] = range(10) ''') self.flakes(''' [*a, b] = range(10) ''') self.flakes(''' [a, *b, c] = range(10) ''') # Taken from test_unpack_ex.py in the cPython source s = ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \ ", *rest = range(1<<8)" self.flakes(s) s = "(" + ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \ ", *rest) = range(1<<8)" self.flakes(s) s = "[" + ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \ ", *rest] = range(1<<8)" self.flakes(s) @skipIf(version_info < (3, ), "Python 3 only") def test_starredAssignmentErrors(self): """ SyntaxErrors (not encoded in the ast) surrounding Python 3 extended iterable unpacking """ # Taken from test_unpack_ex.py in the cPython source s = ", ".join("a%d" % i for i in range(1 << 8)) + \ ", *rest = range(1<<8 + 1)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) s = "(" + ", ".join("a%d" % i for i in range(1 << 8)) + \ ", *rest) = range(1<<8 + 1)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) s = "[" + ", ".join("a%d" % i for i in range(1 << 8)) + \ ", *rest] = range(1<<8 + 1)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) s = ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \ ", *rest = range(1<<8 + 2)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) s = "(" + ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \ ", *rest) = range(1<<8 + 2)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) s = "[" + ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \ ", *rest] = range(1<<8 + 2)" self.flakes(s, m.TooManyExpressionsInStarredAssignment) # No way we can actually test this! # s = "*rest, " + ", ".join("a%d" % i for i in range(1<<24)) + \ # ", *rest = range(1<<24 + 1)" # self.flakes(s, m.TooManyExpressionsInStarredAssignment) self.flakes(''' a, *b, *c = range(10) ''', m.TwoStarredExpressions) self.flakes(''' a, *b, c, *d = range(10) ''', m.TwoStarredExpressions) self.flakes(''' *a, *b, *c = range(10) ''', m.TwoStarredExpressions) self.flakes(''' (a, *b, *c) = range(10) ''', m.TwoStarredExpressions) self.flakes(''' (a, *b, c, *d) = range(10) ''', m.TwoStarredExpressions) self.flakes(''' (*a, *b, *c) = range(10) ''', m.TwoStarredExpressions) self.flakes(''' [a, *b, *c] = range(10) ''', m.TwoStarredExpressions) self.flakes(''' [a, *b, c, *d] = range(10) ''', m.TwoStarredExpressions) self.flakes(''' [*a, *b, *c] = range(10) ''', m.TwoStarredExpressions) @skip("todo: Too hard to make this warn but other cases stay silent") def test_doubleAssignment(self): """ If a variable is re-assigned to without being used, no warning is emitted. """ self.flakes(''' x = 10 x = 20 ''', m.RedefinedWhileUnused) def test_doubleAssignmentConditionally(self): """ If a variable is re-assigned within a conditional, no warning is emitted. """ self.flakes(''' x = 10 if True: x = 20 ''') def test_doubleAssignmentWithUse(self): """ If a variable is re-assigned to after being used, no warning is emitted. """ self.flakes(''' x = 10 y = x * 2 x = 20 ''') def test_comparison(self): """ If a defined name is used on either side of any of the six comparison operators, no warning is emitted. """ self.flakes(''' x = 10 y = 20 x < y x <= y x == y x != y x >= y x > y ''') def test_identity(self): """ If a defined name is used on either side of an identity test, no warning is emitted. """ self.flakes(''' x = 10 y = 20 x is y x is not y ''') def test_containment(self): """ If a defined name is used on either side of a containment test, no warning is emitted. """ self.flakes(''' x = 10 y = 20 x in y x not in y ''') def test_loopControl(self): """ break and continue statements are supported. """ self.flakes(''' for x in [1, 2]: break ''') self.flakes(''' for x in [1, 2]: continue ''') def test_ellipsis(self): """ Ellipsis in a slice is supported. """ self.flakes(''' [1, 2][...] ''') def test_extendedSlice(self): """ Extended slices are supported. """ self.flakes(''' x = 3 [1, 2][x,:] ''') def test_varAugmentedAssignment(self): """ Augmented assignment of a variable is supported. We don't care about var refs. """ self.flakes(''' foo = 0 foo += 1 ''') def test_attrAugmentedAssignment(self): """ Augmented assignment of attributes is supported. We don't care about attr refs. """ self.flakes(''' foo = None foo.bar += foo.baz ''') def test_globalDeclaredInDifferentScope(self): """ A 'global' can be declared in one scope and reused in another. """ self.flakes(''' def f(): global foo def g(): foo = 'anything'; foo.is_used() ''') class TestUnusedAssignment(TestCase): """ Tests for warning about unused assignments. """ def test_unusedVariable(self): """ Warn when a variable in a function is assigned a value that's never used. """ self.flakes(''' def a(): b = 1 ''', m.UnusedVariable) def test_unusedVariableAsLocals(self): """ Using locals() it is perfectly valid to have unused variables """ self.flakes(''' def a(): b = 1 return locals() ''') def test_unusedVariableNoLocals(self): """ Using locals() in wrong scope should not matter """ self.flakes(''' def a(): locals() def a(): b = 1 return ''', m.UnusedVariable) @skip("todo: Difficult because it does't apply in the context of a loop") def test_unusedReassignedVariable(self): """ Shadowing a used variable can still raise an UnusedVariable warning. """ self.flakes(''' def a(): b = 1 b.foo() b = 2 ''', m.UnusedVariable) def test_variableUsedInLoop(self): """ Shadowing a used variable cannot raise an UnusedVariable warning in the context of a loop. """ self.flakes(''' def a(): b = True while b: b = False ''') def test_assignToGlobal(self): """ Assigning to a global and then not using that global is perfectly acceptable. Do not mistake it for an unused local variable. """ self.flakes(''' b = 0 def a(): global b b = 1 ''') @skipIf(version_info < (3,), 'new in Python 3') def test_assignToNonlocal(self): """ Assigning to a nonlocal and then not using that binding is perfectly acceptable. Do not mistake it for an unused local variable. """ self.flakes(''' b = b'0' def a(): nonlocal b b = b'1' ''') def test_assignToMember(self): """ Assigning to a member of another object and then not using that member variable is perfectly acceptable. Do not mistake it for an unused local variable. """ # XXX: Adding this test didn't generate a failure. Maybe not # necessary? self.flakes(''' class b: pass def a(): b.foo = 1 ''') def test_assignInForLoop(self): """ Don't warn when a variable in a for loop is assigned to but not used. """ self.flakes(''' def f(): for i in range(10): pass ''') def test_assignInListComprehension(self): """ Don't warn when a variable in a list comprehension is assigned to but not used. """ self.flakes(''' def f(): [None for i in range(10)] ''') def test_generatorExpression(self): """ Don't warn when a variable in a generator expression is assigned to but not used. """ self.flakes(''' def f(): (None for i in range(10)) ''') def test_assignmentInsideLoop(self): """ Don't warn when a variable assignment occurs lexically after its use. """ self.flakes(''' def f(): x = None for i in range(10): if i > 2: return x x = i * 2 ''') def test_tupleUnpacking(self): """ Don't warn when a variable included in tuple unpacking is unused. It's very common for variables in a tuple unpacking assignment to be unused in good Python code, so warning will only create false positives. """ self.flakes(''' def f(tup): (x, y) = tup ''') self.flakes(''' def f(): (x, y) = 1, 2 ''', m.UnusedVariable, m.UnusedVariable) self.flakes(''' def f(): (x, y) = coords = 1, 2 if x > 1: print(coords) ''') self.flakes(''' def f(): (x, y) = coords = 1, 2 ''', m.UnusedVariable) self.flakes(''' def f(): coords = (x, y) = 1, 2 ''', m.UnusedVariable) def test_listUnpacking(self): """ Don't warn when a variable included in list unpacking is unused. """ self.flakes(''' def f(tup): [x, y] = tup ''') self.flakes(''' def f(): [x, y] = [1, 2] ''', m.UnusedVariable, m.UnusedVariable) def test_closedOver(self): """ Don't warn when the assignment is used in an inner function. """ self.flakes(''' def barMaker(): foo = 5 def bar(): return foo return bar ''') def test_doubleClosedOver(self): """ Don't warn when the assignment is used in an inner function, even if that inner function itself is in an inner function. """ self.flakes(''' def barMaker(): foo = 5 def bar(): def baz(): return foo return bar ''') def test_tracebackhideSpecialVariable(self): """ Do not warn about unused local variable __tracebackhide__, which is a special variable for py.test. """ self.flakes(""" def helper(): __tracebackhide__ = True """) def test_ifexp(self): """ Test C{foo if bar else baz} statements. """ self.flakes("a = 'moo' if True else 'oink'") self.flakes("a = foo if True else 'oink'", m.UndefinedName) self.flakes("a = 'moo' if True else bar", m.UndefinedName) def test_withStatementNoNames(self): """ No warnings are emitted for using inside or after a nameless C{with} statement a name defined beforehand. """ self.flakes(''' from __future__ import with_statement bar = None with open("foo"): bar bar ''') def test_withStatementSingleName(self): """ No warnings are emitted for using a name defined by a C{with} statement within the suite or afterwards. """ self.flakes(''' from __future__ import with_statement with open('foo') as bar: bar bar ''') def test_withStatementAttributeName(self): """ No warnings are emitted for using an attribute as the target of a C{with} statement. """ self.flakes(''' from __future__ import with_statement import foo with open('foo') as foo.bar: pass ''') def test_withStatementSubscript(self): """ No warnings are emitted for using a subscript as the target of a C{with} statement. """ self.flakes(''' from __future__ import with_statement import foo with open('foo') as foo[0]: pass ''') def test_withStatementSubscriptUndefined(self): """ An undefined name warning is emitted if the subscript used as the target of a C{with} statement is not defined. """ self.flakes(''' from __future__ import with_statement import foo with open('foo') as foo[bar]: pass ''', m.UndefinedName) def test_withStatementTupleNames(self): """ No warnings are emitted for using any of the tuple of names defined by a C{with} statement within the suite or afterwards. """ self.flakes(''' from __future__ import with_statement with open('foo') as (bar, baz): bar, baz bar, baz ''') def test_withStatementListNames(self): """ No warnings are emitted for using any of the list of names defined by a C{with} statement within the suite or afterwards. """ self.flakes(''' from __future__ import with_statement with open('foo') as [bar, baz]: bar, baz bar, baz ''') def test_withStatementComplicatedTarget(self): """ If the target of a C{with} statement uses any or all of the valid forms for that part of the grammar (See U{http://docs.python.org/reference/compound_stmts.html#the-with-statement}), the names involved are checked both for definedness and any bindings created are respected in the suite of the statement and afterwards. """ self.flakes(''' from __future__ import with_statement c = d = e = g = h = i = None with open('foo') as [(a, b), c[d], e.f, g[h:i]]: a, b, c, d, e, g, h, i a, b, c, d, e, g, h, i ''') def test_withStatementSingleNameUndefined(self): """ An undefined name warning is emitted if the name first defined by a C{with} statement is used before the C{with} statement. """ self.flakes(''' from __future__ import with_statement bar with open('foo') as bar: pass ''', m.UndefinedName) def test_withStatementTupleNamesUndefined(self): """ An undefined name warning is emitted if a name first defined by a the tuple-unpacking form of the C{with} statement is used before the C{with} statement. """ self.flakes(''' from __future__ import with_statement baz with open('foo') as (bar, baz): pass ''', m.UndefinedName) def test_withStatementSingleNameRedefined(self): """ A redefined name warning is emitted if a name bound by an import is rebound by the name defined by a C{with} statement. """ self.flakes(''' from __future__ import with_statement import bar with open('foo') as bar: pass ''', m.RedefinedWhileUnused) def test_withStatementTupleNamesRedefined(self): """ A redefined name warning is emitted if a name bound by an import is rebound by one of the names defined by the tuple-unpacking form of a C{with} statement. """ self.flakes(''' from __future__ import with_statement import bar with open('foo') as (bar, baz): pass ''', m.RedefinedWhileUnused) def test_withStatementUndefinedInside(self): """ An undefined name warning is emitted if a name is used inside the body of a C{with} statement without first being bound. """ self.flakes(''' from __future__ import with_statement with open('foo') as bar: baz ''', m.UndefinedName) def test_withStatementNameDefinedInBody(self): """ A name defined in the body of a C{with} statement can be used after the body ends without warning. """ self.flakes(''' from __future__ import with_statement with open('foo') as bar: baz = 10 baz ''') def test_withStatementUndefinedInExpression(self): """ An undefined name warning is emitted if a name in the I{test} expression of a C{with} statement is undefined. """ self.flakes(''' from __future__ import with_statement with bar as baz: pass ''', m.UndefinedName) self.flakes(''' from __future__ import with_statement with bar as bar: pass ''', m.UndefinedName) @skipIf(version_info < (2, 7), "Python >= 2.7 only") def test_dictComprehension(self): """ Dict comprehensions are properly handled. """ self.flakes(''' a = {1: x for x in range(10)} ''') @skipIf(version_info < (2, 7), "Python >= 2.7 only") def test_setComprehensionAndLiteral(self): """ Set comprehensions are properly handled. """ self.flakes(''' a = {1, 2, 3} b = {x for x in range(10)} ''') def test_exceptionUsedInExcept(self): as_exc = ', ' if version_info < (2, 6) else ' as ' self.flakes(''' try: pass except Exception%se: e ''' % as_exc) self.flakes(''' def download_review(): try: pass except Exception%se: e ''' % as_exc) def test_exceptWithoutNameInFunction(self): """ Don't issue false warning when an unnamed exception is used. Previously, there would be a false warning, but only when the try..except was in a function """ self.flakes(''' import tokenize def foo(): try: pass except tokenize.TokenError: pass ''') def test_exceptWithoutNameInFunctionTuple(self): """ Don't issue false warning when an unnamed exception is used. This example catches a tuple of exception types. """ self.flakes(''' import tokenize def foo(): try: pass except (tokenize.TokenError, IndentationError): pass ''') def test_augmentedAssignmentImportedFunctionCall(self): """ Consider a function that is called on the right part of an augassign operation to be used. """ self.flakes(''' from foo import bar baz = 0 baz += bar() ''') def test_assert_without_message(self): """An assert without a message is not an error.""" self.flakes(''' a = 1 assert a ''') def test_assert_with_message(self): """An assert with a message is not an error.""" self.flakes(''' a = 1 assert a, 'x' ''') def test_assert_tuple(self): """An assert of a non-empty tuple is always True.""" self.flakes(''' assert (False, 'x') assert (False, ) ''', m.AssertTuple, m.AssertTuple) def test_assert_tuple_empty(self): """An assert of an empty tuple is always False.""" self.flakes(''' assert () ''') def test_assert_static(self): """An assert of a static value is not an error.""" self.flakes(''' assert True assert 1 ''') @skipIf(version_info < (3, 3), 'new in Python 3.3') def test_yieldFromUndefined(self): """ Test C{yield from} statement """ self.flakes(''' def bar(): yield from foo() ''', m.UndefinedName) @skipIf(version_info < (3, 6), 'new in Python 3.6') def test_f_string(self): """Test PEP 498 f-strings are treated as a usage.""" self.flakes(''' baz = 0 print(f'\x7b4*baz\N{RIGHT CURLY BRACKET}') ''') class TestAsyncStatements(TestCase): @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncDef(self): self.flakes(''' async def bar(): return 42 ''') @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncDefAwait(self): self.flakes(''' async def read_data(db): await db.fetch('SELECT ...') ''') @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncDefUndefined(self): self.flakes(''' async def bar(): return foo() ''', m.UndefinedName) @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncFor(self): self.flakes(''' async def read_data(db): output = [] async for row in db.cursor(): output.append(row) return output ''') @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncWith(self): self.flakes(''' async def commit(session, data): async with session.transaction(): await session.update(data) ''') @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_asyncWithItem(self): self.flakes(''' async def commit(session, data): async with session.transaction() as trans: await trans.begin() ... await trans.end() ''') @skipIf(version_info < (3, 5), 'new in Python 3.5') def test_matmul(self): self.flakes(''' def foo(a, b): return a @ b ''') PKjqG8;y y pyflakes/test/harness.py import sys import textwrap import unittest from pyflakes import checker __all__ = ['TestCase', 'skip', 'skipIf'] if sys.version_info < (2, 7): skip = lambda why: (lambda func: 'skip') # not callable skipIf = lambda cond, why: (skip(why) if cond else lambda func: func) else: skip = unittest.skip skipIf = unittest.skipIf PyCF_ONLY_AST = 1024 class TestCase(unittest.TestCase): withDoctest = False def flakes(self, input, *expectedOutputs, **kw): tree = compile(textwrap.dedent(input), "", "exec", PyCF_ONLY_AST) w = checker.Checker(tree, withDoctest=self.withDoctest, **kw) outputs = [type(o) for o in w.messages] expectedOutputs = list(expectedOutputs) outputs.sort(key=lambda t: t.__name__) expectedOutputs.sort(key=lambda t: t.__name__) self.assertEqual(outputs, expectedOutputs, '''\ for input: %s expected outputs: %r but got: %s''' % (input, expectedOutputs, '\n'.join([str(o) for o in w.messages]))) return w if not hasattr(unittest.TestCase, 'assertIs'): def assertIs(self, expr1, expr2, msg=None): if expr1 is not expr2: self.fail(msg or '%r is not %r' % (expr1, expr2)) if not hasattr(unittest.TestCase, 'assertIsInstance'): def assertIsInstance(self, obj, cls, msg=None): """Same as self.assertTrue(isinstance(obj, cls)).""" if not isinstance(obj, cls): self.fail(msg or '%r is not an instance of %r' % (obj, cls)) if not hasattr(unittest.TestCase, 'assertNotIsInstance'): def assertNotIsInstance(self, obj, cls, msg=None): """Same as self.assertFalse(isinstance(obj, cls)).""" if isinstance(obj, cls): self.fail(msg or '%r is an instance of %r' % (obj, cls)) if not hasattr(unittest.TestCase, 'assertIn'): def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b).""" if member not in container: self.fail(msg or '%r not found in %r' % (member, container)) if not hasattr(unittest.TestCase, 'assertNotIn'): def assertNotIn(self, member, container, msg=None): """Just like self.assertTrue(a not in b).""" if member in container: self.fail(msg or '%r unexpectedly found in %r' % (member, container)) PKq7E p<pyflakes/test/test_return_with_arguments_inside_generator.py from sys import version_info from pyflakes import messages as m from pyflakes.test.harness import TestCase, skipIf class Test(TestCase): @skipIf(version_info >= (3, 3), 'new in Python 3.3') def test_return(self): self.flakes(''' class a: def b(): for x in a.c: if x: yield x return a ''', m.ReturnWithArgsInsideGenerator) @skipIf(version_info >= (3, 3), 'new in Python 3.3') def test_returnNone(self): self.flakes(''' def a(): yield 12 return None ''', m.ReturnWithArgsInsideGenerator) @skipIf(version_info >= (3, 3), 'new in Python 3.3') def test_returnYieldExpression(self): self.flakes(''' def a(): b = yield a return b ''', m.ReturnWithArgsInsideGenerator) PKhUH=rpyflakes/test/harness.pyc (KVc@sddlZddlZddlZddlmZdddgZejd krgdZd ZnejZejZd Z dej fd YZ dS( iN(tcheckertTestCasetskiptskipIfiicCsdS(NcSsdS(NR((tfunc((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyt s((twhy((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR scCs|rt|SdS(NcSs|S(N((R((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR s(R(tcondR((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR sicBseZeZdZeejds6d dZ neejdsWd dZ neejdsxd dZ neejdsd dZ neejd sd d Z nRS( c Osttj|ddt}tj|d|j|}g|jD]}t|^qC}t |}|j dd|j dd|j ||d||dj g|jD]}t |^qf|S( Nstexect withDoctesttkeycSs|jS(N(t__name__(tt((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyRscSs|jS(N(R (R ((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyRss.for input: %s expected outputs: %r but got: %ss (tcompilettextwraptdedentt PyCF_ONLY_ASTRtCheckerR tmessagesttypetlisttsortt assertEqualtjointstr(tselftinputtexpectedOutputstkwttreetwtotoutputs((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pytflakess"  9tassertIscCs0||k r,|j|p%d||fndS(Ns %r is not %r(tfail(Rtexpr1texpr2tmsg((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR")s tassertIsInstancecCs3t||s/|j|p(d||fndS(s.Same as self.assertTrue(isinstance(obj, cls)).s%r is not an instance of %rN(t isinstanceR#(RtobjtclsR&((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR'/stassertNotIsInstancecCs3t||r/|j|p(d||fndS(s/Same as self.assertFalse(isinstance(obj, cls)).s%r is an instance of %rN(R(R#(RR)R*R&((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR+6stassertIncCs0||kr,|j|p%d||fndS(s"Just like self.assertTrue(a in b).s%r not found in %rN(R#(Rtmembert containerR&((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR,=s t assertNotIncCs0||kr,|j|p%d||fndS(s&Just like self.assertTrue(a not in b).s%r unexpectedly found in %rN(R#(RR-R.R&((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyR/Ds  N(R t __module__tFalseR R!thasattrtunittestRtNoneR"R'R+R,R/(((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyRs (ii( tsysRR3tpyflakesRt__all__t version_infoRRRR(((sS/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/harness.pyts       PKpaH8R 00pyflakes/test/test_doctests.pyimport sys import textwrap from pyflakes import messages as m from pyflakes.checker import ( DoctestScope, FunctionScope, ModuleScope, ) from pyflakes.test.test_other import Test as TestOther from pyflakes.test.test_imports import Test as TestImports from pyflakes.test.test_undefined_names import Test as TestUndefinedNames from pyflakes.test.harness import TestCase, skip try: sys.pypy_version_info PYPY = True except AttributeError: PYPY = False class _DoctestMixin(object): withDoctest = True def doctestify(self, input): lines = [] for line in textwrap.dedent(input).splitlines(): if line.strip() == '': pass elif (line.startswith(' ') or line.startswith('except:') or line.startswith('except ') or line.startswith('finally:') or line.startswith('else:') or line.startswith('elif ')): line = "... %s" % line else: line = ">>> %s" % line lines.append(line) doctestificator = textwrap.dedent('''\ def doctest_something(): """ %s """ ''') return doctestificator % "\n ".join(lines) def flakes(self, input, *args, **kw): return super(_DoctestMixin, self).flakes(self.doctestify(input), *args, **kw) class Test(TestCase): withDoctest = True def test_scope_class(self): """Check that a doctest is given a DoctestScope.""" checker = self.flakes(""" m = None def doctest_stuff(): ''' >>> d = doctest_stuff() ''' f = m return f """) scopes = checker.deadScopes module_scopes = [ scope for scope in scopes if scope.__class__ is ModuleScope] doctest_scopes = [ scope for scope in scopes if scope.__class__ is DoctestScope] function_scopes = [ scope for scope in scopes if scope.__class__ is FunctionScope] self.assertEqual(len(module_scopes), 1) self.assertEqual(len(doctest_scopes), 1) module_scope = module_scopes[0] doctest_scope = doctest_scopes[0] self.assertIsInstance(doctest_scope, DoctestScope) self.assertIsInstance(doctest_scope, ModuleScope) self.assertNotIsInstance(doctest_scope, FunctionScope) self.assertNotIsInstance(module_scope, DoctestScope) self.assertIn('m', module_scope) self.assertIn('doctest_stuff', module_scope) self.assertIn('d', doctest_scope) self.assertEqual(len(function_scopes), 1) self.assertIn('f', function_scopes[0]) def test_nested_doctest_ignored(self): """Check that nested doctests are ignored.""" checker = self.flakes(""" m = None def doctest_stuff(): ''' >>> def function_in_doctest(): ... \"\"\" ... >>> ignored_undefined_name ... \"\"\" ... df = m ... return df ... >>> function_in_doctest() ''' f = m return f """) scopes = checker.deadScopes module_scopes = [ scope for scope in scopes if scope.__class__ is ModuleScope] doctest_scopes = [ scope for scope in scopes if scope.__class__ is DoctestScope] function_scopes = [ scope for scope in scopes if scope.__class__ is FunctionScope] self.assertEqual(len(module_scopes), 1) self.assertEqual(len(doctest_scopes), 1) module_scope = module_scopes[0] doctest_scope = doctest_scopes[0] self.assertIn('m', module_scope) self.assertIn('doctest_stuff', module_scope) self.assertIn('function_in_doctest', doctest_scope) self.assertEqual(len(function_scopes), 2) self.assertIn('f', function_scopes[0]) self.assertIn('df', function_scopes[1]) def test_global_module_scope_pollution(self): """Check that global in doctest does not pollute module scope.""" checker = self.flakes(""" def doctest_stuff(): ''' >>> def function_in_doctest(): ... global m ... m = 50 ... df = 10 ... m = df ... >>> function_in_doctest() ''' f = 10 return f """) scopes = checker.deadScopes module_scopes = [ scope for scope in scopes if scope.__class__ is ModuleScope] doctest_scopes = [ scope for scope in scopes if scope.__class__ is DoctestScope] function_scopes = [ scope for scope in scopes if scope.__class__ is FunctionScope] self.assertEqual(len(module_scopes), 1) self.assertEqual(len(doctest_scopes), 1) module_scope = module_scopes[0] doctest_scope = doctest_scopes[0] self.assertIn('doctest_stuff', module_scope) self.assertIn('function_in_doctest', doctest_scope) self.assertEqual(len(function_scopes), 2) self.assertIn('f', function_scopes[0]) self.assertIn('df', function_scopes[1]) self.assertIn('m', function_scopes[1]) self.assertNotIn('m', module_scope) def test_global_undefined(self): self.flakes(""" global m def doctest_stuff(): ''' >>> m ''' """, m.UndefinedName) def test_nested_class(self): """Doctest within nested class are processed.""" self.flakes(""" class C: class D: ''' >>> m ''' def doctest_stuff(self): ''' >>> m ''' return 1 """, m.UndefinedName, m.UndefinedName) def test_ignore_nested_function(self): """Doctest module does not process doctest in nested functions.""" # 'syntax error' would cause a SyntaxError if the doctest was processed. # However doctest does not find doctest in nested functions # (https://bugs.python.org/issue1650090). If nested functions were # processed, this use of m should cause UndefinedName, and the # name inner_function should probably exist in the doctest scope. self.flakes(""" def doctest_stuff(): def inner_function(): ''' >>> syntax error >>> inner_function() 1 >>> m ''' return 1 m = inner_function() return m """) def test_inaccessible_scope_class(self): """Doctest may not access class scope.""" self.flakes(""" class C: def doctest_stuff(self): ''' >>> m ''' return 1 m = 1 """, m.UndefinedName) def test_importBeforeDoctest(self): self.flakes(""" import foo def doctest_stuff(): ''' >>> foo ''' """) @skip("todo") def test_importBeforeAndInDoctest(self): self.flakes(''' import foo def doctest_stuff(): """ >>> import foo >>> foo """ foo ''', m.RedefinedWhileUnused) def test_importInDoctestAndAfter(self): self.flakes(''' def doctest_stuff(): """ >>> import foo >>> foo """ import foo foo() ''') def test_offsetInDoctests(self): exc = self.flakes(''' def doctest_stuff(): """ >>> x # line 5 """ ''', m.UndefinedName).messages[0] self.assertEqual(exc.lineno, 5) self.assertEqual(exc.col, 12) def test_offsetInLambdasInDoctests(self): exc = self.flakes(''' def doctest_stuff(): """ >>> lambda: x # line 5 """ ''', m.UndefinedName).messages[0] self.assertEqual(exc.lineno, 5) self.assertEqual(exc.col, 20) def test_offsetAfterDoctests(self): exc = self.flakes(''' def doctest_stuff(): """ >>> x = 5 """ x ''', m.UndefinedName).messages[0] self.assertEqual(exc.lineno, 8) self.assertEqual(exc.col, 0) def test_syntaxErrorInDoctest(self): exceptions = self.flakes( ''' def doctest_stuff(): """ >>> from # line 4 >>> fortytwo = 42 >>> except Exception: """ ''', m.DoctestSyntaxError, m.DoctestSyntaxError, m.DoctestSyntaxError).messages exc = exceptions[0] self.assertEqual(exc.lineno, 4) self.assertEqual(exc.col, 26) # PyPy error column offset is 0, # for the second and third line of the doctest # i.e. at the beginning of the line exc = exceptions[1] self.assertEqual(exc.lineno, 5) if PYPY: self.assertEqual(exc.col, 13) else: self.assertEqual(exc.col, 16) exc = exceptions[2] self.assertEqual(exc.lineno, 6) if PYPY: self.assertEqual(exc.col, 13) else: self.assertEqual(exc.col, 18) def test_indentationErrorInDoctest(self): exc = self.flakes(''' def doctest_stuff(): """ >>> if True: ... pass """ ''', m.DoctestSyntaxError).messages[0] self.assertEqual(exc.lineno, 5) if PYPY: self.assertEqual(exc.col, 13) else: self.assertEqual(exc.col, 16) def test_offsetWithMultiLineArgs(self): (exc1, exc2) = self.flakes( ''' def doctest_stuff(arg1, arg2, arg3): """ >>> assert >>> this """ ''', m.DoctestSyntaxError, m.UndefinedName).messages self.assertEqual(exc1.lineno, 6) self.assertEqual(exc1.col, 19) self.assertEqual(exc2.lineno, 7) self.assertEqual(exc2.col, 12) def test_doctestCanReferToFunction(self): self.flakes(""" def foo(): ''' >>> foo ''' """) def test_doctestCanReferToClass(self): self.flakes(""" class Foo(): ''' >>> Foo ''' def bar(self): ''' >>> Foo ''' """) def test_noOffsetSyntaxErrorInDoctest(self): exceptions = self.flakes( ''' def buildurl(base, *args, **kwargs): """ >>> buildurl('/blah.php', ('a', '&'), ('b', '=') '/blah.php?a=%26&b=%3D' >>> buildurl('/blah.php', a='&', 'b'='=') '/blah.php?b=%3D&a=%26' """ pass ''', m.DoctestSyntaxError, m.DoctestSyntaxError).messages exc = exceptions[0] self.assertEqual(exc.lineno, 4) exc = exceptions[1] self.assertEqual(exc.lineno, 6) def test_singleUnderscoreInDoctest(self): self.flakes(''' def func(): """A docstring >>> func() 1 >>> _ 1 """ return 1 ''') class TestOther(_DoctestMixin, TestOther): """Run TestOther with each test wrapped in a doctest.""" class TestImports(_DoctestMixin, TestImports): """Run TestImports with each test wrapped in a doctest.""" class TestUndefinedNames(_DoctestMixin, TestUndefinedNames): """Run TestUndefinedNames with each test wrapped in a doctest.""" PKHןpppyflakes/test/test_imports.py from sys import version_info from pyflakes import messages as m from pyflakes.checker import ( FutureImportation, Importation, ImportationFrom, StarImportation, SubmoduleImportation, ) from pyflakes.test.harness import TestCase, skip, skipIf class TestImportationObject(TestCase): def test_import_basic(self): binding = Importation('a', None, 'a') assert binding.source_statement == 'import a' assert str(binding) == 'a' def test_import_as(self): binding = Importation('c', None, 'a') assert binding.source_statement == 'import a as c' assert str(binding) == 'a as c' def test_import_submodule(self): binding = SubmoduleImportation('a.b', None) assert binding.source_statement == 'import a.b' assert str(binding) == 'a.b' def test_import_submodule_as(self): # A submodule import with an as clause is not a SubmoduleImportation binding = Importation('c', None, 'a.b') assert binding.source_statement == 'import a.b as c' assert str(binding) == 'a.b as c' def test_import_submodule_as_source_name(self): binding = Importation('a', None, 'a.b') assert binding.source_statement == 'import a.b as a' assert str(binding) == 'a.b as a' def test_importfrom_member(self): binding = ImportationFrom('b', None, 'a', 'b') assert binding.source_statement == 'from a import b' assert str(binding) == 'a.b' def test_importfrom_submodule_member(self): binding = ImportationFrom('c', None, 'a.b', 'c') assert binding.source_statement == 'from a.b import c' assert str(binding) == 'a.b.c' def test_importfrom_member_as(self): binding = ImportationFrom('c', None, 'a', 'b') assert binding.source_statement == 'from a import b as c' assert str(binding) == 'a.b as c' def test_importfrom_submodule_member_as(self): binding = ImportationFrom('d', None, 'a.b', 'c') assert binding.source_statement == 'from a.b import c as d' assert str(binding) == 'a.b.c as d' def test_importfrom_star(self): binding = StarImportation('a.b', None) assert binding.source_statement == 'from a.b import *' assert str(binding) == 'a.b.*' def test_importfrom_future(self): binding = FutureImportation('print_function', None, None) assert binding.source_statement == 'from __future__ import print_function' assert str(binding) == '__future__.print_function' class Test(TestCase): def test_unusedImport(self): self.flakes('import fu, bar', m.UnusedImport, m.UnusedImport) self.flakes('from baz import fu, bar', m.UnusedImport, m.UnusedImport) def test_aliasedImport(self): self.flakes('import fu as FU, bar as FU', m.RedefinedWhileUnused, m.UnusedImport) self.flakes('from moo import fu as FU, bar as FU', m.RedefinedWhileUnused, m.UnusedImport) def test_aliasedImportShadowModule(self): """Imported aliases can shadow the source of the import.""" self.flakes('from moo import fu as moo; moo') self.flakes('import fu as fu; fu') self.flakes('import fu.bar as fu; fu') def test_usedImport(self): self.flakes('import fu; print(fu)') self.flakes('from baz import fu; print(fu)') self.flakes('import fu; del fu') def test_redefinedWhileUnused(self): self.flakes('import fu; fu = 3', m.RedefinedWhileUnused) self.flakes('import fu; fu, bar = 3', m.RedefinedWhileUnused) self.flakes('import fu; [fu, bar] = 3', m.RedefinedWhileUnused) def test_redefinedIf(self): """ Test that importing a module twice within an if block does raise a warning. """ self.flakes(''' i = 2 if i==1: import os import os os.path''', m.RedefinedWhileUnused) def test_redefinedIfElse(self): """ Test that importing a module twice in if and else blocks does not raise a warning. """ self.flakes(''' i = 2 if i==1: import os else: import os os.path''') def test_redefinedTry(self): """ Test that importing a module twice in an try block does raise a warning. """ self.flakes(''' try: import os import os except: pass os.path''', m.RedefinedWhileUnused) def test_redefinedTryExcept(self): """ Test that importing a module twice in an try and except block does not raise a warning. """ self.flakes(''' try: import os except: import os os.path''') def test_redefinedTryNested(self): """ Test that importing a module twice using a nested try/except and if blocks does not issue a warning. """ self.flakes(''' try: if True: if True: import os except: import os os.path''') def test_redefinedTryExceptMulti(self): self.flakes(""" try: from aa import mixer except AttributeError: from bb import mixer except RuntimeError: from cc import mixer except: from dd import mixer mixer(123) """) def test_redefinedTryElse(self): self.flakes(""" try: from aa import mixer except ImportError: pass else: from bb import mixer mixer(123) """, m.RedefinedWhileUnused) def test_redefinedTryExceptElse(self): self.flakes(""" try: import funca except ImportError: from bb import funca from bb import funcb else: from bbb import funcb print(funca, funcb) """) def test_redefinedTryExceptFinally(self): self.flakes(""" try: from aa import a except ImportError: from bb import a finally: a = 42 print(a) """) def test_redefinedTryExceptElseFinally(self): self.flakes(""" try: import b except ImportError: b = Ellipsis from bb import a else: from aa import a finally: a = 42 print(a, b) """) def test_redefinedByFunction(self): self.flakes(''' import fu def fu(): pass ''', m.RedefinedWhileUnused) def test_redefinedInNestedFunction(self): """ Test that shadowing a global name with a nested function definition generates a warning. """ self.flakes(''' import fu def bar(): def baz(): def fu(): pass ''', m.RedefinedWhileUnused, m.UnusedImport) def test_redefinedInNestedFunctionTwice(self): """ Test that shadowing a global name with a nested function definition generates a warning. """ self.flakes(''' import fu def bar(): import fu def baz(): def fu(): pass ''', m.RedefinedWhileUnused, m.RedefinedWhileUnused, m.UnusedImport, m.UnusedImport) def test_redefinedButUsedLater(self): """ Test that a global import which is redefined locally, but used later in another scope does not generate a warning. """ self.flakes(''' import unittest, transport class GetTransportTestCase(unittest.TestCase): def test_get_transport(self): transport = 'transport' self.assertIsNotNone(transport) class TestTransportMethodArgs(unittest.TestCase): def test_send_defaults(self): transport.Transport() ''') def test_redefinedByClass(self): self.flakes(''' import fu class fu: pass ''', m.RedefinedWhileUnused) def test_redefinedBySubclass(self): """ If an imported name is redefined by a class statement which also uses that name in the bases list, no warning is emitted. """ self.flakes(''' from fu import bar class bar(bar): pass ''') def test_redefinedInClass(self): """ Test that shadowing a global with a class attribute does not produce a warning. """ self.flakes(''' import fu class bar: fu = 1 print(fu) ''') def test_importInClass(self): """ Test that import within class is a locally scoped attribute. """ self.flakes(''' class bar: import fu ''') self.flakes(''' class bar: import fu fu ''', m.UndefinedName) def test_usedInFunction(self): self.flakes(''' import fu def fun(): print(fu) ''') def test_shadowedByParameter(self): self.flakes(''' import fu def fun(fu): print(fu) ''', m.UnusedImport, m.RedefinedWhileUnused) self.flakes(''' import fu def fun(fu): print(fu) print(fu) ''') def test_newAssignment(self): self.flakes('fu = None') def test_usedInGetattr(self): self.flakes('import fu; fu.bar.baz') self.flakes('import fu; "bar".fu.baz', m.UnusedImport) def test_usedInSlice(self): self.flakes('import fu; print(fu.bar[1:])') def test_usedInIfBody(self): self.flakes(''' import fu if True: print(fu) ''') def test_usedInIfConditional(self): self.flakes(''' import fu if fu: pass ''') def test_usedInElifConditional(self): self.flakes(''' import fu if False: pass elif fu: pass ''') def test_usedInElse(self): self.flakes(''' import fu if False: pass else: print(fu) ''') def test_usedInCall(self): self.flakes('import fu; fu.bar()') def test_usedInClass(self): self.flakes(''' import fu class bar: bar = fu ''') def test_usedInClassBase(self): self.flakes(''' import fu class bar(object, fu.baz): pass ''') def test_notUsedInNestedScope(self): self.flakes(''' import fu def bleh(): pass print(fu) ''') def test_usedInFor(self): self.flakes(''' import fu for bar in range(9): print(fu) ''') def test_usedInForElse(self): self.flakes(''' import fu for bar in range(10): pass else: print(fu) ''') def test_redefinedByFor(self): self.flakes(''' import fu for fu in range(2): pass ''', m.ImportShadowedByLoopVar) def test_shadowedByFor(self): """ Test that shadowing a global name with a for loop variable generates a warning. """ self.flakes(''' import fu fu.bar() for fu in (): pass ''', m.ImportShadowedByLoopVar) def test_shadowedByForDeep(self): """ Test that shadowing a global name with a for loop variable nested in a tuple unpack generates a warning. """ self.flakes(''' import fu fu.bar() for (x, y, z, (a, b, c, (fu,))) in (): pass ''', m.ImportShadowedByLoopVar) # Same with a list instead of a tuple self.flakes(''' import fu fu.bar() for [x, y, z, (a, b, c, (fu,))] in (): pass ''', m.ImportShadowedByLoopVar) def test_usedInReturn(self): self.flakes(''' import fu def fun(): return fu ''') def test_usedInOperators(self): self.flakes('import fu; 3 + fu.bar') self.flakes('import fu; 3 % fu.bar') self.flakes('import fu; 3 - fu.bar') self.flakes('import fu; 3 * fu.bar') self.flakes('import fu; 3 ** fu.bar') self.flakes('import fu; 3 / fu.bar') self.flakes('import fu; 3 // fu.bar') self.flakes('import fu; -fu.bar') self.flakes('import fu; ~fu.bar') self.flakes('import fu; 1 == fu.bar') self.flakes('import fu; 1 | fu.bar') self.flakes('import fu; 1 & fu.bar') self.flakes('import fu; 1 ^ fu.bar') self.flakes('import fu; 1 >> fu.bar') self.flakes('import fu; 1 << fu.bar') def test_usedInAssert(self): self.flakes('import fu; assert fu.bar') def test_usedInSubscript(self): self.flakes('import fu; fu.bar[1]') def test_usedInLogic(self): self.flakes('import fu; fu and False') self.flakes('import fu; fu or False') self.flakes('import fu; not fu.bar') def test_usedInList(self): self.flakes('import fu; [fu]') def test_usedInTuple(self): self.flakes('import fu; (fu,)') def test_usedInTry(self): self.flakes(''' import fu try: fu except: pass ''') def test_usedInExcept(self): self.flakes(''' import fu try: fu except: pass ''') def test_redefinedByExcept(self): as_exc = ', ' if version_info < (2, 6) else ' as ' self.flakes(''' import fu try: pass except Exception%sfu: pass ''' % as_exc, m.RedefinedWhileUnused) def test_usedInRaise(self): self.flakes(''' import fu raise fu.bar ''') def test_usedInYield(self): self.flakes(''' import fu def gen(): yield fu ''') def test_usedInDict(self): self.flakes('import fu; {fu:None}') self.flakes('import fu; {1:fu}') def test_usedInParameterDefault(self): self.flakes(''' import fu def f(bar=fu): pass ''') def test_usedInAttributeAssign(self): self.flakes('import fu; fu.bar = 1') def test_usedInKeywordArg(self): self.flakes('import fu; fu.bar(stuff=fu)') def test_usedInAssignment(self): self.flakes('import fu; bar=fu') self.flakes('import fu; n=0; n+=fu') def test_usedInListComp(self): self.flakes('import fu; [fu for _ in range(1)]') self.flakes('import fu; [1 for _ in range(1) if fu]') @skipIf(version_info >= (3,), 'in Python 3 list comprehensions execute in a separate scope') def test_redefinedByListComp(self): self.flakes('import fu; [1 for fu in range(1)]', m.RedefinedInListComp) def test_usedInTryFinally(self): self.flakes(''' import fu try: pass finally: fu ''') self.flakes(''' import fu try: fu finally: pass ''') def test_usedInWhile(self): self.flakes(''' import fu while 0: fu ''') self.flakes(''' import fu while fu: pass ''') def test_usedInGlobal(self): """ A 'global' statement shadowing an unused import should not prevent it from being reported. """ self.flakes(''' import fu def f(): global fu ''', m.UnusedImport) def test_usedAndGlobal(self): """ A 'global' statement shadowing a used import should not cause it to be reported as unused. """ self.flakes(''' import foo def f(): global foo def g(): foo.is_used() ''') def test_assignedToGlobal(self): """ Binding an import to a declared global should not cause it to be reported as unused. """ self.flakes(''' def f(): global foo; import foo def g(): foo.is_used() ''') @skipIf(version_info >= (3,), 'deprecated syntax') def test_usedInBackquote(self): self.flakes('import fu; `fu`') def test_usedInExec(self): if version_info < (3,): exec_stmt = 'exec "print 1" in fu.bar' else: exec_stmt = 'exec("print(1)", fu.bar)' self.flakes('import fu; %s' % exec_stmt) def test_usedInLambda(self): self.flakes('import fu; lambda: fu') def test_shadowedByLambda(self): self.flakes('import fu; lambda fu: fu', m.UnusedImport, m.RedefinedWhileUnused) self.flakes('import fu; lambda fu: fu\nfu()') def test_usedInSliceObj(self): self.flakes('import fu; "meow"[::fu]') def test_unusedInNestedScope(self): self.flakes(''' def bar(): import fu fu ''', m.UnusedImport, m.UndefinedName) def test_methodsDontUseClassScope(self): self.flakes(''' class bar: import fu def fun(self): fu ''', m.UndefinedName) def test_nestedFunctionsNestScope(self): self.flakes(''' def a(): def b(): fu import fu ''') def test_nestedClassAndFunctionScope(self): self.flakes(''' def a(): import fu class b: def c(self): print(fu) ''') def test_importStar(self): """Use of import * at module level is reported.""" self.flakes('from fu import *', m.ImportStarUsed, m.UnusedImport) self.flakes(''' try: from fu import * except: pass ''', m.ImportStarUsed, m.UnusedImport) @skipIf(version_info < (3,), 'import * below module level is a warning on Python 2') def test_localImportStar(self): """import * is only allowed at module level.""" self.flakes(''' def a(): from fu import * ''', m.ImportStarNotPermitted) self.flakes(''' class a: from fu import * ''', m.ImportStarNotPermitted) @skipIf(version_info > (3,), 'import * below module level is an error on Python 3') def test_importStarNested(self): """All star imports are marked as used by an undefined variable.""" self.flakes(''' from fu import * def f(): from bar import * x ''', m.ImportStarUsed, m.ImportStarUsed, m.ImportStarUsage) def test_packageImport(self): """ If a dotted name is imported and used, no warning is reported. """ self.flakes(''' import fu.bar fu.bar ''') def test_unusedPackageImport(self): """ If a dotted name is imported and not used, an unused import warning is reported. """ self.flakes('import fu.bar', m.UnusedImport) def test_duplicateSubmoduleImport(self): """ If a submodule of a package is imported twice, an unused import warning and a redefined while unused warning are reported. """ self.flakes(''' import fu.bar, fu.bar fu.bar ''', m.RedefinedWhileUnused) self.flakes(''' import fu.bar import fu.bar fu.bar ''', m.RedefinedWhileUnused) def test_differentSubmoduleImport(self): """ If two different submodules of a package are imported, no duplicate import warning is reported for the package. """ self.flakes(''' import fu.bar, fu.baz fu.bar, fu.baz ''') self.flakes(''' import fu.bar import fu.baz fu.bar, fu.baz ''') def test_used_package_with_submodule_import(self): """ Usage of package marks submodule imports as used. """ self.flakes(''' import fu import fu.bar fu.x ''') self.flakes(''' import fu.bar import fu fu.x ''') def test_unused_package_with_submodule_import(self): """ When a package and its submodule are imported, only report once. """ checker = self.flakes(''' import fu import fu.bar ''', m.UnusedImport) error = checker.messages[0] assert error.message == '%r imported but unused' assert error.message_args == ('fu.bar', ) assert error.lineno == 5 if self.withDoctest else 3 def test_assignRHSFirst(self): self.flakes('import fu; fu = fu') self.flakes('import fu; fu, bar = fu') self.flakes('import fu; [fu, bar] = fu') self.flakes('import fu; fu += fu') def test_tryingMultipleImports(self): self.flakes(''' try: import fu except ImportError: import bar as fu fu ''') def test_nonGlobalDoesNotRedefine(self): self.flakes(''' import fu def a(): fu = 3 return fu fu ''') def test_functionsRunLater(self): self.flakes(''' def a(): fu import fu ''') def test_functionNamesAreBoundNow(self): self.flakes(''' import fu def fu(): fu fu ''', m.RedefinedWhileUnused) def test_ignoreNonImportRedefinitions(self): self.flakes('a = 1; a = 2') @skip("todo") def test_importingForImportError(self): self.flakes(''' try: import fu except ImportError: pass ''') def test_importedInClass(self): """Imports in class scope can be used through self.""" self.flakes(''' class c: import i def __init__(self): self.i ''') def test_importUsedInMethodDefinition(self): """ Method named 'foo' with default args referring to module named 'foo'. """ self.flakes(''' import foo class Thing(object): def foo(self, parser=foo.parse_foo): pass ''') def test_futureImport(self): """__future__ is special.""" self.flakes('from __future__ import division') self.flakes(''' "docstring is allowed before future import" from __future__ import division ''') def test_futureImportFirst(self): """ __future__ imports must come before anything else. """ self.flakes(''' x = 5 from __future__ import division ''', m.LateFutureImport) self.flakes(''' from foo import bar from __future__ import division bar ''', m.LateFutureImport) def test_futureImportUsed(self): """__future__ is special, but names are injected in the namespace.""" self.flakes(''' from __future__ import division from __future__ import print_function assert print_function is not division ''') def test_futureImportUndefined(self): """Importing undefined names from __future__ fails.""" self.flakes(''' from __future__ import print_statement ''', m.FutureFeatureNotDefined) def test_futureImportStar(self): """Importing '*' from __future__ fails.""" self.flakes(''' from __future__ import * ''', m.FutureFeatureNotDefined) class TestSpecialAll(TestCase): """ Tests for suppression of unused import warnings by C{__all__}. """ def test_ignoredInFunction(self): """ An C{__all__} definition does not suppress unused import warnings in a function scope. """ self.flakes(''' def foo(): import bar __all__ = ["bar"] ''', m.UnusedImport, m.UnusedVariable) def test_ignoredInClass(self): """ An C{__all__} definition in a class does not suppress unused import warnings. """ self.flakes(''' import bar class foo: __all__ = ["bar"] ''', m.UnusedImport) def test_warningSuppressed(self): """ If a name is imported and unused but is named in C{__all__}, no warning is reported. """ self.flakes(''' import foo __all__ = ["foo"] ''') self.flakes(''' import foo __all__ = ("foo",) ''') def test_augmentedAssignment(self): """ The C{__all__} variable is defined incrementally. """ self.flakes(''' import a import c __all__ = ['a'] __all__ += ['b'] if 1 < 3: __all__ += ['c', 'd'] ''', m.UndefinedExport, m.UndefinedExport) def test_unrecognizable(self): """ If C{__all__} is defined in a way that can't be recognized statically, it is ignored. """ self.flakes(''' import foo __all__ = ["f" + "oo"] ''', m.UnusedImport) self.flakes(''' import foo __all__ = [] + ["foo"] ''', m.UnusedImport) def test_unboundExported(self): """ If C{__all__} includes a name which is not bound, a warning is emitted. """ self.flakes(''' __all__ = ["foo"] ''', m.UndefinedExport) # Skip this in __init__.py though, since the rules there are a little # different. for filename in ["foo/__init__.py", "__init__.py"]: self.flakes(''' __all__ = ["foo"] ''', filename=filename) def test_importStarExported(self): """ Do not report undefined if import * is used """ self.flakes(''' from foolib import * __all__ = ["foo"] ''', m.ImportStarUsed) def test_importStarNotExported(self): """Report unused import when not needed to satisfy __all__.""" self.flakes(''' from foolib import * a = 1 __all__ = ['a'] ''', m.ImportStarUsed, m.UnusedImport) def test_usedInGenExp(self): """ Using a global in a generator expression results in no warnings. """ self.flakes('import fu; (fu for _ in range(1))') self.flakes('import fu; (1 for _ in range(1) if fu)') def test_redefinedByGenExp(self): """ Re-using a global name as the loop variable for a generator expression results in a redefinition warning. """ self.flakes('import fu; (1 for fu in range(1))', m.RedefinedWhileUnused, m.UnusedImport) def test_usedAsDecorator(self): """ Using a global name in a decorator statement results in no warnings, but using an undefined name in a decorator statement results in an undefined name warning. """ self.flakes(''' from interior import decorate @decorate def f(): return "hello" ''') self.flakes(''' from interior import decorate @decorate('value') def f(): return "hello" ''') self.flakes(''' @decorate def f(): return "hello" ''', m.UndefinedName) class Python26Tests(TestCase): """ Tests for checking of syntax which is valid in PYthon 2.6 and newer. """ @skipIf(version_info < (2, 6), "Python >= 2.6 only") def test_usedAsClassDecorator(self): """ Using an imported name as a class decorator results in no warnings, but using an undefined name as a class decorator results in an undefined name warning. """ self.flakes(''' from interior import decorate @decorate class foo: pass ''') self.flakes(''' from interior import decorate @decorate("foo") class bar: pass ''') self.flakes(''' @decorate class foo: pass ''', m.UndefinedName) PKhUHbj~pyflakes/test/__init__.pyc ~!Tc@sdS(N((((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/__init__.pytsPKHj \\%pyflakes/test/test_undefined_names.py from _ast import PyCF_ONLY_AST from sys import version_info from pyflakes import messages as m, checker from pyflakes.test.harness import TestCase, skipIf, skip class Test(TestCase): def test_undefined(self): self.flakes('bar', m.UndefinedName) def test_definedInListComp(self): self.flakes('[a for a in range(10) if a]') @skipIf(version_info < (3,), 'in Python 2 list comprehensions execute in the same scope') def test_undefinedInListComp(self): self.flakes(''' [a for a in range(10)] a ''', m.UndefinedName) @skipIf(version_info < (3,), 'in Python 2 exception names stay bound after the except: block') def test_undefinedExceptionName(self): """Exception names can't be used after the except: block.""" self.flakes(''' try: raise ValueError('ve') except ValueError as exc: pass exc ''', m.UndefinedName) def test_namesDeclaredInExceptBlocks(self): """Locals declared in except: blocks can be used after the block. This shows the example in test_undefinedExceptionName is different.""" self.flakes(''' try: raise ValueError('ve') except ValueError as exc: e = exc e ''') @skip('error reporting disabled due to false positives below') def test_undefinedExceptionNameObscuringLocalVariable(self): """Exception names obscure locals, can't be used after. Last line will raise UnboundLocalError on Python 3 after exiting the except: block. Note next two examples for false positives to watch out for.""" self.flakes(''' exc = 'Original value' try: raise ValueError('ve') except ValueError as exc: pass exc ''', m.UndefinedName) @skipIf(version_info < (3,), 'in Python 2 exception names stay bound after the except: block') def test_undefinedExceptionNameObscuringLocalVariable2(self): """Exception names are unbound after the `except:` block. Last line will raise UnboundLocalError on Python 3 but would print out 've' on Python 2.""" self.flakes(''' try: raise ValueError('ve') except ValueError as exc: pass print(exc) exc = 'Original value' ''', m.UndefinedName) def test_undefinedExceptionNameObscuringLocalVariableFalsePositive1(self): """Exception names obscure locals, can't be used after. Unless. Last line will never raise UnboundLocalError because it's only entered if no exception was raised.""" self.flakes(''' exc = 'Original value' try: raise ValueError('ve') except ValueError as exc: print('exception logged') raise exc ''') def test_delExceptionInExcept(self): """The exception name can be deleted in the except: block.""" self.flakes(''' try: pass except Exception as exc: del exc ''') def test_undefinedExceptionNameObscuringLocalVariableFalsePositive2(self): """Exception names obscure locals, can't be used after. Unless. Last line will never raise UnboundLocalError because `error` is only falsy if the `except:` block has not been entered.""" self.flakes(''' exc = 'Original value' error = None try: raise ValueError('ve') except ValueError as exc: error = 'exception logged' if error: print(error) else: exc ''') @skip('error reporting disabled due to false positives below') def test_undefinedExceptionNameObscuringGlobalVariable(self): """Exception names obscure globals, can't be used after. Last line will raise UnboundLocalError on both Python 2 and Python 3 because the existence of that exception name creates a local scope placeholder for it, obscuring any globals, etc.""" self.flakes(''' exc = 'Original value' def func(): try: pass # nothing is raised except ValueError as exc: pass # block never entered, exc stays unbound exc ''', m.UndefinedLocal) @skip('error reporting disabled due to false positives below') def test_undefinedExceptionNameObscuringGlobalVariable2(self): """Exception names obscure globals, can't be used after. Last line will raise NameError on Python 3 because the name is locally unbound after the `except:` block, even if it's nonlocal. We should issue an error in this case because code only working correctly if an exception isn't raised, is invalid. Unless it's explicitly silenced, see false positives below.""" self.flakes(''' exc = 'Original value' def func(): global exc try: raise ValueError('ve') except ValueError as exc: pass # block never entered, exc stays unbound exc ''', m.UndefinedLocal) def test_undefinedExceptionNameObscuringGlobalVariableFalsePositive1(self): """Exception names obscure globals, can't be used after. Unless. Last line will never raise NameError because it's only entered if no exception was raised.""" self.flakes(''' exc = 'Original value' def func(): global exc try: raise ValueError('ve') except ValueError as exc: print('exception logged') raise exc ''') def test_undefinedExceptionNameObscuringGlobalVariableFalsePositive2(self): """Exception names obscure globals, can't be used after. Unless. Last line will never raise NameError because `error` is only falsy if the `except:` block has not been entered.""" self.flakes(''' exc = 'Original value' def func(): global exc error = None try: raise ValueError('ve') except ValueError as exc: error = 'exception logged' if error: print(error) else: exc ''') def test_functionsNeedGlobalScope(self): self.flakes(''' class a: def b(): fu fu = 1 ''') def test_builtins(self): self.flakes('range(10)') def test_builtinWindowsError(self): """ C{WindowsError} is sometimes a builtin name, so no warning is emitted for using it. """ self.flakes('WindowsError') def test_magicGlobalsFile(self): """ Use of the C{__file__} magic global should not emit an undefined name warning. """ self.flakes('__file__') def test_magicGlobalsBuiltins(self): """ Use of the C{__builtins__} magic global should not emit an undefined name warning. """ self.flakes('__builtins__') def test_magicGlobalsName(self): """ Use of the C{__name__} magic global should not emit an undefined name warning. """ self.flakes('__name__') def test_magicGlobalsPath(self): """ Use of the C{__path__} magic global should not emit an undefined name warning, if you refer to it from a file called __init__.py. """ self.flakes('__path__', m.UndefinedName) self.flakes('__path__', filename='package/__init__.py') def test_globalImportStar(self): """Can't find undefined names with import *.""" self.flakes('from fu import *; bar', m.ImportStarUsed, m.ImportStarUsage) @skipIf(version_info >= (3,), 'obsolete syntax') def test_localImportStar(self): """ A local import * still allows undefined names to be found in upper scopes. """ self.flakes(''' def a(): from fu import * bar ''', m.ImportStarUsed, m.UndefinedName, m.UnusedImport) @skipIf(version_info >= (3,), 'obsolete syntax') def test_unpackedParameter(self): """Unpacked function parameters create bindings.""" self.flakes(''' def a((bar, baz)): bar; baz ''') def test_definedByGlobal(self): """ "global" can make an otherwise undefined name in another function defined. """ self.flakes(''' def a(): global fu; fu = 1 def b(): fu ''') self.flakes(''' def c(): bar def b(): global bar; bar = 1 ''') def test_definedByGlobalMultipleNames(self): """ "global" can accept multiple names. """ self.flakes(''' def a(): global fu, bar; fu = 1; bar = 2 def b(): fu; bar ''') def test_globalInGlobalScope(self): """ A global statement in the global scope is ignored. """ self.flakes(''' global x def foo(): print(x) ''', m.UndefinedName) def test_global_reset_name_only(self): """A global statement does not prevent other names being undefined.""" # Only different undefined names are reported. # See following test that fails where the same name is used. self.flakes(''' def f1(): s def f2(): global m ''', m.UndefinedName) @skip("todo") def test_unused_global(self): """An unused global statement does not define the name.""" self.flakes(''' def f1(): m def f2(): global m ''', m.UndefinedName) def test_del(self): """Del deletes bindings.""" self.flakes('a = 1; del a; a', m.UndefinedName) def test_delGlobal(self): """Del a global binding from a function.""" self.flakes(''' a = 1 def f(): global a del a a ''') def test_delUndefined(self): """Del an undefined name.""" self.flakes('del a', m.UndefinedName) def test_delConditional(self): """ Ignores conditional bindings deletion. """ self.flakes(''' context = None test = True if False: del(test) assert(test) ''') def test_delConditionalNested(self): """ Ignored conditional bindings deletion even if they are nested in other blocks. """ self.flakes(''' context = None test = True if False: with context(): del(test) assert(test) ''') def test_delWhile(self): """ Ignore bindings deletion if called inside the body of a while statement. """ self.flakes(''' def test(): foo = 'bar' while False: del foo assert(foo) ''') def test_delWhileTestUsage(self): """ Ignore bindings deletion if called inside the body of a while statement and name is used inside while's test part. """ self.flakes(''' def _worker(): o = True while o is not True: del o o = False ''') def test_delWhileNested(self): """ Ignore bindings deletions if node is part of while's test, even when del is in a nested block. """ self.flakes(''' context = None def _worker(): o = True while o is not True: while True: with context(): del o o = False ''') def test_globalFromNestedScope(self): """Global names are available from nested scopes.""" self.flakes(''' a = 1 def b(): def c(): a ''') def test_laterRedefinedGlobalFromNestedScope(self): """ Test that referencing a local name that shadows a global, before it is defined, generates a warning. """ self.flakes(''' a = 1 def fun(): a a = 2 return a ''', m.UndefinedLocal) def test_laterRedefinedGlobalFromNestedScope2(self): """ Test that referencing a local name in a nested scope that shadows a global declared in an enclosing scope, before it is defined, generates a warning. """ self.flakes(''' a = 1 def fun(): global a def fun2(): a a = 2 return a ''', m.UndefinedLocal) def test_intermediateClassScopeIgnored(self): """ If a name defined in an enclosing scope is shadowed by a local variable and the name is used locally before it is bound, an unbound local warning is emitted, even if there is a class scope between the enclosing scope and the local scope. """ self.flakes(''' def f(): x = 1 class g: def h(self): a = x x = None print(x, a) print(x) ''', m.UndefinedLocal) def test_doubleNestingReportsClosestName(self): """ Test that referencing a local name in a nested scope that shadows a variable declared in two different outer scopes before it is defined in the innermost scope generates an UnboundLocal warning which refers to the nearest shadowed name. """ exc = self.flakes(''' def a(): x = 1 def b(): x = 2 # line 5 def c(): x x = 3 return x return x return x ''', m.UndefinedLocal).messages[0] # _DoctestMixin.flakes adds two lines preceding the code above. expected_line_num = 7 if self.withDoctest else 5 self.assertEqual(exc.message_args, ('x', expected_line_num)) def test_laterRedefinedGlobalFromNestedScope3(self): """ Test that referencing a local name in a nested scope that shadows a global, before it is defined, generates a warning. """ self.flakes(''' def fun(): a = 1 def fun2(): a a = 1 return a return a ''', m.UndefinedLocal) def test_undefinedAugmentedAssignment(self): self.flakes( ''' def f(seq): a = 0 seq[a] += 1 seq[b] /= 2 c[0] *= 2 a -= 3 d += 4 e[any] = 5 ''', m.UndefinedName, # b m.UndefinedName, # c m.UndefinedName, m.UnusedVariable, # d m.UndefinedName, # e ) def test_nestedClass(self): """Nested classes can access enclosing scope.""" self.flakes(''' def f(foo): class C: bar = foo def f(self): return foo return C() f(123).f() ''') def test_badNestedClass(self): """Free variables in nested classes must bind at class creation.""" self.flakes(''' def f(): class C: bar = foo foo = 456 return foo f() ''', m.UndefinedName) def test_definedAsStarArgs(self): """Star and double-star arg names are defined.""" self.flakes(''' def f(a, *b, **c): print(a, b, c) ''') @skipIf(version_info < (3,), 'new in Python 3') def test_definedAsStarUnpack(self): """Star names in unpack are defined.""" self.flakes(''' a, *b = range(10) print(a, b) ''') self.flakes(''' *a, b = range(10) print(a, b) ''') self.flakes(''' a, *b, c = range(10) print(a, b, c) ''') @skipIf(version_info < (3,), 'new in Python 3') def test_usedAsStarUnpack(self): """ Star names in unpack are used if RHS is not a tuple/list literal. """ self.flakes(''' def f(): a, *b = range(10) ''') self.flakes(''' def f(): (*a, b) = range(10) ''') self.flakes(''' def f(): [a, *b, c] = range(10) ''') @skipIf(version_info < (3,), 'new in Python 3') def test_unusedAsStarUnpack(self): """ Star names in unpack are unused if RHS is a tuple/list literal. """ self.flakes(''' def f(): a, *b = any, all, 4, 2, 'un' ''', m.UnusedVariable, m.UnusedVariable) self.flakes(''' def f(): (*a, b) = [bool, int, float, complex] ''', m.UnusedVariable, m.UnusedVariable) self.flakes(''' def f(): [a, *b, c] = 9, 8, 7, 6, 5, 4 ''', m.UnusedVariable, m.UnusedVariable, m.UnusedVariable) @skipIf(version_info < (3,), 'new in Python 3') def test_keywordOnlyArgs(self): """Keyword-only arg names are defined.""" self.flakes(''' def f(*, a, b=None): print(a, b) ''') self.flakes(''' import default_b def f(*, a, b=default_b): print(a, b) ''') @skipIf(version_info < (3,), 'new in Python 3') def test_keywordOnlyArgsUndefined(self): """Typo in kwonly name.""" self.flakes(''' def f(*, a, b=default_c): print(a, b) ''', m.UndefinedName) @skipIf(version_info < (3,), 'new in Python 3') def test_annotationUndefined(self): """Undefined annotations.""" self.flakes(''' from abc import note1, note2, note3, note4, note5 def func(a: note1, *args: note2, b: note3=12, **kw: note4) -> note5: pass ''') self.flakes(''' def func(): d = e = 42 def func(a: {1, d}) -> (lambda c: e): pass ''') @skipIf(version_info < (3,), 'new in Python 3') def test_metaClassUndefined(self): self.flakes(''' from abc import ABCMeta class A(metaclass=ABCMeta): pass ''') def test_definedInGenExp(self): """ Using the loop variable of a generator expression results in no warnings. """ self.flakes('(a for a in [1, 2, 3] if a)') self.flakes('(b for b in (a for a in [1, 2, 3] if a) if b)') def test_undefinedInGenExpNested(self): """ The loop variables of generator expressions nested together are not defined in the other generator. """ self.flakes('(b for b in (a for a in [1, 2, 3] if b) if b)', m.UndefinedName) self.flakes('(b for b in (a for a in [1, 2, 3] if a) if a)', m.UndefinedName) def test_undefinedWithErrorHandler(self): """ Some compatibility code checks explicitly for NameError. It should not trigger warnings. """ self.flakes(''' try: socket_map except NameError: socket_map = {} ''') self.flakes(''' try: _memoryview.contiguous except (NameError, AttributeError): raise RuntimeError("Python >= 3.3 is required") ''') # If NameError is not explicitly handled, generate a warning self.flakes(''' try: socket_map except: socket_map = {} ''', m.UndefinedName) self.flakes(''' try: socket_map except Exception: socket_map = {} ''', m.UndefinedName) def test_definedInClass(self): """ Defined name for generator expressions and dict/set comprehension. """ self.flakes(''' class A: T = range(10) Z = (x for x in T) L = [x for x in T] B = dict((i, str(i)) for i in T) ''') if version_info >= (2, 7): self.flakes(''' class A: T = range(10) X = {x for x in T} Y = {x:x for x in T} ''') def test_definedInClassNested(self): """Defined name for nested generator expressions in a class.""" self.flakes(''' class A: T = range(10) Z = (x for x in (a for a in T)) ''') def test_undefinedInLoop(self): """ The loop variable is defined after the expression is computed. """ self.flakes(''' for i in range(i): print(i) ''', m.UndefinedName) self.flakes(''' [42 for i in range(i)] ''', m.UndefinedName) self.flakes(''' (42 for i in range(i)) ''', m.UndefinedName) @skipIf(version_info < (2, 7), 'Dictionary comprehensions do not exist') def test_definedFromLambdaInDictionaryComprehension(self): """ Defined name referenced from a lambda function within a dict/set comprehension. """ self.flakes(''' {lambda: id(x) for x in range(10)} ''') def test_definedFromLambdaInGenerator(self): """ Defined name referenced from a lambda function within a generator expression. """ self.flakes(''' any(lambda: id(x) for x in range(10)) ''') @skipIf(version_info < (2, 7), 'Dictionary comprehensions do not exist') def test_undefinedFromLambdaInDictionaryComprehension(self): """ Undefined name referenced from a lambda function within a dict/set comprehension. """ self.flakes(''' {lambda: id(y) for x in range(10)} ''', m.UndefinedName) def test_undefinedFromLambdaInComprehension(self): """ Undefined name referenced from a lambda function within a generator expression. """ self.flakes(''' any(lambda: id(y) for x in range(10)) ''', m.UndefinedName) class NameTests(TestCase): """ Tests for some extra cases of name handling. """ def test_impossibleContext(self): """ A Name node with an unrecognized context results in a RuntimeError being raised. """ tree = compile("x = 10", "", "exec", PyCF_ONLY_AST) # Make it into something unrecognizable. tree.body[0].targets[0].ctx = object() self.assertRaises(RuntimeError, checker.Checker, tree) PKoH7LULUpyflakes/test/test_api.py""" Tests for L{pyflakes.scripts.pyflakes}. """ import os import sys import shutil import subprocess import tempfile from pyflakes.messages import UnusedImport from pyflakes.reporter import Reporter from pyflakes.api import ( main, checkPath, checkRecursive, iterSourceCode, ) from pyflakes.test.harness import TestCase, skipIf if sys.version_info < (3,): from cStringIO import StringIO else: from io import StringIO unichr = chr try: sys.pypy_version_info PYPY = True except AttributeError: PYPY = False ERROR_HAS_COL_NUM = ERROR_HAS_LAST_LINE = sys.version_info >= (3, 2) or PYPY def withStderrTo(stderr, f, *args, **kwargs): """ Call C{f} with C{sys.stderr} redirected to C{stderr}. """ (outer, sys.stderr) = (sys.stderr, stderr) try: return f(*args, **kwargs) finally: sys.stderr = outer class Node(object): """ Mock an AST node. """ def __init__(self, lineno, col_offset=0): self.lineno = lineno self.col_offset = col_offset class SysStreamCapturing(object): """Replaces sys.stdin, sys.stdout and sys.stderr with StringIO objects.""" def __init__(self, stdin): self._stdin = StringIO(stdin or '') def __enter__(self): self._orig_stdin = sys.stdin self._orig_stdout = sys.stdout self._orig_stderr = sys.stderr sys.stdin = self._stdin sys.stdout = self._stdout_stringio = StringIO() sys.stderr = self._stderr_stringio = StringIO() return self def __exit__(self, *args): self.output = self._stdout_stringio.getvalue() self.error = self._stderr_stringio.getvalue() sys.stdin = self._orig_stdin sys.stdout = self._orig_stdout sys.stderr = self._orig_stderr class LoggingReporter(object): """ Implementation of Reporter that just appends any error to a list. """ def __init__(self, log): """ Construct a C{LoggingReporter}. @param log: A list to append log messages to. """ self.log = log def flake(self, message): self.log.append(('flake', str(message))) def unexpectedError(self, filename, message): self.log.append(('unexpectedError', filename, message)) def syntaxError(self, filename, msg, lineno, offset, line): self.log.append(('syntaxError', filename, msg, lineno, offset, line)) class TestIterSourceCode(TestCase): """ Tests for L{iterSourceCode}. """ def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tempdir) def makeEmptyFile(self, *parts): assert parts fpath = os.path.join(self.tempdir, *parts) fd = open(fpath, 'a') fd.close() return fpath def test_emptyDirectory(self): """ There are no Python files in an empty directory. """ self.assertEqual(list(iterSourceCode([self.tempdir])), []) def test_singleFile(self): """ If the directory contains one Python file, C{iterSourceCode} will find it. """ childpath = self.makeEmptyFile('foo.py') self.assertEqual(list(iterSourceCode([self.tempdir])), [childpath]) def test_onlyPythonSource(self): """ Files that are not Python source files are not included. """ self.makeEmptyFile('foo.pyc') self.assertEqual(list(iterSourceCode([self.tempdir])), []) def test_recurses(self): """ If the Python files are hidden deep down in child directories, we will find them. """ os.mkdir(os.path.join(self.tempdir, 'foo')) apath = self.makeEmptyFile('foo', 'a.py') os.mkdir(os.path.join(self.tempdir, 'bar')) bpath = self.makeEmptyFile('bar', 'b.py') cpath = self.makeEmptyFile('c.py') self.assertEqual( sorted(iterSourceCode([self.tempdir])), sorted([apath, bpath, cpath])) def test_multipleDirectories(self): """ L{iterSourceCode} can be given multiple directories. It will recurse into each of them. """ foopath = os.path.join(self.tempdir, 'foo') barpath = os.path.join(self.tempdir, 'bar') os.mkdir(foopath) apath = self.makeEmptyFile('foo', 'a.py') os.mkdir(barpath) bpath = self.makeEmptyFile('bar', 'b.py') self.assertEqual( sorted(iterSourceCode([foopath, barpath])), sorted([apath, bpath])) def test_explicitFiles(self): """ If one of the paths given to L{iterSourceCode} is not a directory but a file, it will include that in its output. """ epath = self.makeEmptyFile('e.py') self.assertEqual(list(iterSourceCode([epath])), [epath]) class TestReporter(TestCase): """ Tests for L{Reporter}. """ def test_syntaxError(self): """ C{syntaxError} reports that there was a syntax error in the source file. It reports to the error stream and includes the filename, line number, error message, actual line of source and a caret pointing to where the error is. """ err = StringIO() reporter = Reporter(None, err) reporter.syntaxError('foo.py', 'a problem', 3, 7, 'bad line of source') self.assertEqual( ("foo.py:3:8: a problem\n" "bad line of source\n" " ^\n"), err.getvalue()) def test_syntaxErrorNoOffset(self): """ C{syntaxError} doesn't include a caret pointing to the error if C{offset} is passed as C{None}. """ err = StringIO() reporter = Reporter(None, err) reporter.syntaxError('foo.py', 'a problem', 3, None, 'bad line of source') self.assertEqual( ("foo.py:3: a problem\n" "bad line of source\n"), err.getvalue()) def test_multiLineSyntaxError(self): """ If there's a multi-line syntax error, then we only report the last line. The offset is adjusted so that it is relative to the start of the last line. """ err = StringIO() lines = [ 'bad line of source', 'more bad lines of source', ] reporter = Reporter(None, err) reporter.syntaxError('foo.py', 'a problem', 3, len(lines[0]) + 7, '\n'.join(lines)) self.assertEqual( ("foo.py:3:7: a problem\n" + lines[-1] + "\n" + " ^\n"), err.getvalue()) def test_unexpectedError(self): """ C{unexpectedError} reports an error processing a source file. """ err = StringIO() reporter = Reporter(None, err) reporter.unexpectedError('source.py', 'error message') self.assertEqual('source.py: error message\n', err.getvalue()) def test_flake(self): """ C{flake} reports a code warning from Pyflakes. It is exactly the str() of a L{pyflakes.messages.Message}. """ out = StringIO() reporter = Reporter(out, None) message = UnusedImport('foo.py', Node(42), 'bar') reporter.flake(message) self.assertEqual(out.getvalue(), "%s\n" % (message,)) class CheckTests(TestCase): """ Tests for L{check} and L{checkPath} which check a file for flakes. """ def makeTempFile(self, content): """ Make a temporary file containing C{content} and return a path to it. """ _, fpath = tempfile.mkstemp() if not hasattr(content, 'decode'): content = content.encode('ascii') fd = open(fpath, 'wb') fd.write(content) fd.close() return fpath def assertHasErrors(self, path, errorList): """ Assert that C{path} causes errors. @param path: A path to a file to check. @param errorList: A list of errors expected to be printed to stderr. """ err = StringIO() count = withStderrTo(err, checkPath, path) self.assertEqual( (count, err.getvalue()), (len(errorList), ''.join(errorList))) def getErrors(self, path): """ Get any warnings or errors reported by pyflakes for the file at C{path}. @param path: The path to a Python file on disk that pyflakes will check. @return: C{(count, log)}, where C{count} is the number of warnings or errors generated, and log is a list of those warnings, presented as structured data. See L{LoggingReporter} for more details. """ log = [] reporter = LoggingReporter(log) count = checkPath(path, reporter) return count, log def test_legacyScript(self): from pyflakes.scripts import pyflakes as script_pyflakes self.assertIs(script_pyflakes.checkPath, checkPath) def test_missingTrailingNewline(self): """ Source which doesn't end with a newline shouldn't cause any exception to be raised nor an error indicator to be returned by L{check}. """ fName = self.makeTempFile("def foo():\n\tpass\n\t") self.assertHasErrors(fName, []) def test_checkPathNonExisting(self): """ L{checkPath} handles non-existing files. """ count, errors = self.getErrors('extremo') self.assertEqual(count, 1) self.assertEqual( errors, [('unexpectedError', 'extremo', 'No such file or directory')]) def test_multilineSyntaxError(self): """ Source which includes a syntax error which results in the raised L{SyntaxError.text} containing multiple lines of source are reported with only the last line of that source. """ source = """\ def foo(): ''' def bar(): pass def baz(): '''quux''' """ # Sanity check - SyntaxError.text should be multiple lines, if it # isn't, something this test was unprepared for has happened. def evaluate(source): exec(source) try: evaluate(source) except SyntaxError: e = sys.exc_info()[1] if not PYPY: self.assertTrue(e.text.count('\n') > 1) else: self.fail() sourcePath = self.makeTempFile(source) if PYPY: message = 'EOF while scanning triple-quoted string literal' else: message = 'invalid syntax' self.assertHasErrors( sourcePath, ["""\ %s:8:11: %s '''quux''' ^ """ % (sourcePath, message)]) def test_eofSyntaxError(self): """ The error reported for source files which end prematurely causing a syntax error reflects the cause for the syntax error. """ sourcePath = self.makeTempFile("def foo(") if PYPY: result = """\ %s:1:7: parenthesis is never closed def foo( ^ """ % (sourcePath,) else: result = """\ %s:1:9: unexpected EOF while parsing def foo( ^ """ % (sourcePath,) self.assertHasErrors( sourcePath, [result]) def test_eofSyntaxErrorWithTab(self): """ The error reported for source files which end prematurely causing a syntax error reflects the cause for the syntax error. """ sourcePath = self.makeTempFile("if True:\n\tfoo =") column = 5 if PYPY else 7 last_line = '\t ^' if PYPY else '\t ^' self.assertHasErrors( sourcePath, ["""\ %s:2:%s: invalid syntax \tfoo = %s """ % (sourcePath, column, last_line)]) def test_nonDefaultFollowsDefaultSyntaxError(self): """ Source which has a non-default argument following a default argument should include the line number of the syntax error. However these exceptions do not include an offset. """ source = """\ def foo(bar=baz, bax): pass """ sourcePath = self.makeTempFile(source) last_line = ' ^\n' if ERROR_HAS_LAST_LINE else '' column = '8:' if ERROR_HAS_COL_NUM else '' self.assertHasErrors( sourcePath, ["""\ %s:1:%s non-default argument follows default argument def foo(bar=baz, bax): %s""" % (sourcePath, column, last_line)]) def test_nonKeywordAfterKeywordSyntaxError(self): """ Source which has a non-keyword argument after a keyword argument should include the line number of the syntax error. However these exceptions do not include an offset. """ source = """\ foo(bar=baz, bax) """ sourcePath = self.makeTempFile(source) last_line = ' ^\n' if ERROR_HAS_LAST_LINE else '' column = '13:' if ERROR_HAS_COL_NUM or PYPY else '' if sys.version_info >= (3, 5): message = 'positional argument follows keyword argument' else: message = 'non-keyword arg after keyword arg' self.assertHasErrors( sourcePath, ["""\ %s:1:%s %s foo(bar=baz, bax) %s""" % (sourcePath, column, message, last_line)]) def test_invalidEscape(self): """ The invalid escape syntax raises ValueError in Python 2 """ ver = sys.version_info # ValueError: invalid \x escape sourcePath = self.makeTempFile(r"foo = '\xyz'") if ver < (3,): decoding_error = "%s: problem decoding source\n" % (sourcePath,) elif PYPY: # pypy3 only decoding_error = """\ %s:1:6: %s: ('unicodeescape', b'\\\\xyz', 0, 2, 'truncated \\\\xXX escape') foo = '\\xyz' ^ """ % (sourcePath, 'UnicodeDecodeError') else: last_line = ' ^\n' if ERROR_HAS_LAST_LINE else '' # Column has been "fixed" since 3.2.4 and 3.3.1 col = 1 if ver >= (3, 3, 1) or ((3, 2, 4) <= ver < (3, 3)) else 2 decoding_error = """\ %s:1:7: (unicode error) 'unicodeescape' codec can't decode bytes \ in position 0-%d: truncated \\xXX escape foo = '\\xyz' %s""" % (sourcePath, col, last_line) self.assertHasErrors( sourcePath, [decoding_error]) @skipIf(sys.platform == 'win32', 'unsupported on Windows') def test_permissionDenied(self): """ If the source file is not readable, this is reported on standard error. """ sourcePath = self.makeTempFile('') os.chmod(sourcePath, 0) count, errors = self.getErrors(sourcePath) self.assertEqual(count, 1) self.assertEqual( errors, [('unexpectedError', sourcePath, "Permission denied")]) def test_pyflakesWarning(self): """ If the source file has a pyflakes warning, this is reported as a 'flake'. """ sourcePath = self.makeTempFile("import foo") count, errors = self.getErrors(sourcePath) self.assertEqual(count, 1) self.assertEqual( errors, [('flake', str(UnusedImport(sourcePath, Node(1), 'foo')))]) def test_encodedFileUTF8(self): """ If source file declares the correct encoding, no error is reported. """ SNOWMAN = unichr(0x2603) source = ("""\ # coding: utf-8 x = "%s" """ % SNOWMAN).encode('utf-8') sourcePath = self.makeTempFile(source) self.assertHasErrors(sourcePath, []) def test_CRLFLineEndings(self): """ Source files with Windows CR LF line endings are parsed successfully. """ sourcePath = self.makeTempFile("x = 42\r\n") self.assertHasErrors(sourcePath, []) def test_misencodedFileUTF8(self): """ If a source file contains bytes which cannot be decoded, this is reported on stderr. """ SNOWMAN = unichr(0x2603) source = ("""\ # coding: ascii x = "%s" """ % SNOWMAN).encode('utf-8') sourcePath = self.makeTempFile(source) if PYPY and sys.version_info < (3, ): message = ('\'ascii\' codec can\'t decode byte 0xe2 ' 'in position 21: ordinal not in range(128)') result = """\ %s:0:0: %s x = "\xe2\x98\x83" ^\n""" % (sourcePath, message) else: message = 'problem decoding source' result = "%s: problem decoding source\n" % (sourcePath,) self.assertHasErrors( sourcePath, [result]) def test_misencodedFileUTF16(self): """ If a source file contains bytes which cannot be decoded, this is reported on stderr. """ SNOWMAN = unichr(0x2603) source = ("""\ # coding: ascii x = "%s" """ % SNOWMAN).encode('utf-16') sourcePath = self.makeTempFile(source) self.assertHasErrors( sourcePath, ["%s: problem decoding source\n" % (sourcePath,)]) def test_checkRecursive(self): """ L{checkRecursive} descends into each directory, finding Python files and reporting problems. """ tempdir = tempfile.mkdtemp() os.mkdir(os.path.join(tempdir, 'foo')) file1 = os.path.join(tempdir, 'foo', 'bar.py') fd = open(file1, 'wb') fd.write("import baz\n".encode('ascii')) fd.close() file2 = os.path.join(tempdir, 'baz.py') fd = open(file2, 'wb') fd.write("import contraband".encode('ascii')) fd.close() log = [] reporter = LoggingReporter(log) warnings = checkRecursive([tempdir], reporter) self.assertEqual(warnings, 2) self.assertEqual( sorted(log), sorted([('flake', str(UnusedImport(file1, Node(1), 'baz'))), ('flake', str(UnusedImport(file2, Node(1), 'contraband')))])) class IntegrationTests(TestCase): """ Tests of the pyflakes script that actually spawn the script. """ def setUp(self): self.tempdir = tempfile.mkdtemp() self.tempfilepath = os.path.join(self.tempdir, 'temp') def tearDown(self): shutil.rmtree(self.tempdir) def getPyflakesBinary(self): """ Return the path to the pyflakes binary. """ import pyflakes package_dir = os.path.dirname(pyflakes.__file__) return os.path.join(package_dir, '..', 'bin', 'pyflakes') def runPyflakes(self, paths, stdin=None): """ Launch a subprocess running C{pyflakes}. @param paths: Command-line arguments to pass to pyflakes. @param stdin: Text to use as stdin. @return: C{(returncode, stdout, stderr)} of the completed pyflakes process. """ env = dict(os.environ) env['PYTHONPATH'] = os.pathsep.join(sys.path) command = [sys.executable, self.getPyflakesBinary()] command.extend(paths) if stdin: p = subprocess.Popen(command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate(stdin.encode('ascii')) else: p = subprocess.Popen(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() rv = p.wait() if sys.version_info >= (3,): stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') return (stdout, stderr, rv) def test_goodFile(self): """ When a Python source file is all good, the return code is zero and no messages are printed to either stdout or stderr. """ fd = open(self.tempfilepath, 'a') fd.close() d = self.runPyflakes([self.tempfilepath]) self.assertEqual(d, ('', '', 0)) def test_fileWithFlakes(self): """ When a Python source file has warnings, the return code is non-zero and the warnings are printed to stdout. """ fd = open(self.tempfilepath, 'wb') fd.write("import contraband\n".encode('ascii')) fd.close() d = self.runPyflakes([self.tempfilepath]) expected = UnusedImport(self.tempfilepath, Node(1), 'contraband') self.assertEqual(d, ("%s%s" % (expected, os.linesep), '', 1)) def test_errors(self): """ When pyflakes finds errors with the files it's given, (if they don't exist, say), then the return code is non-zero and the errors are printed to stderr. """ d = self.runPyflakes([self.tempfilepath]) error_msg = '%s: No such file or directory%s' % (self.tempfilepath, os.linesep) self.assertEqual(d, ('', error_msg, 1)) def test_readFromStdin(self): """ If no arguments are passed to C{pyflakes} then it reads from stdin. """ d = self.runPyflakes([], stdin='import contraband') expected = UnusedImport('', Node(1), 'contraband') self.assertEqual(d, ("%s%s" % (expected, os.linesep), '', 1)) class TestMain(IntegrationTests): """ Tests of the pyflakes main function. """ def runPyflakes(self, paths, stdin=None): try: with SysStreamCapturing(stdin) as capture: main(args=paths) except SystemExit as e: return (capture.output, capture.error, e.code) else: raise RuntimeError('SystemExit not raised') PKq7Epyflakes/test/__init__.pyPKhUHg@n mm<pyflakes/test/__pycache__/test_imports.cpython-27-PYTEST.pyc *+Wpc@sddlZddljjZddlmZddlm Z ddl m Z m Z mZmZmZddlmZmZmZdefdYZdefd YZd efd YZd efd YZdS(iN(t version_info(tmessages(tFutureImportationt ImportationtImportationFromtStarImportationtSubmoduleImportation(tTestCasetskiptskipIftTestImportationObjectcBskeZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( c Cstddd}|j}d}||k}|stjd|fd||fidtjksutj|rtj|ndd6tj|d6tj|d6}di|d 6}t tj |nd}}}t |}d}||k}|stjd|fd||fid tjksLtjt r[tjt nd d6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(Ntasimport as==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)stbindingtpy0tpy2tpy5tsassert %(py7)stpy7s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ststrtpy1tpy3tpy6sassert %(py8)stpy8(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RtNonetsource_statementt @pytest_art_call_reprcomparet @py_builtinstlocalst_should_repr_global_namet _safereprtAssertionErrort_format_explanationR( tselfR t @py_assert1t @py_assert4t @py_assert3t @py_format6t @py_format8t @py_assert2t @py_assert5t @py_format7t @py_format9((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_import_basics"  |  c Cstddd}|j}d}||k}|stjd|fd||fidtjksutj|rtj|ndd6tj|d6tj|d 6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksLtjt r[tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NtcR s import a as cs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa as cs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_import_ass"  |  c Cstdd}|j}d}||k}|stjd|fd||fidtjksrtj|rtj|ndd6tj|d6tj|d6}di|d 6}t tj |nd}}}t |}d}||k}|stjd|fd||fid tjksItjt rXtjt nd d6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(Nsa.bs import a.bs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_import_submodules"  |  c Cstddd}|j}d}||k}|stjd|fd||fidtjksutj|rtj|ndd6tj|d6tj|d 6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksLtjt r[tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NR,sa.bsimport a.b as cs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.b as cs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_import_submodule_as s"  |  c Cstddd}|j}d}||k}|stjd|fd||fidtjksutj|rtj|ndd6tj|d6tj|d 6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksLtjt r[tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NR sa.bsimport a.b as as==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.b as as0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt$test_import_submodule_as_source_name&s"  |  c Cstdddd}|j}d}||k}|stjd|fd||fidtjksxtj|rtj|ndd6tj|d6tj|d 6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksOtjt r^tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NtbR sfrom a import bs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.bs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importfrom_member+s"  |  c Cstdddd}|j}d}||k}|stjd|fd||fidtjksxtj|rtj|ndd6tj|d6tj|d 6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksOtjt r^tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NR,sa.bsfrom a.b import cs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.b.cs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt test_importfrom_submodule_member0s"  |  c Cstdddd}|j}d}||k}|stjd|fd||fidtjksxtj|rtj|ndd6tj|d 6tj|d 6}di|d 6}t tj |nd}}}t |}d}||k}|stjd|fd||fidtjksOtjt r^tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(NR,R R1sfrom a import b as cs==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.b as cs0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importfrom_member_as5s"  |  c Cstdddd}|j}d}||k}|stjd|fd||fidtjksxtj|rtj|ndd6tj|d 6tj|d 6}di|d 6}t tj |nd}}}t |}d}||k}|stjd|fd||fidtjksOtjt r^tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(Ntdsa.bR,sfrom a.b import c as ds==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRs a.b.c as ds0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt#test_importfrom_submodule_member_as:s"  |  c Cstdd}|j}d}||k}|stjd|fd||fidtjksrtj|rtj|ndd6tj|d6tj|d6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksItjt rXtjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(Nsa.bsfrom a.b import *s==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRsa.b.*s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importfrom_star?s"  |  c Cstddd}|j}d}||k}|stjd|fd||fidtjksutj|rtj|ndd6tj|d6tj|d6}di|d 6}t tj |nd}}}t |}d }||k}|stjd|fd||fidtjksLtjt r[tjt ndd6dtjkstj|rtj|ndd6tj|d6tj|d6} di| d6} t tj | nd}}}dS(Ntprint_functions%from __future__ import print_functions==s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)sR R RRRsassert %(py7)sRs__future__.print_functions0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)sRRRRsassert %(py8)sR(s==(s8%(py2)s {%(py2)s = %(py0)s.source_statement } == %(py5)ssassert %(py7)s(s==(s0%(py3)s {%(py3)s = %(py0)s(%(py1)s) } == %(py6)ssassert %(py8)s( RRRRRRRRRRR R( R!R R"R#R$R%R&R'R(R)R*((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importfrom_futureDs"  |  ( t__name__t __module__R+R-R.R/R0R2R3R4R6R7R9(((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyR s          tTestcBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0d/Z1d0Z2d1Z3d2Z4d3Z5d4Z6d5Z7d6Z8d7Z9d8Z:d9Z;d:Z<e=e>dgkd<d=Z?d>Z@d?ZAd@ZBdAZCdBZDe=e>dhkdCdDZEdEZFdFZGdGZHdHZIdIZJdJZKdKZLdLZMdMZNe=e>dikdNdOZOe=e>djkdPdQZPdRZQdSZRdTZSdUZTdVZUdWZVdXZWdYZXdZZYd[ZZd\Z[d]Z\e]d^d_Z^d`Z_daZ`dbZadcZbddZcdeZddfZeRS(kcCs6|jdtjtj|jdtjtjdS(Nsimport fu, barsfrom baz import fu, bar(tflakestmt UnusedImport(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_unusedImportLscCs6|jdtjtj|jdtjtjdS(Nsimport fu as FU, bar as FUs#from moo import fu as FU, bar as FU(R=R>tRedefinedWhileUnusedR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_aliasedImportPs  cCs+|jd|jd|jddS(s5Imported aliases can shadow the source of the import.sfrom moo import fu as moo; moosimport fu as fu; fusimport fu.bar as fu; fuN(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_aliasedImportShadowModuleVs  cCs+|jd|jd|jddS(Nsimport fu; print(fu)sfrom baz import fu; print(fu)simport fu; del fu(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedImport\s  cCs=|jdtj|jdtj|jdtjdS(Nsimport fu; fu = 3simport fu; fu, bar = 3simport fu; [fu, bar] = 3(R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedWhileUnusedascCs|jdtjdS(se Test that importing a module twice within an if block does raise a warning. s[ i = 2 if i==1: import os import os os.pathN(R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedIffscCs|jddS(sl Test that importing a module twice in if and else blocks does not raise a warning. si i = 2 if i==1: import os else: import os os.pathN(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedIfElserscCs|jdtjdS(sb Test that importing a module twice in an try block does raise a warning. sj try: import os import os except: pass os.pathN(R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryscCs|jddS(sq Test that importing a module twice in an try and except block does not raise a warning. sY try: import os except: import os os.pathN(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryExceptscCs|jddS(s~ Test that importing a module twice using a nested try/except and if blocks does not issue a warning. s try: if True: if True: import os except: import os os.pathN(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryNestedscCs|jddS(Ns try: from aa import mixer except AttributeError: from bb import mixer except RuntimeError: from cc import mixer except: from dd import mixer mixer(123) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryExceptMultis cCs|jdtjdS(Ns try: from aa import mixer except ImportError: pass else: from bb import mixer mixer(123) (R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryElsescCs|jddS(Ns try: import funca except ImportError: from bb import funca from bb import funcb else: from bbb import funcb print(funca, funcb) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryExceptElses cCs|jddS(Ns try: from aa import a except ImportError: from bb import a finally: a = 42 print(a) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedTryExceptFinallyscCs|jddS(Ns try: import b except ImportError: b = Ellipsis from bb import a else: from aa import a finally: a = 42 print(a, b) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt"test_redefinedTryExceptElseFinallys cCs|jdtjdS(Ns> import fu def fu(): pass (R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByFunctionscCs|jdtjtjdS(sr Test that shadowing a global name with a nested function definition generates a warning. sx import fu def bar(): def baz(): def fu(): pass N(R=R>RAR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedInNestedFunctionscCs)|jdtjtjtjtjdS(sr Test that shadowing a global name with a nested function definition generates a warning. s import fu def bar(): import fu def baz(): def fu(): pass N(R=R>RAR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt#test_redefinedInNestedFunctionTwices cCs|jddS(s Test that a global import which is redefined locally, but used later in another scope does not generate a warning. sq import unittest, transport class GetTransportTestCase(unittest.TestCase): def test_get_transport(self): transport = 'transport' self.assertIsNotNone(transport) class TestTransportMethodArgs(unittest.TestCase): def test_send_defaults(self): transport.Transport() N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedButUsedLaters cCs|jdtjdS(Ns> import fu class fu: pass (R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByClassscCs|jddS(s If an imported name is redefined by a class statement which also uses that name in the bases list, no warning is emitted. sM from fu import bar class bar(bar): pass N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedBySubclass scCs|jddS(si Test that shadowing a global with a class attribute does not produce a warning. sS import fu class bar: fu = 1 print(fu) N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedInClass+scCs$|jd|jdtjdS(sN Test that import within class is a locally scoped attribute. s2 class bar: import fu s> class bar: import fu fu N(R=R>t UndefinedName(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importInClass7scCs|jddS(NsD import fu def fun(): print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInFunctionGscCs*|jdtjtj|jddS(NsF import fu def fun(fu): print(fu) sX import fu def fun(fu): print(fu) print(fu) (R=R>R?RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_shadowedByParameterNscCs|jddS(Ns fu = None(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_newAssignment\scCs$|jd|jdtjdS(Nsimport fu; fu.bar.bazsimport fu; "bar".fu.baz(R=R>R?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInGetattr_s cCs|jddS(Nsimport fu; print(fu.bar[1:])(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInSlicecscCs|jddS(Ns6 import fu if True: print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInIfBodyfscCs|jddS(Ns/ import fu if fu: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInIfConditionallscCs|jddS(NsH import fu if False: pass elif fu: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInElifConditionalrscCs|jddS(NsJ import fu if False: pass else: print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInElseyscCs|jddS(Nsimport fu; fu.bar()(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInCallscCs|jddS(NsC import fu class bar: bar = fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInClassscCs|jddS(NsO import fu class bar(object, fu.baz): pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInClassBasescCs|jddS(NsR import fu def bleh(): pass print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_notUsedInNestedScopescCs|jddS(NsN import fu for bar in range(9): print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInForscCs|jddS(Nsn import fu for bar in range(10): pass else: print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInForElsescCs|jdtjdS(NsH import fu for fu in range(2): pass (R=R>tImportShadowedByLoopVar(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByForscCs|jdtjdS(si Test that shadowing a global name with a for loop variable generates a warning. sS import fu fu.bar() for fu in (): pass N(R=R>Rh(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_shadowedByForscCs*|jdtj|jdtjdS(s Test that shadowing a global name with a for loop variable nested in a tuple unpack generates a warning. sl import fu fu.bar() for (x, y, z, (a, b, c, (fu,))) in (): pass sl import fu fu.bar() for [x, y, z, (a, b, c, (fu,))] in (): pass N(R=R>Rh(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_shadowedByForDeeps cCs|jddS(NsD import fu def fun(): return fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInReturnscCs|jd|jd|jd|jd|jd|jd|jd|jd|jd |jd |jd |jd |jd |jd|jddS(Nsimport fu; 3 + fu.barsimport fu; 3 % fu.barsimport fu; 3 - fu.barsimport fu; 3 * fu.barsimport fu; 3 ** fu.barsimport fu; 3 / fu.barsimport fu; 3 // fu.barsimport fu; -fu.barsimport fu; ~fu.barsimport fu; 1 == fu.barsimport fu; 1 | fu.barsimport fu; 1 & fu.barsimport fu; 1 ^ fu.barsimport fu; 1 >> fu.barsimport fu; 1 << fu.bar(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInOperatorss              cCs|jddS(Nsimport fu; assert fu.bar(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInAssertscCs|jddS(Nsimport fu; fu.bar[1](R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInSubscriptscCs+|jd|jd|jddS(Nsimport fu; fu and Falsesimport fu; fu or Falsesimport fu; not fu.bar(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInLogics  cCs|jddS(Nsimport fu; [fu](R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInListscCs|jddS(Nsimport fu; (fu,)(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInTuplescCs|jddS(Ns@ import fu try: fu except: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInTryscCs|jddS(Ns@ import fu try: fu except: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInExceptscCs3tdkrdnd}|jd|tjdS(Niis, s as sP import fu try: pass except Exception%sfu: pass (ii(RR=R>RA(R!tas_exc((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByExceptscCs|jddS(Ns0 import fu raise fu.bar (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInRaisescCs|jddS(NsC import fu def gen(): yield fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInYieldscCs|jd|jddS(Nsimport fu; {fu:None}simport fu; {1:fu}(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInDicts cCs|jddS(NsC import fu def f(bar=fu): pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInParameterDefaultscCs|jddS(Nsimport fu; fu.bar = 1(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInAttributeAssign&scCs|jddS(Nsimport fu; fu.bar(stuff=fu)(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInKeywordArg)scCs|jd|jddS(Nsimport fu; bar=fusimport fu; n=0; n+=fu(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInAssignment,s cCs|jd|jddS(Ns!import fu; [fu for _ in range(1)]s&import fu; [1 for _ in range(1) if fu](R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInListComp0s is;in Python 3 list comprehensions execute in a separate scopecCs|jdtjdS(Ns!import fu; [1 for fu in range(1)](R=R>tRedefinedInListComp(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByListComp4s cCs|jd|jddS(NsA import fu try: pass finally: fu sA import fu try: fu finally: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInTryFinally:scCs|jd|jddS(Ns; import fu while 0: fu s2 import fu while fu: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInWhileGscCs|jdtjdS(st A 'global' statement shadowing an unused import should not prevent it from being reported. s6 import fu def f(): global fu N(R=R>R?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInGlobalSscCs|jddS(st A 'global' statement shadowing a used import should not cause it to be reported as unused. sc import foo def f(): global foo def g(): foo.is_used() N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedAndGlobal]scCs|jddS(sn Binding an import to a declared global should not cause it to be reported as unused. sX def f(): global foo; import foo def g(): foo.is_used() N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_assignedToGlobalhssdeprecated syntaxcCs|jddS(Nsimport fu; `fu`(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInBackquoterscCs0tdkrd}nd}|jd|dS(Nisexec "print 1" in fu.barsexec("print(1)", fu.bar)s import fu; %s(i(RR=(R!t exec_stmt((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInExecvs  cCs|jddS(Nsimport fu; lambda: fu(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInLambda}scCs*|jdtjtj|jddS(Nsimport fu; lambda fu: fusimport fu; lambda fu: fu fu()(R=R>R?RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_shadowedByLambdas cCs|jddS(Nsimport fu; "meow"[::fu](R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInSliceObjscCs|jdtjtjdS(Ns= def bar(): import fu fu (R=R>R?RW(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_unusedInNestedScopescCs|jdtjdS(Ns` class bar: import fu def fun(self): fu (R=R>RW(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_methodsDontUseClassScopescCs|jddS(NsX def a(): def b(): fu import fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_nestedFunctionsNestScopescCs|jddS(Ns def a(): import fu class b: def c(self): print(fu) (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt test_nestedClassAndFunctionScopescCs6|jdtjtj|jdtjtjdS(s,Use of import * at module level is reported.sfrom fu import *sT try: from fu import * except: pass N(R=R>tImportStarUsedR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importStarss4import * below module level is a warning on Python 2cCs*|jdtj|jdtjdS(s)import * is only allowed at module level.s7 def a(): from fu import * s7 class a: from fu import * N(R=R>tImportStarNotPermitted(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_localImportStars s3import * below module level is an error on Python 3cCs#|jdtjtjtjdS(s=All star imports are marked as used by an undefined variable.s_ from fu import * def f(): from bar import * x N(R=R>RtImportStarUsage(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importStarNestedscCs|jddS(sP If a dotted name is imported and used, no warning is reported. s. import fu.bar fu.bar N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_packageImportscCs|jdtjdS(sj If a dotted name is imported and not used, an unused import warning is reported. s import fu.barN(R=R>R?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_unusedPackageImportscCs*|jdtj|jdtjdS(s If a submodule of a package is imported twice, an unused import warning and a redefined while unused warning are reported. s6 import fu.bar, fu.bar fu.bar sD import fu.bar import fu.bar fu.bar N(R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_duplicateSubmoduleImports cCs|jd|jddS(s If two different submodules of a package are imported, no duplicate import warning is reported for the package. s> import fu.bar, fu.baz fu.bar, fu.baz sL import fu.bar import fu.baz fu.bar, fu.baz N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_differentSubmoduleImportscCs|jd|jddS(sC Usage of package marks submodule imports as used. s> import fu import fu.bar fu.x s> import fu.bar import fu fu.x N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt'test_used_package_with_submodule_importsc Cs*|jdtj}|jd}|j}d}||k}|stjd|fd||fidtjkstj |rtj |ndd6tj |d6tj |d 6}di|d 6}t tj |nd}}}|j}d}||k}|stjd|fd||fidtjksYtj |rhtj |ndd6tj |d6tj |d 6}di|d 6}t tj |nd}}}|jr|jdknd}|s ditj |d6} t tj | nd}dS(sR When a package and its submodule are imported, only report once. s1 import fu import fu.bar is%r imported but unuseds==s/%(py2)s {%(py2)s = %(py0)s.message } == %(py5)sterrorR RRRsassert %(py7)sRsfu.bars4%(py2)s {%(py2)s = %(py0)s.message_args } == %(py5)siisassert %(py1)sRN(s==(s/%(py2)s {%(py2)s = %(py0)s.message } == %(py5)ssassert %(py7)s(sfu.bar(s==(s4%(py2)s {%(py2)s = %(py0)s.message_args } == %(py5)ssassert %(py7)ssassert %(py1)s(R=R>R?RtmessageRRRRRRRR Rt message_argst withDoctesttlineno( R!tcheckerRR"R#R$R%R&t @py_assert0t @py_format2((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt)test_unused_package_with_submodule_imports0   |  |cCs8|jd|jd|jd|jddS(Nsimport fu; fu = fusimport fu; fu, bar = fusimport fu; [fu, bar] = fusimport fu; fu += fu(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_assignRHSFirsts   cCs|jddS(Nsp try: import fu except ImportError: import bar as fu fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_tryingMultipleImportsscCs|jddS(Ns` import fu def a(): fu = 3 return fu fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_nonGlobalDoesNotRedefine$scCs|jddS(Ns; def a(): fu import fu (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_functionsRunLater-scCs|jdtjdS(NsG import fu def fu(): fu fu (R=R>RA(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_functionNamesAreBoundNow4scCs|jddS(Ns a = 1; a = 2(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt!test_ignoreNonImportRedefinitions<sttodocCs|jddS(NsY try: import fu except ImportError: pass (R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importingForImportError?scCs|jddS(s0Imports in class scope can be used through self.sf class c: import i def __init__(self): self.i N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importedInClassHscCs|jddS(sW Method named 'foo' with default args referring to module named 'foo'. s import foo class Thing(object): def foo(self, parser=foo.parse_foo): pass N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyt!test_importUsedInMethodDefinitionQscCs|jd|jddS(s__future__ is special.sfrom __future__ import divisionse "docstring is allowed before future import" from __future__ import division N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_futureImport]s cCs*|jdtj|jdtjdS(sD __future__ imports must come before anything else. s? x = 5 from __future__ import division sY from foo import bar from __future__ import division bar N(R=R>tLateFutureImport(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_futureImportFirstes cCs|jddS(s?__future__ is special, but names are injected in the namespace.s from __future__ import division from __future__ import print_function assert print_function is not division N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_futureImportUsedsscCs|jdtjdS(s0Importing undefined names from __future__ fails.s8 from __future__ import print_statement N(R=R>tFutureFeatureNotDefined(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_futureImportUndefined|scCs|jdtjdS(s$Importing '*' from __future__ fails.s* from __future__ import * N(R=R>R(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_futureImportStars(i(i(i(i(fR:R;R@RBRCRDRERFRGRHRIRJRKRLRMRNRORPRQRRRSRTRURVRXRYRZR[R\R]R^R_R`RaRbRcRdReRfRgRiRjRkRlRmRnRoRpRqRrRsRtRvRwRxRyRzR{R|R}R~R RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR(((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyR<Js                                                                    tTestSpecialAllcBsqeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( sH Tests for suppression of unused import warnings by C{__all__}. cCs|jdtjtjdS(sp An C{__all__} definition does not suppress unused import warnings in a function scope. sQ def foo(): import bar __all__ = ["bar"] N(R=R>R?tUnusedVariable(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_ignoredInFunctionscCs|jdtjdS(s_ An C{__all__} definition in a class does not suppress unused import warnings. sM import bar class foo: __all__ = ["bar"] N(R=R>R?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_ignoredInClassscCs|jd|jddS(sn If a name is imported and unused but is named in C{__all__}, no warning is reported. s6 import foo __all__ = ["foo"] s7 import foo __all__ = ("foo",) N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_warningSuppressedscCs|jdtjtjdS(sC The C{__all__} variable is defined incrementally. s import a import c __all__ = ['a'] __all__ += ['b'] if 1 < 3: __all__ += ['c', 'd'] N(R=R>tUndefinedExport(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_augmentedAssignmentscCs*|jdtj|jdtjdS(so If C{__all__} is defined in a way that can't be recognized statically, it is ignored. s; import foo __all__ = ["f" + "oo"] s; import foo __all__ = [] + ["foo"] N(R=R>R?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_unrecognizables cCsA|jdtjx'ddgD]}|jdd|q WdS(sY If C{__all__} includes a name which is not bound, a warning is emitted. s# __all__ = ["foo"] sfoo/__init__.pys __init__.pys+ __all__ = ["foo"] tfilenameN(R=R>R(R!R((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_unboundExporteds  cCs|jdtjdS(s= Do not report undefined if import * is used s@ from foolib import * __all__ = ["foo"] N(R=R>R(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importStarExportedscCs|jdtjtjdS(s8Report unused import when not needed to satisfy __all__.sL from foolib import * a = 1 __all__ = ['a'] N(R=R>RR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_importStarNotExportedscCs|jd|jddS(sR Using a global in a generator expression results in no warnings. s!import fu; (fu for _ in range(1))s&import fu; (1 for _ in range(1) if fu)N(R=(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedInGenExps cCs|jdtjtjdS(s Re-using a global name as the loop variable for a generator expression results in a redefinition warning. s!import fu; (1 for fu in range(1))N(R=R>RAR?(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_redefinedByGenExps cCs1|jd|jd|jdtjdS(s Using a global name in a decorator statement results in no warnings, but using an undefined name in a decorator statement results in an undefined name warning. sm from interior import decorate @decorate def f(): return "hello" sv from interior import decorate @decorate('value') def f(): return "hello" sG @decorate def f(): return "hello" N(R=R>RW(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedAsDecorators (R:R;t__doc__RRRRRRRRRRR(((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyRs      t Python26TestscBs,eZdZeedkddZRS(sN Tests for checking of syntax which is valid in PYthon 2.6 and newer. iisPython >= 2.6 onlycCs1|jd|jd|jdtjdS(s Using an imported name as a class decorator results in no warnings, but using an undefined name as a class decorator results in an undefined name warning. se from interior import decorate @decorate class foo: pass sl from interior import decorate @decorate("foo") class bar: pass s? @decorate class foo: pass N(R=R>RW(R!((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyttest_usedAsClassDecorators (ii(R:R;RR RR(((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyRs(t __builtin__Rt_pytest.assertion.rewritet assertiontrewriteRtsysRtpyflakesRR>tpyflakes.checkerRRRRRtpyflakes.test.harnessRRR R R<RR(((sX/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_imports.pyts (;BPKhUH ۫:pyflakes/test/__pycache__/test_other.cpython-27-PYTEST.pyc :FV{c@sdZddlZddljjZddlmZddl m Z ddl m Z mZmZde fdYZde fd YZd e fd YZdS( s& Tests for various Pyflakes behavior. iN(t version_info(tmessages(tTestCasetskiptskipIftTestcBseZdZdZeed=kddZdZeed>kdd Zeed?kdd Z d Z d Z d Z dZ dZdZdZeed@kddZdZdZeedAkddZdZdZdZdZdZdZdZdZd Zd!Zd"ZeedBkd#d$Z eedCkd#d%Z!d&Z"d'Z#d(Z$d)Z%d*Z&d+Z'd,Z(eedDkd-d.Z)eedEkd-d/Z*e+d0d1Z,d2Z-d3Z.d4Z/d5Z0d6Z1d7Z2d8Z3d9Z4d:Z5d;Z6d<Z7RS(FcCs|jdtjdS(Nsdef fu(bar, bar): pass(tflakestmtDuplicateArgument(tself((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_duplicateArgs scCs|jdtjtjdS(NsG a = 1 def f(): a; a=1 f() (RRtUndefinedLocaltUnusedVariable(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt$test_localReferencedBeforeAssignmentsis;in Python 3 list comprehensions execute in a separate scopecCsW|jdtj|jdtj|jdtj|jd|jddS(sb Test that shadowing a variable in a list comprehension raises a warning. s8 a = 1 [1 for a, b in [(1, 2)]] sQ class A: a = 1 [1 for a, b in [(1, 2)]] sQ def f(): a = 1 [1 for a, b in [(1, 2)]] sK [1 for a, b in [(1, 2)]] [1 for a, b in [(1, 2)]] sY for a, b in [(1, 2)]: pass [1 for a, b in [(1, 2)]] N(RRtRedefinedInListComp(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedInListComps   cCsK|jd|jd|jdtj|jd|jddS(s_ Test that reusing a variable in a generator does not raise a warning. s8 a = 1 (1 for a, b in [(1, 2)]) sU class A: a = 1 list(1 for a, b in [(1, 2)]) sQ def f(): a = 1 (1 for a, b in [(1, 2)]) sK (1 for a, b in [(1, 2)]) (1 for a, b in [(1, 2)]) sY for a, b in [(1, 2)]: pass (1 for a, b in [(1, 2)]) N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedInGenerator7s iisPython >= 2.7 onlycCsK|jd|jd|jdtj|jd|jddS(sg Test that reusing a variable in a set comprehension does not raise a warning. s8 a = 1 {1 for a, b in [(1, 2)]} sQ class A: a = 1 {1 for a, b in [(1, 2)]} sQ def f(): a = 1 {1 for a, b in [(1, 2)]} sK {1 for a, b in [(1, 2)]} {1 for a, b in [(1, 2)]} sY for a, b in [(1, 2)]: pass {1 for a, b in [(1, 2)]} N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_redefinedInSetComprehensionTs cCsK|jd|jd|jdtj|jd|jddS(sh Test that reusing a variable in a dict comprehension does not raise a warning. s< a = 1 {1: 42 for a, b in [(1, 2)]} sU class A: a = 1 {1: 42 for a, b in [(1, 2)]} sU def f(): a = 1 {1: 42 for a, b in [(1, 2)]} sS {1: 42 for a, b in [(1, 2)]} {1: 42 for a, b in [(1, 2)]} s] for a, b in [(1, 2)]: pass {1: 42 for a, b in [(1, 2)]} N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt!test_redefinedInDictComprehensionrs cCs|jdtjdS(sf Test that shadowing a function definition with another one raises a warning. s5 def a(): pass def a(): pass N(RRtRedefinedWhileUnused(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedFunctionscCs|jdtjdS(sw Test that shadowing a function definition in a class suite with another one raises a warning. sN class A: def a(): pass def a(): pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedClassFunctionscCs|jddS(s{ Test that shadowing a function definition twice in an if and else block does not raise a warning. s\ if True: def a(): pass else: def a(): pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedIfElseFunctionscCs|jdtjdS(sh Test that shadowing a function definition within an if block raises a warning. sN if True: def a(): pass def a(): pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedIfFunctionscCs|jddS(s{ Test that shadowing a function definition twice in try and except block does not raise a warning. sZ try: def a(): pass except: def a(): pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedTryExceptFunctionscCs|jdtjdS(sh Test that shadowing a function definition within a try block raises a warning. sk try: def a(): pass def a(): pass except: pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedTryFunctionscCs|jddS(s Test that shadowing a variable in a list comprehension in an if and else block does not raise a warning. sY if False: a = 1 else: [a for a in '12'] N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedIfElseInListCompscCs|jdtjdS(s{ Test that shadowing a variable in a list comprehension in an else (or if) block raises a warning. sj if False: pass else: a = 1 [a for a in '12'] N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_redefinedElseInListCompscCs|jddS(s Test that shadowing a function definition with a decorated version of that function does not raise a warning. si from somewhere import somedecorator def a(): pass a = somedecorator(a) N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_functionDecoratorscCs|jddS(s Test that shadowing a function definition in a class suite with a decorated version of that function does not raise a warning. sS class A: def a(): pass a = classmethod(a) N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classFunctionDecoratorsisPython >= 2.6 onlycCs|jddS(Ns class A: @property def t(self): pass @t.setter def t(self, value): pass @t.deleter def t(self): pass (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_modernPropertys cCs|jddS(sDon't die on unary +.s+1N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_unaryPlusscCs|jdtjdS(sn If a name in the base list of a class definition is undefined, a warning is emitted. s2 class foo(foo): pass N(RRt UndefinedName(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_undefinedBaseClassscCs|jdtjdS(s If a class name is used in the body of that class's definition and the name is not already defined, a warning is emitted. s, class foo: foo N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt"test_classNameUndefinedInClassBody$scCs|jddS(s If a class name is used in the body of that class's definition and the name was previously defined in some other way, no warning is emitted. s? foo = None class foo: foo N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classNameDefinedPreviously.scCs|jdtjdS(sW If a class is defined twice in the same module, a warning is emitted. sQ class Foo: pass class Foo: pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classRedefinition:scCs|jdtjdS(sN If a function is redefined as a class, a warning is emitted. sQ def Foo(): pass class Foo: pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_functionRedefinedAsClassEscCs|jdtjdS(sN If a class is redefined as a function, a warning is emitted. sQ class Foo: pass def Foo(): pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classRedefinedAsFunctionPscCs|jdtjdS(sK If a return is used inside a class, a warning is emitted. s7 class Foo(object): return N(RRtReturnOutsideFunction(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classWithReturn[scCs|jdtjdS(sP If a return is used at the module level, a warning is emitted. s return N(RRR'(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_moduleWithReturndscCs|jdtjdS(sJ If a yield is used inside a class, a warning is emitted. s6 class Foo(object): yield N(RRtYieldOutsideFunction(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classWithYieldlscCs|jdtjdS(sO If a yield is used at the module level, a warning is emitted. s yield N(RRR*(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_moduleWithYieldussPython >= 3.3 onlycCs|jdtjdS(sO If a yield from is used inside a class, a warning is emitted. sE class Foo(object): yield from range(10) N(RRR*(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_classWithYieldFrom}scCs|jdtjdS(sT If a yield from is used at the module level, a warning is emitted. s& yield from range(10) N(RRR*(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_moduleWithYieldFromscCsv|jdtj|jdtj|jdtj|jdtj|jdtj|jdtjdS(Ns continue s/ def f(): continue sQ while True: pass else: continue s while True: pass else: if 1: if 2: continue sK while True: def f(): continue sK while True: class A: continue (RRtContinueOutsideLoop(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_continueOutsideLoops     cCsR|jd|jd|jd|jd|jd|jddS(Ns2 while True: continue s: for i in range(10): continue sH while True: if 1: continue sP for i in range(10): if 1: continue s while True: while True: pass else: continue else: pass s while True: try: pass finally: while True: continue (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_continueInsideLoopscCs=|jdtj|jdtj|jdtjdS(Nsq while True: try: pass finally: continue s while True: try: pass finally: if 1: if 2: continue sM try: pass finally: continue (RRtContinueInFinally(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_continueInFinallys   cCs|jdtj|jdtj|jdtj|jdtj|jdtj|jdtj|jdtjdS(Ns break s, def f(): break sN while True: pass else: break s~ while True: pass else: if 1: if 2: break sH while True: def f(): break sH while True: class A: break sJ try: pass finally: break (RRtBreakOutsideLoop(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_breakOutsideLoops      cCsl|jd|jd|jd|jd|jd|jd|jd|jddS( Ns/ while True: break s7 for i in range(10): break sE while True: if 1: break sM for i in range(10): if 1: break s while True: while True: pass else: break else: pass s while True: try: pass finally: while True: break sn while True: try: pass finally: break s while True: try: pass finally: if 1: if 2: break (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_breakInsideLoop)s cCsR|jd|jd|jd|jd|jd|jddS(s# A default except block should be last. YES: try: ... except Exception: ... except: ... NO: try: ... except: ... except Exception: ... sS try: pass except ValueError: pass st try: pass except ValueError: pass except: pass sH try: pass except: pass sr try: pass except ValueError: pass else: pass sg try: pass except: pass else: pass s try: pass except ValueError: pass except: pass else: pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_defaultExceptLastes cCsL|jdtj|jdtj|jdtj|jdtjtj|jdtj|jdtj|jdtj|jdtjtj|jd tj|jd tj|jd tj|jd tjtj|jd tj|jdtj|jdtj|jdtjtjdS(Nst try: pass except: pass except ValueError: pass si try: pass except: pass except: pass s try: pass except: pass except ValueError: pass except: pass s try: pass except: pass except ValueError: pass except: pass except ValueError: pass s try: pass except: pass except ValueError: pass else: pass s try: pass except: pass except: pass else: pass s try: pass except: pass except ValueError: pass except: pass else: pass s try: pass except: pass except ValueError: pass except: pass except ValueError: pass else: pass s try: pass except: pass except ValueError: pass finally: pass s try: pass except: pass except: pass finally: pass s try: pass except: pass except ValueError: pass except: pass finally: pass s try: pass except: pass except ValueError: pass except: pass except ValueError: pass finally: pass s try: pass except: pass except ValueError: pass else: pass finally: pass s try: pass except: pass except: pass else: pass finally: pass s try: pass except: pass except ValueError: pass except: pass else: pass finally: pass s try: pass except: pass except ValueError: pass except: pass except ValueError: pass else: pass finally: pass (RRtDefaultExceptNotLast(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_defaultExceptNotLasts@               s Python 3 onlycCs|jd|jd|jd|jd|jd|jd|jd|jd|jd d jd td d>Dd}|j|dd jdtd d>Dd}|j|dd jdtd d>Dd}|j|dS(s6 Python 3 extended iterable unpacking s# a, *b = range(10) s# *a, b = range(10) s& a, *b, c = range(10) s% (a, *b) = range(10) s% (*a, b) = range(10) s( (a, *b, c) = range(10) s% [a, *b] = range(10) s% [*a, b] = range(10) s( [a, *b, c] = range(10) s, css|]}d|VqdS(sa%dN((t.0ti((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys siis, *rest = range(1<<8)t(css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest) = range(1<<8)t[css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest] = range(1<<8)Niii(Rtjointrange(R ts((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_starredAssignmentNoErrorxs6  $ $cCsdjdtdDd}|j|tjddjdtdDd}|j|tjd djd tdDd }|j|tjdjd tdd>Dd }|j|tjddjdtdd >Dd}|j|tjd djdtdd!>Dd}|j|tj|jdtj|jdtj|jdtj|jdtj|jdtj|jdtj|jdtj|jdtj|jdtjdS("sp SyntaxErrors (not encoded in the ast) surrounding Python 3 extended iterable unpacking s, css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys siis, *rest = range(1<<8 + 1)R<css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest) = range(1<<8 + 1)R=css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest] = range(1<<8 + 1)css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest = range(1<<8 + 2)css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest) = range(1<<8 + 2)css|]}d|VqdS(sa%dN((R:R;((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pys ss, *rest] = range(1<<8 + 2)s' a, *b, *c = range(10) s* a, *b, c, *d = range(10) s( *a, *b, *c = range(10) s) (a, *b, *c) = range(10) s, (a, *b, c, *d) = range(10) s* (*a, *b, *c) = range(10) s) [a, *b, *c] = range(10) s, [a, *b, c, *d] = range(10) s* [*a, *b, *c] = range(10) Niiii i i (R>R?RRt%TooManyExpressionsInStarredAssignmenttTwoStarredExpressions(R R@((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_starredAssignmentErrorssH   $$        s<todo: Too hard to make this warn but other cases stay silentcCs|jdtjdS(sd If a variable is re-assigned to without being used, no warning is emitted. s' x = 10 x = 20 N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_doubleAssignmentscCs|jddS(sc If a variable is re-assigned within a conditional, no warning is emitted. s< x = 10 if True: x = 20 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt"test_doubleAssignmentConditionallyscCs|jddS(sb If a variable is re-assigned to after being used, no warning is emitted. s9 x = 10 y = x * 2 x = 20 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_doubleAssignmentWithUse scCs|jddS(s If a defined name is used on either side of any of the six comparison operators, no warning is emitted. s x = 10 y = 20 x < y x <= y x == y x != y x >= y x > y N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_comparisons cCs|jddS(sn If a defined name is used on either side of an identity test, no warning is emitted. sI x = 10 y = 20 x is y x is not y N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_identity'scCs|jddS(sp If a defined name is used on either side of a containment test, no warning is emitted. sI x = 10 y = 20 x in y x not in y N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_containment3scCs|jd|jddS(s> break and continue statements are supported. s4 for x in [1, 2]: break s7 for x in [1, 2]: continue N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_loopControl?scCs|jddS(s3 Ellipsis in a slice is supported. s [1, 2][...] N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_ellipsisLscCs|jddS(s0 Extended slices are supported. s+ x = 3 [1, 2][x,:] N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_extendedSliceTscCs|jddS(sh Augmented assignment of a variable is supported. We don't care about var refs. s* foo = 0 foo += 1 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_varAugmentedAssignment]scCs|jddS(si Augmented assignment of attributes is supported. We don't care about attr refs. s7 foo = None foo.bar += foo.baz N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_attrAugmentedAssignmentgscCs|jddS(sP A 'global' can be declared in one scope and reused in another. sV def f(): global foo def g(): foo = 'anything'; foo.is_used() N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt#test_globalDeclaredInDifferentScopeqs(i(ii(ii(i(ii(ii(ii(i(i(8t__name__t __module__R R RRRRRRRRRRRRRRRRRRR!R"R#R$R%R&R(R)R+R,R-R.R0R1R3R5R6R7R9RARDRRERFRGRHRIRJRKRLRMRNRORP(((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyR sj           & *  - < J 6H   tTestUnusedAssignmentcBs!eZdZdZdZdZeddZdZdZ e e d8kd d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&e e d9kd'd(Z'e e d:kd'd)Z(d*Z)d+Z*d,Z+d-Z,d.Z-d/Z.d0Z/d1Z0d2Z1e e d;kd3d4Z2e e d<kd6d7Z3RS(=s5 Tests for warning about unused assignments. cCs|jdtjdS(sc Warn when a variable in a function is assigned a value that's never used. s, def a(): b = 1 N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_unusedVariablescCs|jddS(sO Using locals() it is perfectly valid to have unused variables sH def a(): b = 1 return locals() N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_unusedVariableAsLocalsscCs|jdtjdS(sA Using locals() in wrong scope should not matter sq def a(): locals() def a(): b = 1 return N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_unusedVariableNoLocalsss@todo: Difficult because it does't apply in the context of a loopcCs|jdtjdS(sV Shadowing a used variable can still raise an UnusedVariable warning. sR def a(): b = 1 b.foo() b = 2 N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_unusedReassignedVariablescCs|jddS(st Shadowing a used variable cannot raise an UnusedVariable warning in the context of a loop. s^ def a(): b = True while b: b = False N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_variableUsedInLoopscCs|jddS(s Assigning to a global and then not using that global is perfectly acceptable. Do not mistake it for an unused local variable. sO b = 0 def a(): global b b = 1 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignToGlobalsisnew in Python 3cCs|jddS(s Assigning to a nonlocal and then not using that binding is perfectly acceptable. Do not mistake it for an unused local variable. sW b = b'0' def a(): nonlocal b b = b'1' N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignToNonlocalscCs|jddS(s Assigning to a member of another object and then not using that member variable is perfectly acceptable. Do not mistake it for an unused local variable. sR class b: pass def a(): b.foo = 1 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignToMemberscCs|jddS(sW Don't warn when a variable in a for loop is assigned to but not used. sO def f(): for i in range(10): pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignInForLoopscCs|jddS(si Don't warn when a variable in a list comprehension is assigned to but not used. s@ def f(): [None for i in range(10)] N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignInListComprehensionscCs|jddS(sk Don't warn when a variable in a generator expression is assigned to but not used. s@ def f(): (None for i in range(10)) N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_generatorExpressionscCs|jddS(sW Don't warn when a variable assignment occurs lexically after its use. s def f(): x = None for i in range(10): if i > 2: return x x = i * 2 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assignmentInsideLoopscCs]|jd|jdtjtj|jd|jdtj|jdtjdS(s Don't warn when a variable included in tuple unpacking is unused. It's very common for variables in a tuple unpacking assignment to be unused in good Python code, so warning will only create false positives. s6 def f(tup): (x, y) = tup s4 def f(): (x, y) = 1, 2 sq def f(): (x, y) = coords = 1, 2 if x > 1: print(coords) s= def f(): (x, y) = coords = 1, 2 s= def f(): coords = (x, y) = 1, 2 N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_tupleUnpacking s cCs*|jd|jdtjtjdS(sR Don't warn when a variable included in list unpacking is unused. s6 def f(tup): [x, y] = tup s6 def f(): [x, y] = [1, 2] N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_listUnpacking(scCs|jddS(sN Don't warn when the assignment is used in an inner function. s~ def barMaker(): foo = 5 def bar(): return foo return bar N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_closedOver5scCs|jddS(s Don't warn when the assignment is used in an inner function, even if that inner function itself is in an inner function. s def barMaker(): foo = 5 def bar(): def baz(): return foo return bar N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_doubleClosedOverAscCs|jddS(s} Do not warn about unused local variable __tracebackhide__, which is a special variable for py.test. sL def helper(): __tracebackhide__ = True N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt!test_tracebackhideSpecialVariableOscCs7|jd|jdtj|jdtjdS(s9 Test C{foo if bar else baz} statements. sa = 'moo' if True else 'oink'sa = foo if True else 'oink'sa = 'moo' if True else barN(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_ifexpYs cCs|jddS(s No warnings are emitted for using inside or after a nameless C{with} statement a name defined beforehand. s from __future__ import with_statement bar = None with open("foo"): bar bar N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementNoNamesascCs|jddS(s No warnings are emitted for using a name defined by a C{with} statement within the suite or afterwards. st from __future__ import with_statement with open('foo') as bar: bar bar N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementSingleNamenscCs|jddS(sn No warnings are emitted for using an attribute as the target of a C{with} statement. s from __future__ import with_statement import foo with open('foo') as foo.bar: pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementAttributeNamezscCs|jddS(sm No warnings are emitted for using a subscript as the target of a C{with} statement. s from __future__ import with_statement import foo with open('foo') as foo[0]: pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementSubscriptscCs|jdtjdS(s An undefined name warning is emitted if the subscript used as the target of a C{with} statement is not defined. s from __future__ import with_statement import foo with open('foo') as foo[bar]: pass N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt$test_withStatementSubscriptUndefinedscCs|jddS(s No warnings are emitted for using any of the tuple of names defined by a C{with} statement within the suite or afterwards. s from __future__ import with_statement with open('foo') as (bar, baz): bar, baz bar, baz N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementTupleNamesscCs|jddS(s No warnings are emitted for using any of the list of names defined by a C{with} statement within the suite or afterwards. s from __future__ import with_statement with open('foo') as [bar, baz]: bar, baz bar, baz N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_withStatementListNamesscCs|jddS(sq If the target of a C{with} statement uses any or all of the valid forms for that part of the grammar (See U{http://docs.python.org/reference/compound_stmts.html#the-with-statement}), the names involved are checked both for definedness and any bindings created are respected in the suite of the statement and afterwards. s from __future__ import with_statement c = d = e = g = h = i = None with open('foo') as [(a, b), c[d], e.f, g[h:i]]: a, b, c, d, e, g, h, i a, b, c, d, e, g, h, i N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt#test_withStatementComplicatedTargetscCs|jdtjdS(s An undefined name warning is emitted if the name first defined by a C{with} statement is used before the C{with} statement. su from __future__ import with_statement bar with open('foo') as bar: pass N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt%test_withStatementSingleNameUndefinedscCs|jdtjdS(s An undefined name warning is emitted if a name first defined by a the tuple-unpacking form of the C{with} statement is used before the C{with} statement. s| from __future__ import with_statement baz with open('foo') as (bar, baz): pass N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt%test_withStatementTupleNamesUndefinedscCs|jdtjdS(s A redefined name warning is emitted if a name bound by an import is rebound by the name defined by a C{with} statement. s| from __future__ import with_statement import bar with open('foo') as bar: pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt%test_withStatementSingleNameRedefinedscCs|jdtjdS(s A redefined name warning is emitted if a name bound by an import is rebound by one of the names defined by the tuple-unpacking form of a C{with} statement. s from __future__ import with_statement import bar with open('foo') as (bar, baz): pass N(RRR(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt%test_withStatementTupleNamesRedefinedscCs|jdtjdS(s An undefined name warning is emitted if a name is used inside the body of a C{with} statement without first being bound. sh from __future__ import with_statement with open('foo') as bar: baz N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt!test_withStatementUndefinedInsidescCs|jddS(s| A name defined in the body of a C{with} statement can be used after the body ends without warning. sy from __future__ import with_statement with open('foo') as bar: baz = 10 baz N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt#test_withStatementNameDefinedInBodyscCs*|jdtj|jdtjdS(s An undefined name warning is emitted if a name in the I{test} expression of a C{with} statement is undefined. sa from __future__ import with_statement with bar as baz: pass sa from __future__ import with_statement with bar as bar: pass N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt'test_withStatementUndefinedInExpressions iisPython >= 2.7 onlycCs|jddS(s; Dict comprehensions are properly handled. s/ a = {1: x for x in range(10)} N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_dictComprehension scCs|jddS(s: Set comprehensions are properly handled. sB a = {1, 2, 3} b = {x for x in range(10)} N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_setComprehensionAndLiteral)scCs>tdkrdnd}|jd||jd|dS(Niis, s as s: try: pass except Exception%se: e sa def download_review(): try: pass except Exception%se: e (ii(RR(R tas_exc((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_exceptionUsedInExcept3s  cCs|jddS(s Don't issue false warning when an unnamed exception is used. Previously, there would be a false warning, but only when the try..except was in a function sw import tokenize def foo(): try: pass except tokenize.TokenError: pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_exceptWithoutNameInFunction@scCs|jddS(s Don't issue false warning when an unnamed exception is used. This example catches a tuple of exception types. s import tokenize def foo(): try: pass except (tokenize.TokenError, IndentationError): pass N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt%test_exceptWithoutNameInFunctionTupleMscCs|jddS(st Consider a function that is called on the right part of an augassign operation to be used. sJ from foo import bar baz = 0 baz += bar() N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt,test_augmentedAssignmentImportedFunctionCallYscCs|jddS(s,An assert without a message is not an error.s( a = 1 assert a N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assert_without_messagedscCs|jddS(s)An assert with a message is not an error.s- a = 1 assert a, 'x' N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assert_with_messagekscCs|jdtjtjdS(s.An assert of a non-empty tuple is always True.s> assert (False, 'x') assert (False, ) N(RRt AssertTuple(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assert_tuplerscCs|jddS(s,An assert of an empty tuple is always False.s assert () N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assert_tuple_emptyyscCs|jddS(s,An assert of a static value is not an error.s. assert True assert 1 N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_assert_staticssnew in Python 3.3cCs|jdtjdS(s. Test C{yield from} statement s9 def bar(): yield from foo() N(RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_yieldFromUndefinedsisnew in Python 3.6cCs|jddS(s.Test PEP 498 f-strings are treated as a usage.sI baz = 0 print(f'{4*baz\N{RIGHT CURLY BRACKET}') N(R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_f_strings(i(ii(ii(ii(ii(4RQRRt__doc__RTRURVRRWRXRYRRRZR[R\R]R^R_R`RaRbRcRdReRfRgRhRiRjRkRlRmRnRoRpRqRrRsRtRuRvRxRyRzR{R|R}RRRRR(((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyRS{s^               tTestAsyncStatementscBseZeed kddZeed kddZeed kddZeed kddZeedkddZeedkddZ eedkdd Z RS(iisnew in Python 3.5cCs|jddS(Ns8 async def bar(): return 42 (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_asyncDefscCs|jddS(NsS async def read_data(db): await db.fetch('SELECT ...') (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_asyncDefAwaitscCs|jdtjdS(Ns; async def bar(): return foo() (RRR (R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_asyncDefUndefinedscCs|jddS(Ns async def read_data(db): output = [] async for row in db.cursor(): output.append(row) return output (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_asyncForscCs|jddS(Ns async def commit(session, data): async with session.transaction(): await session.update(data) (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_asyncWithscCs|jddS(Ns async def commit(session, data): async with session.transaction() as trans: await trans.begin() ... await trans.end() (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyttest_asyncWithItemscCs|jddS(Ns9 def foo(a, b): return a @ b (R(R ((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyt test_matmuls(ii(ii(ii(ii(ii(ii(ii( RQRRRRRRRRRRR(((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyRs  (Rt __builtin__t @py_builtinst_pytest.assertion.rewritet assertiontrewritet @pytest_artsysRtpyflakesRRtpyflakes.test.harnessRRRRRSR(((sV/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_other.pyts t PKhUHx )@@[pyflakes/test/__pycache__/test_return_with_arguments_inside_generator.cpython-27-PYTEST.pyc ~!Tc@snddlZddljjZddlmZddlm Z ddl m Z m Z de fdYZdS(iN(t version_info(tmessages(tTestCasetskipIftTestcBsbeZeedkddZeedkddZeedkddZRS(isnew in Python 3.3cCs|jdtjdS(Ns class a: def b(): for x in a.c: if x: yield x return a (tflakestmtReturnWithArgsInsideGenerator(tself((sw/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_return_with_arguments_inside_generator.pyt test_return scCs|jdtjdS(NsG def a(): yield 12 return None (RRR(R((sw/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_return_with_arguments_inside_generator.pyttest_returnNonescCs|jdtjdS(NsG def a(): b = yield a return b (RRR(R((sw/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_return_with_arguments_inside_generator.pyttest_returnYieldExpressions(ii(ii(ii(t__name__t __module__RRR R R (((sw/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_return_with_arguments_inside_generator.pyRs (t __builtin__t @py_builtinst_pytest.assertion.rewritet assertiontrewritet @pytest_artsysRtpyflakesRRtpyflakes.test.harnessRRR(((sw/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_return_with_arguments_inside_generator.pyts PKhUHqDpyflakes/test/__pycache__/test_undefined_names.cpython-27-PYTEST.pyc L)W[c@sddlZddljjZddlmZddlm Z ddl m Z m Z ddlmZmZmZdefdYZdefd YZdS( iN(t PyCF_ONLY_AST(t version_info(tmessagestchecker(tTestCasetskipIftskiptTestcBseZdZdZeedIkddZeedJkddZdZe dd Z eedKkdd Z d Z d Z e dd Ze ddZdZdZdZdZdZdZdZdZdZdZeedLkddZeedMkddZdZdZdZdZe d d!Z d"Z!d#Z"d$Z#d%Z$d&Z%d'Z&d(Z'd)Z(d*Z)d+Z*d,Z+d-Z,d.Z-d/Z.d0Z/d1Z0d2Z1d3Z2eedNkd4d5Z3eedOkd4d6Z4eedPkd4d7Z5eedQkd4d8Z6eedRkd4d9Z7eedSkd4d:Z8eedTkd4d;Z9d<Z:d=Z;d>Z<d?Z=d@Z>dAZ?eedUkdDdEZ@dFZAeedVkdDdGZBdHZCRS(WcCs|jdtjdS(Ntbar(tflakestmt UndefinedName(tself((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefined scCs|jddS(Ns for a in range(10) if a](R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedInListComp sis9in Python 2 list comprehensions execute in the same scopecCs|jdtjdS(Ns2 [a for a in range(10)] a (R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefinedInListCompss>in Python 2 exception names stay bound after the except: blockcCs|jdtjdS(s6Exception names can't be used after the except: block.sx try: raise ValueError('ve') except ValueError as exc: pass exc N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefinedExceptionNamescCs|jddS(sLocals declared in except: blocks can be used after the block. This shows the example in test_undefinedExceptionName is different.sy try: raise ValueError('ve') except ValueError as exc: e = exc e N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt test_namesDeclaredInExceptBlocks&ss5error reporting disabled due to false positives belowcCs|jdtjdS(sException names obscure locals, can't be used after. Last line will raise UnboundLocalError on Python 3 after exiting the except: block. Note next two examples for false positives to watch out for.s exc = 'Original value' try: raise ValueError('ve') except ValueError as exc: pass exc N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt1test_undefinedExceptionNameObscuringLocalVariable3scCs|jdtjdS(sException names are unbound after the `except:` block. Last line will raise UnboundLocalError on Python 3 but would print out 've' on Python 2.s try: raise ValueError('ve') except ValueError as exc: pass print(exc) exc = 'Original value' N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt2test_undefinedExceptionNameObscuringLocalVariable2DscCs|jddS(sException names obscure locals, can't be used after. Unless. Last line will never raise UnboundLocalError because it's only entered if no exception was raised.s exc = 'Original value' try: raise ValueError('ve') except ValueError as exc: print('exception logged') raise exc N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt?test_undefinedExceptionNameObscuringLocalVariableFalsePositive1UscCs|jddS(sException names obscure locals, can't be used after. Unless. Last line will never raise UnboundLocalError because `error` is only falsy if the `except:` block has not been entered.s exc = 'Original value' error = None try: raise ValueError('ve') except ValueError as exc: error = 'exception logged' if error: print(error) else: exc N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt?test_undefinedExceptionNameObscuringLocalVariableFalsePositive2ds cCs|jdtjdS(sException names obscure globals, can't be used after. Last line will raise UnboundLocalError on both Python 2 and Python 3 because the existence of that exception name creates a local scope placeholder for it, obscuring any globals, etc.s exc = 'Original value' def func(): try: pass # nothing is raised except ValueError as exc: pass # block never entered, exc stays unbound exc N(R R tUndefinedLocal(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt2test_undefinedExceptionNameObscuringGlobalVariablevscCs|jdtjdS(sException names obscure globals, can't be used after. Last line will raise NameError on Python 3 because the name is locally unbound after the `except:` block, even if it's nonlocal. We should issue an error in this case because code only working correctly if an exception isn't raised, is invalid. Unless it's explicitly silenced, see false positives below.s exc = 'Original value' def func(): global exc try: raise ValueError('ve') except ValueError as exc: pass # block never entered, exc stays unbound exc N(R R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt3test_undefinedExceptionNameObscuringGlobalVariable2s  cCs|jddS(sException names obscure globals, can't be used after. Unless. Last line will never raise NameError because it's only entered if no exception was raised.s exc = 'Original value' def func(): global exc try: raise ValueError('ve') except ValueError as exc: print('exception logged') raise exc N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt@test_undefinedExceptionNameObscuringGlobalVariableFalsePositive1s cCs|jddS(sException names obscure globals, can't be used after. Unless. Last line will never raise NameError because `error` is only falsy if the `except:` block has not been entered.sN exc = 'Original value' def func(): global exc error = None try: raise ValueError('ve') except ValueError as exc: error = 'exception logged' if error: print(error) else: exc N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt@test_undefinedExceptionNameObscuringGlobalVariableFalsePositive2s cCs|jddS(NsQ class a: def b(): fu fu = 1 (R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_functionsNeedGlobalScopescCs|jddS(Ns range(10)(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt test_builtinsscCs|jddS(sm C{WindowsError} is sometimes a builtin name, so no warning is emitted for using it. t WindowsErrorN(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_builtinWindowsErrorscCs|jddS(sh Use of the C{__file__} magic global should not emit an undefined name warning. t__file__N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_magicGlobalsFilescCs|jddS(sl Use of the C{__builtins__} magic global should not emit an undefined name warning. t __builtins__N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_magicGlobalsBuiltinsscCs|jddS(sh Use of the C{__name__} magic global should not emit an undefined name warning. t__name__N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_magicGlobalsNamescCs*|jdtj|jddddS(s Use of the C{__path__} magic global should not emit an undefined name warning, if you refer to it from a file called __init__.py. t__path__tfilenamespackage/__init__.pyN(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_magicGlobalsPathscCs|jdtjtjdS(s)Can't find undefined names with import *.sfrom fu import *; barN(R R tImportStarUsedtImportStarUsage(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_globalImportStars sobsolete syntaxcCs#|jdtjtjtjdS(sd A local import * still allows undefined names to be found in upper scopes. sC def a(): from fu import * bar N(R R R(R t UnusedImport(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_localImportStarscCs|jddS(s-Unpacked function parameters create bindings.s9 def a((bar, baz)): bar; baz N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_unpackedParameterscCs|jd|jddS(sd "global" can make an otherwise undefined name in another function defined. s@ def a(): global fu; fu = 1 def b(): fu sC def c(): bar def b(): global bar; bar = 1 N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedByGlobal scCs|jddS(s5 "global" can accept multiple names. sS def a(): global fu, bar; fu = 1; bar = 2 def b(): fu; bar N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt!test_definedByGlobalMultipleNamesscCs|jdtjdS(sD A global statement in the global scope is ignored. sB global x def foo(): print(x) N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_globalInGlobalScope!scCs|jdtjdS(s@A global statement does not prevent other names being undefined.sQ def f1(): s def f2(): global m N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_global_reset_name_only+sttodocCs|jdtjdS(s4An unused global statement does not define the name.sQ def f1(): m def f2(): global m N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_unused_global7scCs|jdtjdS(sDel deletes bindings.sa = 1; del a; aN(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delBscCs|jddS(s%Del a global binding from a function.sY a = 1 def f(): global a del a a N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delGlobalFscCs|jdtjdS(sDel an undefined name.sdel aN(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delUndefinedPscCs|jddS(s8 Ignores conditional bindings deletion. sq context = None test = True if False: del(test) assert(test) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delConditionalTscCs|jddS(sh Ignored conditional bindings deletion even if they are nested in other blocks. s context = None test = True if False: with context(): del(test) assert(test) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delConditionalNested`scCs|jddS(sb Ignore bindings deletion if called inside the body of a while statement. s~ def test(): foo = 'bar' while False: del foo assert(foo) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt test_delWhilenscCs|jddS(s Ignore bindings deletion if called inside the body of a while statement and name is used inside while's test part. s def _worker(): o = True while o is not True: del o o = False N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delWhileTestUsage{scCs|jddS(sx Ignore bindings deletions if node is part of while's test, even when del is in a nested block. s context = None def _worker(): o = True while o is not True: while True: with context(): del o o = False N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_delWhileNesteds cCs|jddS(s.Global names are available from nested scopes.sO a = 1 def b(): def c(): a N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_globalFromNestedScopescCs|jdtjdS(s~ Test that referencing a local name that shadows a global, before it is defined, generates a warning. s_ a = 1 def fun(): a a = 2 return a N(R R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt(test_laterRedefinedGlobalFromNestedScopescCs|jdtjdS(s Test that referencing a local name in a nested scope that shadows a global declared in an enclosing scope, before it is defined, generates a warning. s a = 1 def fun(): global a def fun2(): a a = 2 return a N(R R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt)test_laterRedefinedGlobalFromNestedScope2scCs|jdtjdS(s If a name defined in an enclosing scope is shadowed by a local variable and the name is used locally before it is bound, an unbound local warning is emitted, even if there is a class scope between the enclosing scope and the local scope. s def f(): x = 1 class g: def h(self): a = x x = None print(x, a) print(x) N(R R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt"test_intermediateClassScopeIgnoreds cCsN|jdtjjd}|jr+dnd}|j|jd|fdS(s Test that referencing a local name in a nested scope that shadows a variable declared in two different outer scopes before it is defined in the innermost scope generates an UnboundLocal warning which refers to the nearest shadowed name. s def a(): x = 1 def b(): x = 2 # line 5 def c(): x x = 3 return x return x return x iiitxN(R R RRt withDoctestt assertEqualt message_args(R texctexpected_line_num((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt$test_doubleNestingReportsClosestNames cCs|jdtjdS(s Test that referencing a local name in a nested scope that shadows a global, before it is defined, generates a warning. s def fun(): a = 1 def fun2(): a a = 1 return a return a N(R R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt)test_laterRedefinedGlobalFromNestedScope3scCs/|jdtjtjtjtjtjdS(Ns def f(seq): a = 0 seq[a] += 1 seq[b] /= 2 c[0] *= 2 a -= 3 d += 4 e[any] = 5 (R R R tUnusedVariable(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt!test_undefinedAugmentedAssignments   cCs|jddS(s*Nested classes can access enclosing scope.s def f(foo): class C: bar = foo def f(self): return foo return C() f(123).f() N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_nestedClass s cCs|jdtjdS(s=Free variables in nested classes must bind at class creation.s def f(): class C: bar = foo foo = 456 return foo f() N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_badNestedClassscCs|jddS(s+Star and double-star arg names are defined.s? def f(a, *b, **c): print(a, b, c) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedAsStarArgs"ssnew in Python 3cCs+|jd|jd|jddS(s!Star names in unpack are defined.s7 a, *b = range(10) print(a, b) s7 *a, b = range(10) print(a, b) s= a, *b, c = range(10) print(a, b, c) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedAsStarUnpack)s cCs+|jd|jd|jddS(sS Star names in unpack are used if RHS is not a tuple/list literal. s8 def f(): a, *b = range(10) s: def f(): (*a, b) = range(10) s= def f(): [a, *b, c] = range(10) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_usedAsStarUnpack9s cCsU|jdtjtj|jdtjtj|jdtjtjtjdS(sQ Star names in unpack are unused if RHS is a tuple/list literal. sC def f(): a, *b = any, all, 4, 2, 'un' sL def f(): (*a, b) = [bool, int, float, complex] sD def f(): [a, *b, c] = 9, 8, 7, 6, 5, 4 N(R R RH(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_unusedAsStarUnpackKs cCs|jd|jddS(s#Keyword-only arg names are defined.s> def f(*, a, b=None): print(a, b) s\ import default_b def f(*, a, b=default_b): print(a, b) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_keywordOnlyArgs]scCs|jdtjdS(sTypo in kwonly name.sC def f(*, a, b=default_c): print(a, b) N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_keywordOnlyArgsUndefinedkscCs|jd|jddS(sUndefined annotations.s from abc import note1, note2, note3, note4, note5 def func(a: note1, *args: note2, b: note3=12, **kw: note4) -> note5: pass sk def func(): d = e = 42 def func(a: {1, d}) -> (lambda c: e): pass N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_annotationUndefinedsscCs|jddS(NsR from abc import ABCMeta class A(metaclass=ABCMeta): pass (R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_metaClassUndefinedscCs|jd|jddS(sc Using the loop variable of a generator expression results in no warnings. s(a for a in [1, 2, 3] if a)s-(b for b in (a for a in [1, 2, 3] if a) if b)N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedInGenExps cCs*|jdtj|jdtjdS(s} The loop variables of generator expressions nested together are not defined in the other generator. s-(b for b in (a for a in [1, 2, 3] if b) if b)s-(b for b in (a for a in [1, 2, 3] if a) if a)N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefinedInGenExpNesteds   cCsD|jd|jd|jdtj|jdtjdS(sr Some compatibility code checks explicitly for NameError. It should not trigger warnings. sc try: socket_map except NameError: socket_map = {} s try: _memoryview.contiguous except (NameError, AttributeError): raise RuntimeError("Python >= 3.3 is required") sY try: socket_map except: socket_map = {} sc try: socket_map except Exception: socket_map = {} N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefinedWithErrorHandlers cCs-|jdtdkr)|jdndS(sT Defined name for generator expressions and dict/set comprehension. s class A: T = range(10) Z = (x for x in T) L = [x for x in T] B = dict((i, str(i)) for i in T) iis class A: T = range(10) X = {x for x in T} Y = {x:x for x in T} N(ii(R R(R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedInClasss  cCs|jddS(s9Defined name for nested generator expressions in a class.sa class A: T = range(10) Z = (x for x in (a for a in T)) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_definedInClassNestedscCs=|jdtj|jdtj|jdtjdS(sP The loop variable is defined after the expression is computed. s9 for i in range(i): print(i) s( [42 for i in range(i)] s( (42 for i in range(i)) N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_undefinedInLoops   iis&Dictionary comprehensions do not existcCs|jddS(si Defined name referenced from a lambda function within a dict/set comprehension. s4 {lambda: id(x) for x in range(10)} N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt/test_definedFromLambdaInDictionaryComprehensionscCs|jddS(sg Defined name referenced from a lambda function within a generator expression. s7 any(lambda: id(x) for x in range(10)) N(R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt!test_definedFromLambdaInGeneratorscCs|jdtjdS(sk Undefined name referenced from a lambda function within a dict/set comprehension. s4 {lambda: id(y) for x in range(10)} N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt1test_undefinedFromLambdaInDictionaryComprehensionscCs|jdtjdS(si Undefined name referenced from a lambda function within a generator expression. s7 any(lambda: id(y) for x in range(10)) N(R R R (R ((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyt'test_undefinedFromLambdaInComprehensions(i(i(i(i(i(i(i(i(i(i(i(i(ii(ii(DR#t __module__R RRRRRRRRRRRRRRRRRRR R"R$R'R*R,R-R.R/R0R1R3R4R5R6R7R8R9R:R;R<R=R>R?RFRGRIRJRKRLRMRNRORPRQRRRSRTRURVRWRXRYRZR[R\R](((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyR s                                    t NameTestscBseZdZdZRS(s6 Tests for some extra cases of name handling. cCsItdddt}t|jdjd_|jttj |dS(sj A Name node with an unrecognized context results in a RuntimeError being raised. sx = 10stexeciN( tcompileRtobjecttbodyttargetstctxt assertRaisest RuntimeErrorRtChecker(R ttree((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyttest_impossibleContexts(R#R^t__doc__Rj(((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyR_s(t __builtin__t @py_builtinst_pytest.assertion.rewritet assertiontrewritet @pytest_art_astRtsysRtpyflakesRR Rtpyflakes.test.harnessRRRRR_(((s`/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_undefined_names.pyts  PKhUHtrtr8pyflakes/test/__pycache__/test_api.cpython-27-PYTEST.pyc :FVLUc@sdZddlZddljjZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZddlmZmZmZmZddlmZmZejdfkrddlmZnddlmZeZyejeZ Wne!k re"Z nXejdd fkp6e Z#Z$d Z%d e&fd YZ'd e&fdYZ(de&fdYZ)defdYZ*defdYZ+defdYZ,defdYZ-de-fdYZ.dS(s) Tests for L{pyflakes.scripts.pyflakes}. iN(t UnusedImport(tReporter(tmaint checkPathtcheckRecursivetiterSourceCode(tTestCasetskipIfi(tStringIOicOs5tj|}t_z|||SWd|t_XdS(s? Call C{f} with C{sys.stderr} redirected to C{stderr}. N(tsyststderr(R tftargstkwargstouter((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt withStderrTo$stNodecBseZdZddZRS(s Mock an AST node. icCs||_||_dS(N(tlinenot col_offset(tselfRR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt__init__3s (t__name__t __module__t__doc__R(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR/stSysStreamCapturingcBs)eZdZdZdZdZRS(sDReplaces sys.stdin, sys.stdout and sys.stderr with StringIO objects.cCst|p d|_dS(Nt(Rt_stdin(Rtstdin((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR<scCsZtj|_tj|_tj|_|jt_tt_|_ tt_|_ |S(N( R Rt _orig_stdintstdoutt _orig_stdoutR t _orig_stderrRRt_stdout_stringiot_stderr_stringio(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt __enter__?s    cGsL|jj|_|jj|_|jt_|jt_ |j t_ dS(N( R tgetvaluetoutputR!terrorRR RRRRR (RR ((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt__exit__Js   (RRRRR"R&(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR8s  tLoggingReportercBs2eZdZdZdZdZdZRS(sK Implementation of Reporter that just appends any error to a list. cCs ||_dS(sh Construct a C{LoggingReporter}. @param log: A list to append log messages to. N(tlog(RR(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRXscCs |jjdt|fdS(Ntflake(R(tappendtstr(Rtmessage((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR)`scCs|jjd||fdS(NtunexpectedError(R(R*(RtfilenameR,((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR-cscCs&|jjd|||||fdS(Nt syntaxError(R(R*(RR.tmsgRtoffsettline((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR/fs(RRRRR)R-R/(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR'Ss    tTestIterSourceCodecBs_eZdZdZdZdZdZdZdZdZ dZ d Z RS( s& Tests for L{iterSourceCode}. cCstj|_dS(N(ttempfiletmkdtempttempdir(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pytsetUposcCstj|jdS(N(tshutiltrmtreeR6(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttearDownrscGs|s_didtjks-tj|r<tj|ndd6}ttj|ntjj |j |}t |d}|j |S(NRsassert %(py0)stpartstpy0tasassert %(py0)s( t @py_builtinstlocalst @pytest_art_should_repr_global_namet _safereprtAssertionErrort_format_explanationtostpathtjoinR6topentclose(RR;t @py_format1tfpathtfd((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt makeEmptyFileusA cCs&|jtt|jggdS(sB There are no Python files in an empty directory. N(t assertEqualtlistRR6(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_emptyDirectory|scCs8|jd}|jtt|jg|gdS(sd If the directory contains one Python file, C{iterSourceCode} will find it. sfoo.pyN(RMRNRORR6(Rt childpath((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_singleFilescCs3|jd|jtt|jggdS(sJ Files that are not Python source files are not included. sfoo.pycN(RMRNRORR6(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_onlyPythonSources cCstjtjj|jd|jdd}tjtjj|jd|jdd}|jd}|jtt|jgt|||gdS(sk If the Python files are hidden deep down in child directories, we will find them. tfoosa.pytbarsb.pysc.pyN( REtmkdirRFRGR6RMRNtsortedR(Rtapathtbpathtcpath((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt test_recursesscCstjj|jd}tjj|jd}tj||jdd}tj||jdd}|jtt||gt||gdS(sr L{iterSourceCode} can be given multiple directories. It will recurse into each of them. RTRUsa.pysb.pyN( RERFRGR6RVRMRNRWR(RtfoopathtbarpathRXRY((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_multipleDirectoriess  cCs5|jd}|jtt|g|gdS(s If one of the paths given to L{iterSourceCode} is not a directory but a file, it will include that in its output. se.pyN(RMRNROR(Rtepath((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_explicitFiless( RRRR7R:RMRPRRRSR[R^R`(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR3js        t TestReportercBs;eZdZdZdZdZdZdZRS(s Tests for L{Reporter}. cCsKt}td|}|jddddd|jd|jdS(s  C{syntaxError} reports that there was a syntax error in the source file. It reports to the error stream and includes the filename, line number, error message, actual line of source and a caret pointing to where the error is. sfoo.pys a problemiisbad line of sources2foo.py:3:8: a problem bad line of source ^ N(RRtNoneR/RNR#(Rterrtreporter((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_syntaxErrors  cCsKt}td|}|jddddd|jd|jdS(sy C{syntaxError} doesn't include a caret pointing to the error if C{offset} is passed as C{None}. sfoo.pys a problemisbad line of sources'foo.py:3: a problem bad line of source N(RRRbR/RNR#(RRcRd((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_syntaxErrorNoOffsets cCs~t}ddg}td |}|jdddt|dddj||jd |d dd |jd S( s If there's a multi-line syntax error, then we only report the last line. The offset is adjusted so that it is relative to the start of the last line. sbad line of sourcesmore bad lines of sourcesfoo.pys a problemiiis sfoo.py:3:7: a problem is ^ N(RRRbR/tlenRGRNR#(RRctlinesRd((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_multiLineSyntaxErrors   cCsBt}td|}|jdd|jd|jdS(sO C{unexpectedError} reports an error processing a source file. s source.pys error messagessource.py: error message N(RRRbR-RNR#(RRcRd((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_unexpectedErrors cCs^t}t|d}tdtdd}|j||j|jd|fdS(s C{flake} reports a code warning from Pyflakes. It is exactly the str() of a L{pyflakes.messages.Message}. sfoo.pyi*RUs%s N(RRRbRRR)RNR#(RtoutRdR,((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt test_flakes   (RRRReRfRiRjRl(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRas     t CheckTestscBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zeejd kddZdZdZdZdZdZdZRS(sL Tests for L{check} and L{checkPath} which check a file for flakes. cCs]tj\}}t|ds3|jd}nt|d}|j||j|S(sV Make a temporary file containing C{content} and return a path to it. tdecodetasciitwb(R4tmkstempthasattrtencodeRHtwriteRI(Rtcontentt_RKRL((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt makeTempFile s  cCsPt}t|t|}|j||jft|dj|fdS(s Assert that C{path} causes errors. @param path: A path to a file to check. @param errorList: A list of errors expected to be printed to stderr. RN(RRRRNR#RgRG(RRFt errorListRctcount((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pytassertHasErrorss cCs+g}t|}t||}||fS(s Get any warnings or errors reported by pyflakes for the file at C{path}. @param path: The path to a Python file on disk that pyflakes will check. @return: C{(count, log)}, where C{count} is the number of warnings or errors generated, and log is a list of those warnings, presented as structured data. See L{LoggingReporter} for more details. (R'R(RRFR(RdRy((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt getErrors!s  cCs'ddlm}|j|jtdS(Ni(tpyflakes(tpyflakes.scriptsR|tassertIsR(Rtscript_pyflakes((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_legacyScript/scCs#|jd}|j|gdS(s Source which doesn't end with a newline shouldn't cause any exception to be raised nor an error indicator to be returned by L{check}. sdef foo(): pass N(RwRz(RtfName((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_missingTrailingNewline3scCs<|jd\}}|j|d|j|dgdS(s: L{checkPath} handles non-existing files. textremoiR-sNo such file or directoryN(sunexpectedErrorRsNo such file or directory(R{RN(RRyterrors((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_checkPathNonExisting<s cCsd}d}y||WnItk rhtjd}tss|j|jjddkqsn X|j|j|}trd}nd}|j |d||fgdS( s Source which includes a syntax error which results in the raised L{SyntaxError.text} containing multiple lines of source are reported with only the last line of that source. sCdef foo(): ''' def bar(): pass def baz(): '''quux''' cRs |dUdS(N((tsource((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pytevaluateYsis s/EOF while scanning triple-quoted string literalsinvalid syntaxs'%s:8:11: %s '''quux''' ^ N( t SyntaxErrorR texc_infotPYPYt assertTruettextRytfailRwRz(RRRtet sourcePathR,((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_multilineSyntaxErrorFs   &  cCsI|jd}tr%d|f}n d|f}|j||gdS(s The error reported for source files which end prematurely causing a syntax error reflects the cause for the syntax error. sdef foo(s5%s:1:7: parenthesis is never closed def foo( ^ s8%s:1:9: unexpected EOF while parsing def foo( ^ N(RwRRz(RRtresult((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_eofSyntaxErrorss cCsW|jd}trdnd}tr-dnd}|j|d|||fgdS(s The error reported for source files which end prematurely causing a syntax error reflects the cause for the syntax error. sif True: foo =iis ^s ^s"%s:2:%s: invalid syntax foo = %s N(RwRRz(RRtcolumnt last_line((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_eofSyntaxErrorWithTabs cCs]d}|j|}tr!dnd}tr3dnd}|j|d|||fgdS(s Source which has a non-default argument following a default argument should include the line number of the syntax error. However these exceptions do not include an offset. s def foo(bar=baz, bax): pass s ^ Rs8:sO%s:1:%s non-default argument follows default argument def foo(bar=baz, bax): %sN(RwtERROR_HAS_LAST_LINEtERROR_HAS_COL_NUMRz(RRRRR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt(test_nonDefaultFollowsDefaultSyntaxErrors cCsd}|j|}tr!dnd}ts3tr9dnd}tjd krWd}nd}|j|d ||||fgd S( s Source which has a non-keyword argument after a keyword argument should include the line number of the syntax error. However these exceptions do not include an offset. sfoo(bar=baz, bax) s ^ Rs13:iis,positional argument follows keyword arguments!non-keyword arg after keyword args%s:1:%s %s foo(bar=baz, bax) %sN(ii(RwRRRR t version_infoRz(RRRRRR,((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyt&test_nonKeywordAfterKeywordSyntaxErrors cCstj}|jd}|d kr4d|f}nrtrMd|df}nYtrYdnd}|dksd|kodknrdnd }d |||f}|j||gd S(sI The invalid escape syntax raises ValueError in Python 2 s foo = '\xyz'is%s: problem decoding source s\%s:1:6: %s: ('unicodeescape', b'\\xyz', 0, 2, 'truncated \\xXX escape') foo = '\xyz' ^ tUnicodeDecodeErrors ^ Riiisx%s:1:7: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-%d: truncated \xXX escape foo = '\xyz' %sN(i(iii(iii(ii(R RRwRRRz(RtverRtdecoding_errorRtcol((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_invalidEscapes  4twin32sunsupported on WindowscCsd|jd}tj|d|j|\}}|j|d|j|d|dfgdS(sa If the source file is not readable, this is reported on standard error. RiiR-sPermission deniedN(RwREtchmodR{RN(RRRyR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_permissionDeniedscCsi|jd}|j|\}}|j|d|j|dtt|tddfgdS(sc If the source file has a pyflakes warning, this is reported as a 'flake'. s import fooiR)RTN(RwR{RNR+RR(RRRyR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_pyflakesWarnings cCsBtd}d|jd}|j|}|j|gdS(sU If source file declares the correct encoding, no error is reported. i&s# coding: utf-8 x = "%s" sutf-8N(tunichrRsRwRz(RtSNOWMANRR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_encodedFileUTF8s cCs#|jd}|j|gdS(sW Source files with Windows CR LF line endings are parsed successfully. sx = 42 N(RwRz(RR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_CRLFLineEndings scCstd}d|jd}|j|}tr\tjd kr\d}d||f}nd}d|f}|j||gd S( sn If a source file contains bytes which cannot be decoded, this is reported on stderr. i&s# coding: ascii x = "%s" sutf-8isN'ascii' codec can't decode byte 0xe2 in position 21: ordinal not in range(128)s%s:0:0: %s x = "☃" ^ sproblem decoding sources%s: problem decoding source N(i(RRsRwRR RRz(RRRRR,R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_misencodedFileUTF8s  cCsLtd}d|jd}|j|}|j|d|fgdS(sn If a source file contains bytes which cannot be decoded, this is reported on stderr. i&s# coding: ascii x = "%s" sutf-16s%s: problem decoding source N(RRsRwRz(RRRR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_misencodedFileUTF16+s  c CsItj}tjtjj|dtjj|dd}t|d}|jdjd|j tjj|d}t|d}|jdjd|j g}t |}t |g|}|j |d|j t |t d tt|td d fd tt|td d fgd S(sv L{checkRecursive} descends into each directory, finding Python files and reporting problems. RTsbar.pyRps import baz Rosbaz.pysimport contrabandiR)itbazt contrabandN(R4R5RERVRFRGRHRtRsRIR'RRNRWR+RR(RR6tfile1RLtfile2R(Rdtwarnings((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_checkRecursive9s&     $(RRRRwRzR{RRRRRRRRRRR tplatformRRRRRRR(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRms(   -     !   tIntegrationTestscBsYeZdZdZdZdZd dZdZdZ dZ dZ RS( sF Tests of the pyflakes script that actually spawn the script. cCs.tj|_tjj|jd|_dS(Nttemp(R4R5R6RERFRGt tempfilepath(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR7XscCstj|jdS(N(R8R9R6(R((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyR:\scCs:ddl}tjj|j}tjj|dddS(s9 Return the path to the pyflakes binary. iNs..tbinR|(R|RERFtdirnamet__file__RG(RR|t package_dir((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pytgetPyflakesBinary_s c Cs#ttj}tjjtj|diRs%s%sRN(RRRRNRER(RRR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyttest_readFromStdinsN( RRRR7R:RRbRRRRR(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRSs     tTestMaincBseZdZddZRS(s. Tests of the pyflakes main function. cCs_y&t|}td|WdQXWn&tk rN}|j|j|jfSXtddS(NR sSystemExit not raised(RRt SystemExitR$R%tcodet RuntimeError(RRRtcaptureR((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRs N(RRRRbR(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyRs(/Rt __builtin__R>t_pytest.assertion.rewritet assertiontrewriteR@RER R8RR4tpyflakes.messagesRtpyflakes.reporterRt pyflakes.apiRRRRtpyflakes.test.harnessRRRt cStringIORtiotchrRtpypy_version_infotTrueRtAttributeErrortFalseRRRtobjectRRR'R3RaRmRR(((sT/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_api.pyts>      "     NLPYPKhUHBE;E;=pyflakes/test/__pycache__/test_doctests.cpython-27-PYTEST.pyc uV0c@sNddlZddljjZddlZddlZddlm Z ddl m Z m Z mZddlmZddlmZddlmZddlmZmZyejeZWnek reZnXdefdYZdefd YZd eefd YZd eefd YZdeefdYZdS(iN(tmessages(t DoctestScopet FunctionScopet ModuleScope(tTest(tTestCasetskipt _DoctestMixincBs eZeZdZdZRS(cCsg}xtj|jD]}|jdkr7nq|jds|jds|jds|jds|jds|jdrd|}n d |}|j|qWtjd }|d j|S( Ntt sexcept:sexcept sfinally:selse:selif s... %ss>>> %sso def doctest_something(): """ %s """ s (ttextwraptdedentt splitlineststript startswithtappendtjoin(tselftinputtlinestlinetdoctestificator((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyt doctestifys    cOs%tt|j|j|||S(N(tsuperRtflakesR(RRtargstkw((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyR1s(t__name__t __module__tTruet withDoctestRR(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyRs RcBseZeZdZdZdZdZdZdZ dZ dZ e dd Z d Zd Zd Zd ZdZdZdZdZdZdZdZRS(c Csn|jd}|j}g|D]}|jtkr|^q}g|D]}|jtkrG|^qG}g|D]}|jtkro|^qo}|jt|d|jt|d|d}|d}|j|t|j|t|j |t|j |t|j d||j d||j d||jt|d|j d|ddS( s-Check that a doctest is given a DoctestScope.s m = None def doctest_stuff(): ''' >>> d = doctest_stuff() ''' f = m return f iitmt doctest_stufftdtfN( Rt deadScopest __class__RRRt assertEqualtlentassertIsInstancetassertNotIsInstancetassertIn( Rtcheckertscopestscopet module_scopestdoctest_scopestfunction_scopest module_scopet doctest_scope((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_scope_class9s&  (((  c CsB|jd}|j}g|D]}|jtkr|^q}g|D]}|jtkrG|^qG}g|D]}|jtkro|^qo}|jt|d|jt|d|d}|d}|jd||jd||jd||jt|d|jd|d|jd |dd S( s'Check that nested doctests are ignored.s m = None def doctest_stuff(): ''' >>> def function_in_doctest(): ... """ ... >>> ignored_undefined_name ... """ ... df = m ... return df ... >>> function_in_doctest() ''' f = m return f iiRR tfunction_in_doctestiR"tdfN( RR#R$RRRR%R&R)( RR*R+R,R-R.R/R0R1((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_nested_doctest_ignoredas   (((  c CsV|jd}|j}g|D]}|jtkr|^q}g|D]}|jtkrG|^qG}g|D]}|jtkro|^qo}|jt|d|jt|d|d}|d}|jd||jd||jt|d|jd|d|jd|d|jd |d|j d |d S( s;Check that global in doctest does not pollute module scope.s[ def doctest_stuff(): ''' >>> def function_in_doctest(): ... global m ... m = 50 ... df = 10 ... m = df ... >>> function_in_doctest() ''' f = 10 return f iiR R3iR"R4RN( RR#R$RRRR%R&R)t assertNotIn( RR*R+R,R-R.R/R0R1((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyt"test_global_module_scope_pollutions"  (((  cCs|jdtjdS(Nsn global m def doctest_stuff(): ''' >>> m ''' (RRt UndefinedName(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_global_undefinedscCs|jdtjtjdS(s*Doctest within nested class are processed.s class C: class D: ''' >>> m ''' def doctest_stuff(self): ''' >>> m ''' return 1 N(RRR8(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_nested_classs cCs|jddS(s<Doctest module does not process doctest in nested functions.s= def doctest_stuff(): def inner_function(): ''' >>> syntax error >>> inner_function() 1 >>> m ''' return 1 m = inner_function() return m N(R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_ignore_nested_functions cCs|jdtjdS(s#Doctest may not access class scope.s class C: def doctest_stuff(self): ''' >>> m ''' return 1 m = 1 N(RRR8(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_inaccessible_scope_classscCs|jddS(Nsr import foo def doctest_stuff(): ''' >>> foo ''' (R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_importBeforeDocteststtodocCs|jdtjdS(Ns import foo def doctest_stuff(): """ >>> import foo >>> foo """ foo (RRtRedefinedWhileUnused(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_importBeforeAndInDoctests cCs|jddS(Ns def doctest_stuff(): """ >>> import foo >>> foo """ import foo foo() (R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_importInDoctestAndAfter s cCsF|jdtjjd}|j|jd|j|jddS(Nsg def doctest_stuff(): """ >>> x # line 5 """ iii (RRR8RR%tlinenotcol(Rtexc((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_offsetInDoctestsscCsF|jdtjjd}|j|jd|j|jddS(Nso def doctest_stuff(): """ >>> lambda: x # line 5 """ iii(RRR8RR%RBRC(RRD((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_offsetInLambdasInDoctests!scCsF|jdtjjd}|j|jd|j|jddS(Nsm def doctest_stuff(): """ >>> x = 5 """ x ii(RRR8RR%RBRC(RRD((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_offsetAfterDoctests-s cCs|jdtjtjtjj}|d}|j|jd|j|jd|d}|j|jdtr|j|jdn|j|jd|d }|j|jd tr|j|jdn|j|jd dS( Ns def doctest_stuff(): """ >>> from # line 4 >>> fortytwo = 42 >>> except Exception: """ iiiiii iiii(RRtDoctestSyntaxErrorRR%RBRCtPYPY(Rt exceptionsRD((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_syntaxErrorInDoctest;s$   cCsb|jdtjjd}|j|jdtrK|j|jdn|j|jddS(Ns| def doctest_stuff(): """ >>> if True: ... pass """ iii i(RRRHRR%RBRIRC(RRD((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_indentationErrorInDoctest\s cCst|jdtjtjj\}}|j|jd|j|jd|j|jd|j|jddS(Ns def doctest_stuff(arg1, arg2, arg3): """ >>> assert >>> this """ iiii (RRRHR8RR%RBRC(Rtexc1texc2((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_offsetWithMultiLineArgsjs cCs|jddS(NsT def foo(): ''' >>> foo ''' (R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_doctestCanReferToFunction|scCs|jddS(Ns class Foo(): ''' >>> Foo ''' def bar(self): ''' >>> Foo ''' (R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_doctestCanReferToClasss cCs\|jdtjtjj}|d}|j|jd|d}|j|jddS(NsF def buildurl(base, *args, **kwargs): """ >>> buildurl('/blah.php', ('a', '&'), ('b', '=') '/blah.php?a=%26&b=%3D' >>> buildurl('/blah.php', a='&', 'b'='=') '/blah.php?b=%3D&a=%26' """ pass iiii(RRRHRR%RB(RRJRD((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyt!test_noOffsetSyntaxErrorInDoctests   cCs|jddS(Ns def func(): """A docstring >>> func() 1 >>> _ 1 """ return 1 (R(R((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyttest_singleUnderscoreInDoctests (RRRRR2R5R7R9R:R;R<R=RR@RARERFRGRKRLRORPRQRRRS(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyR5s* ( + +     !    t TestOthercBseZdZRS(s2Run TestOther with each test wrapped in a doctest.(RRt__doc__(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyRTst TestImportscBseZdZRS(s4Run TestImports with each test wrapped in a doctest.(RRRU(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyRVstTestUndefinedNamescBseZdZRS(s;Run TestUndefinedNames with each test wrapped in a doctest.(RRRU(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyRWs( t __builtin__t @py_builtinst_pytest.assertion.rewritet assertiontrewritet @pytest_artsysR tpyflakesRRtpyflakes.checkerRRRtpyflakes.test.test_otherRRTtpyflakes.test.test_importsRVt"pyflakes.test.test_undefined_namesRWtpyflakes.test.harnessRRtpypy_version_infoRRItAttributeErrortFalsetobjectR(((sY/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/test/test_doctests.pyts(      }PKhUHºy\pyflakes/scripts/pyflakes.pyc ~!Tc@@sWdZddlmZdddddgZddlmZmZmZmZm Z d S( s6 Implementation of the command-line I{pyflakes} tool. i(tabsolute_importtcheckt checkPathtcheckRecursivetiterSourceCodetmain(RRRRRN( t__doc__t __future__Rt__all__t pyflakes.apiRRRRR(((sW/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/scripts/pyflakes.pytsPKq7E/pyflakes/scripts/pyflakes.py""" Implementation of the command-line I{pyflakes} tool. """ from __future__ import absolute_import # For backward compatibility __all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main'] from pyflakes.api import check, checkPath, checkRecursive, iterSourceCode, main PKhUHaypyflakes/scripts/__init__.pyc ~!Tc@sdS(N((((sW/home/indigo/Documents/pyflakes/build/lib.linux-x86_64-2.7/pyflakes/scripts/__init__.pytsPKq7Epyflakes/scripts/__init__.pyPKiH1C괅 (pyflakes-1.2.2.dist-info/DESCRIPTION.rst======== Pyflakes ======== A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the source file, not importing it, so it is safe to use on modules with side effects. It's also much faster. It is `available on PyPI `_ and it supports all active versions of Python from 2.5 to 3.5. Installation ------------ It can be installed with:: $ pip install --upgrade pyflakes Useful tips: * Be sure to install it for a version of Python which is compatible with your codebase: for Python 2, ``pip2 install pyflakes`` and for Python3, ``pip3 install pyflakes``. * You can also invoke Pyflakes with ``python3 -m pyflakes .`` or ``python2 -m pyflakes .`` if you have it installed for both versions. * If you require more options and more flexibility, you could give a look to Flake8_ too. Design Principles ----------------- Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives. Pyflakes is also faster than Pylint_ or Pychecker_. This is largely because Pyflakes only examines the syntax tree of each file individually. As a consequence, Pyflakes is more limited in the types of things it can check. If you like Pyflakes but also want stylistic checks, you want flake8_, which combines Pyflakes with style checks against `PEP 8`_ and adds per-project configuration ability. Mailing-list ------------ Share your feedback and ideas: `subscribe to the mailing-list `_ Contributing ------------ Issues are tracked on `Launchpad `_. Patches may be submitted via a `GitHub pull request`_ or via the mailing list if you prefer. If you are comfortable doing so, please `rebase your changes`_ so they may be applied to master with a fast-forward merge, and each commit is a coherent unit of work with a well-written log message. If you are not comfortable with this rebase workflow, the project maintainers will be happy to rebase your commits for you. All changes should be include tests and pass flake8_. .. image:: https://api.travis-ci.org/pyflakes/pyflakes.png :target: https://travis-ci.org/pyflakes/pyflakes :alt: Build status .. _Pylint: http://www.pylint.org/ .. _flake8: https://pypi.python.org/pypi/flake8 .. _`PEP 8`: http://legacy.python.org/dev/peps/pep-0008/ .. _Pychecker: http://pychecker.sourceforge.net/ .. _`rebase your changes`: https://git-scm.com/book/en/v2/Git-Branching-Rebasing .. _`GitHub pull request`: https://github.com/pyflakes/pyflakes/pulls PKiHª00)pyflakes-1.2.2.dist-info/entry_points.txt[console_scripts] pyflakes = pyflakes.api:main PKiHaN8>}}&pyflakes-1.2.2.dist-info/metadata.json{"classifiers": ["Development Status :: 6 - Mature", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development", "Topic :: Utilities"], "extensions": {"python.commands": {"wrap_console": {"pyflakes": "pyflakes.api:main"}}, "python.details": {"contacts": [{"email": "code-quality@python.org", "name": "A lot of people", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://github.com/pyflakes/pyflakes"}}, "python.exports": {"console_scripts": {"pyflakes": "pyflakes.api:main"}}}, "generator": "bdist_wheel (0.26.0)", "license": "MIT", "metadata_version": "2.0", "name": "pyflakes", "summary": "passive checker of Python programs", "version": "1.2.2"}PK 4Gv..!pyflakes-1.2.2.dist-info/pbr.json{"is_release": true, "git_version": "e1da183"}PKiH!K &pyflakes-1.2.2.dist-info/top_level.txtpyflakes PKiHndnnpyflakes-1.2.2.dist-info/WHEELWheel-Version: 1.0 Generator: bdist_wheel (0.26.0) Root-Is-Purelib: true Tag: py2-none-any Tag: py3-none-any PKiH< !pyflakes-1.2.2.dist-info/METADATAMetadata-Version: 2.0 Name: pyflakes Version: 1.2.2 Summary: passive checker of Python programs Home-page: https://github.com/pyflakes/pyflakes Author: A lot of people Author-email: code-quality@python.org License: MIT Platform: UNKNOWN Classifier: Development Status :: 6 - Mature Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development Classifier: Topic :: Utilities ======== Pyflakes ======== A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the source file, not importing it, so it is safe to use on modules with side effects. It's also much faster. It is `available on PyPI `_ and it supports all active versions of Python from 2.5 to 3.5. Installation ------------ It can be installed with:: $ pip install --upgrade pyflakes Useful tips: * Be sure to install it for a version of Python which is compatible with your codebase: for Python 2, ``pip2 install pyflakes`` and for Python3, ``pip3 install pyflakes``. * You can also invoke Pyflakes with ``python3 -m pyflakes .`` or ``python2 -m pyflakes .`` if you have it installed for both versions. * If you require more options and more flexibility, you could give a look to Flake8_ too. Design Principles ----------------- Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives. Pyflakes is also faster than Pylint_ or Pychecker_. This is largely because Pyflakes only examines the syntax tree of each file individually. As a consequence, Pyflakes is more limited in the types of things it can check. If you like Pyflakes but also want stylistic checks, you want flake8_, which combines Pyflakes with style checks against `PEP 8`_ and adds per-project configuration ability. Mailing-list ------------ Share your feedback and ideas: `subscribe to the mailing-list `_ Contributing ------------ Issues are tracked on `Launchpad `_. Patches may be submitted via a `GitHub pull request`_ or via the mailing list if you prefer. If you are comfortable doing so, please `rebase your changes`_ so they may be applied to master with a fast-forward merge, and each commit is a coherent unit of work with a well-written log message. If you are not comfortable with this rebase workflow, the project maintainers will be happy to rebase your commits for you. All changes should be include tests and pass flake8_. .. image:: https://api.travis-ci.org/pyflakes/pyflakes.png :target: https://travis-ci.org/pyflakes/pyflakes :alt: Build status .. _Pylint: http://www.pylint.org/ .. _flake8: https://pypi.python.org/pypi/flake8 .. _`PEP 8`: http://legacy.python.org/dev/peps/pep-0008/ .. _Pychecker: http://pychecker.sourceforge.net/ .. _`rebase your changes`: https://git-scm.com/book/en/v2/Git-Branching-Rebasing .. _`GitHub pull request`: https://github.com/pyflakes/pyflakes/pulls PKiHҠ" pyflakes-1.2.2.dist-info/RECORDpyflakes/__init__.py,sha256=TyoJr5e3yETpfn6Cqp5KwpweiqaDNZKKhK7N7U81GVQ,22 pyflakes/__init__.pyc,sha256=wFEdW4bNEmkVBSr2PwUbyI95d0h-n0NUvIpR6d7jygo,198 pyflakes/__main__.py,sha256=aGZKQczOB3fg-jVju9U0qRNLi3YR7zMCCI9Ss2G1EXg,126 pyflakes/api.py,sha256=7uuGx1qswUHlChuYR04eZGnZckjHpsVd7SS3ct9_Pts,6006 pyflakes/api.pyc,sha256=eFOHMtoZGNNVQIYpVBVaHh6dO-I9U8Z1jZbogcAxeaw,6001 pyflakes/checker.py,sha256=qVg62YBv-5jzOoEJSV0oRnA64beTwE28TVuTB0a-xHw,44366 pyflakes/checker.pyc,sha256=7AWblVYR_5X9KuV403wkUanxBoxlLIXh9IhTWFORBgc,45292 pyflakes/messages.py,sha256=2-l1Qr0TJPkItjk-0WmN9N9JdiuxjMXq_TmoOY83x_4,6068 pyflakes/messages.pyc,sha256=52fP8GsPTDIWyRdDRhQ4e_OWqQpSh49hkKhWkCgI_xQ,12712 pyflakes/reporter.py,sha256=lKZtaX1JP5a5vUBdS8lCBRHUU7ZvQzfGbhmq2p2Rhqo,2665 pyflakes/reporter.pyc,sha256=c3nJOEWaKzTHEP_kLXdrunf0OfTj9P33CkXjNC5XkpI,3640 pyflakes/scripts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 pyflakes/scripts/__init__.pyc,sha256=zQMRpvVQbUtm9rk3CdM2G16usanC0Z-dGjWCWxvh4oo,174 pyflakes/scripts/pyflakes.py,sha256=mkM2-LUyi1i6Zt4-q7r66fJJu4JSnB50gWKTPFLJlmo,287 pyflakes/scripts/pyflakes.pyc,sha256=FqaR0CRunzzsSwkZ7rzYeBlo2FifQI4S7izZc0DVFNM,539 pyflakes/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 pyflakes/test/__init__.pyc,sha256=PYkXLnK1OW6MpFS4TKgRuziN4HtYN9nFfUL4VnYvKl8,171 pyflakes/test/harness.py,sha256=bYtEcWVLSZx5wlf49DB0dheR4ksQUK1EsRgPs0JotlY,2425 pyflakes/test/harness.pyc,sha256=LqRpEw73EzdaKEPIOsYOO0fo8kX0Fd251fF3sIz1jzs,4337 pyflakes/test/test_api.py,sha256=CM7c2azvSuXyAb0wuwCyfFtINruOsIbkM12Dpmq8FYA,21836 pyflakes/test/test_doctests.py,sha256=vNt239HMR2DPlZaMzXROW9B1VupmWh8Ck87e9Vv-jy8,12486 pyflakes/test/test_imports.py,sha256=V95OScLo3f5QJICbGdcy5RNmxs8tjFoSvh9MxQKp-Fs,28831 pyflakes/test/test_other.py,sha256=6uU6Jo7LoCnrEx6gsXepgVvOCsZkWNjfHhDEQ-BKu_I,43131 pyflakes/test/test_return_with_arguments_inside_generator.py,sha256=ay7XvfKNTSonRsrJdhDeVagVzdQy672TJbEOVJVs1jA,899 pyflakes/test/test_undefined_names.py,sha256=UNQiBfioHI7FPI_Bl0kuOTawpjGZlSVBMbRzkVTpboc,23554 pyflakes/test/__pycache__/test_api.cpython-27-PYTEST.pyc,sha256=ZKj9VINFdsVXkCW3kze7h_BQz5_adAlbROP8GLElHYM,29300 pyflakes/test/__pycache__/test_doctests.cpython-27-PYTEST.pyc,sha256=KVS0uC9x-BHTuUs_GgCBPnkQNhTL-cDoUoSVB8gXvsI,15173 pyflakes/test/__pycache__/test_imports.cpython-27-PYTEST.pyc,sha256=iahgmmWu8kikhBtjZOTW3gO2V9rFYnUwrf58ADS5dMM,59757 pyflakes/test/__pycache__/test_other.cpython-27-PYTEST.pyc,sha256=_9J1mISYDKypDDAQe4KmE-eGAOs6o6UI5JhtPHB95Og,59307 pyflakes/test/__pycache__/test_return_with_arguments_inside_generator.cpython-27-PYTEST.pyc,sha256=1s3y54doaZG2wmS9VwdUFUDE40V0QpKY_ZM3OqX7TXI,2112 pyflakes/test/__pycache__/test_undefined_names.cpython-27-PYTEST.pyc,sha256=MsbQC-zeSXRp-E2REQ1lRlrX2lrn4nrhiT8lmCUri2c,33462 pyflakes-1.2.2.dist-info/DESCRIPTION.rst,sha256=c_r6tD1bJ2--g82uf9gy1KnQqagCrQWbii2O5D21W_I,2693 pyflakes-1.2.2.dist-info/METADATA,sha256=r68kUEWMjikq16urJmKpewL3KQ_RCwXR7yhWKGiJ_nU,3318 pyflakes-1.2.2.dist-info/RECORD,, pyflakes-1.2.2.dist-info/WHEEL,sha256=GrqQvamwgBV4nLoJe0vhYRSWzWsx7xjlt74FT0SWYfE,110 pyflakes-1.2.2.dist-info/entry_points.txt,sha256=ibYwCxqSCfn_Aie_yRgFv4X_Qz0X6_i5Av-Qn_5SQIQ,48 pyflakes-1.2.2.dist-info/metadata.json,sha256=s0IdlOsJtbbgqmaAdVWgg2P0Kkv1RYz7b4XhCaioC4c,893 pyflakes-1.2.2.dist-info/pbr.json,sha256=AJnVdPLF2j_F1PUx7X4SYVXTCl-eX8CCjHJNlLj6tbk,46 pyflakes-1.2.2.dist-info/top_level.txt,sha256=wuK-mcws_v9MNkEyZaVwD2x9jdhkuRhdYZcqpBFliNM,9 PKoHjvvpyflakes/api.pyPKhUHo88pyflakes/reporter.pycPKpaHM;&pyflakes/messages.pyPKHPwpLNN=pyflakes/checker.pyPKhUHfspyflakes/__init__.pycPKq7EjHi~~lpyflakes/__main__.pyPKhUH<pyflakes/checker.pycPKhUHb>11:pyflakes/messages.pycPKhUHuqqpyflakes/api.pycPKXjcGafi i pyflakes/reporter.pyPKGH" Opyflakes/__init__.pyPKoH {{{pyflakes/test/test_other.pyPKjqG8;y y Kpyflakes/test/harness.pyPKq7E p<pyflakes/test/test_return_with_arguments_inside_generator.pyPKhUH=rרpyflakes/test/harness.pycPKpaH8R 00pyflakes/test/test_doctests.pyPKHןpppyflakes/test/test_imports.pyPKhUHbj~[pyflakes/test/__init__.pycPKHj \\%\pyflakes/test/test_undefined_names.pyPKoH7LULUpyflakes/test/test_api.pyPKq7Epyflakes/test/__init__.pyPKhUHg@n mm<pyflakes/test/__pycache__/test_imports.cpython-27-PYTEST.pycPKhUH ۫:pyflakes/test/__pycache__/test_other.cpython-27-PYTEST.pycPKhUHx )@@[pyflakes/test/__pycache__/test_return_with_arguments_inside_generator.cpython-27-PYTEST.pycPKhUHqD@pyflakes/test/__pycache__/test_undefined_names.cpython-27-PYTEST.pycPKhUHtrtr8Xlpyflakes/test/__pycache__/test_api.cpython-27-PYTEST.pycPKhUHBE;E;="pyflakes/test/__pycache__/test_doctests.cpython-27-PYTEST.pycPKhUHºy\pyflakes/scripts/pyflakes.pycPKq7E/pyflakes/scripts/pyflakes.pyPKhUHayqpyflakes/scripts/__init__.pycPKq7EZpyflakes/scripts/__init__.pyPKiH1C괅 (pyflakes-1.2.2.dist-info/DESCRIPTION.rstPKiHª00)_*pyflakes-1.2.2.dist-info/entry_points.txtPKiHaN8>}}&*pyflakes-1.2.2.dist-info/metadata.jsonPK 4Gv..!.pyflakes-1.2.2.dist-info/pbr.jsonPKiH!K &/pyflakes-1.2.2.dist-info/top_level.txtPKiHndnnQ/pyflakes-1.2.2.dist-info/WHEELPKiH< !/pyflakes-1.2.2.dist-info/METADATAPKiHҠ" 0=pyflakes-1.2.2.dist-info/RECORDPK''# #K