Skip to content
This repository has been archived by the owner on Mar 7, 2021. It is now read-only.

Add support for whitelisting runtime defined globals. #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# See LICENSE file for details

import __builtin__
import os.path
import os
import _ast

from pyflakes import messages
Expand Down Expand Up @@ -164,10 +164,6 @@ class ModuleScope(Scope):
pass


# Globally defined names which are not attributes of the __builtin__ module.
_MAGIC_GLOBALS = ['__file__', '__builtins__']



class Checker(object):
"""
Expand All @@ -186,6 +182,12 @@ class Checker(object):
traceTree = False

def __init__(self, tree, filename=None):
# Globally defined names which are not attributes of the
# __builtin__ module.
self.MAGIC_GLOBALS = (
['__file__', '__builtins__'] +
os.environ.get('PYFLAKES_GLOBALS_WHITELIST', '').split(','))

if filename is None:
filename = '(none)'
self._deferredFunctions = []
Expand Down Expand Up @@ -464,7 +466,7 @@ def NAME(self, node):
self.scopeStack[0][node.id].used = (self.scope, node)
except KeyError:
if ((not hasattr(__builtin__, node.id))
and node.id not in _MAGIC_GLOBALS
and node.id not in self.MAGIC_GLOBALS
and not importStarred):
if (os.path.basename(self.filename) == '__init__.py' and
node.id == '__path__'):
Expand Down
21 changes: 20 additions & 1 deletion pyflakes/test/test_undefined_names.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

import os
from _ast import PyCF_ONLY_AST

from twisted.trial.unittest import TestCase
Expand Down Expand Up @@ -43,6 +43,25 @@ def test_magicGlobalsBuiltins(self):
self.flakes('__builtins__')


def test_magicGlobalsWhitelistSingle(self):
"""
Use of a whitelisted magic global should not emit an undefined
name warning.
"""
os.environ['PYFLAKES_GLOBALS_WHITELIST'] = '_'
self.flakes('_')


def test_magicGlobalsWhitelistMultiple(self):
"""
Use of whitelisted magic globals should not emit an undefined
name warning.
"""
os.environ['PYFLAKES_GLOBALS_WHITELIST'] = '_,whitelisted'
self.flakes('_')
self.flakes('whitelisted')


def test_magicGlobalsName(self):
"""
Use of the C{__name__} magic global should not emit an undefined name
Expand Down