Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add disallowed_imports #645

Merged
merged 4 commits into from
Jun 12, 2023
Merged
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
2 changes: 2 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add `disallowed_imports` configuration option to disallow
imports of specific modules (#645)
- Consider an annotated assignment without a value to be
an exported name (#644)
- Improve the location where `missing_parameter_annotation`
Expand Down
2 changes: 2 additions & 0 deletions pyanalyze/error_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ class ErrorCode(enum.Enum):
override_does_not_override = 86
reveal_type = 87
missing_generic_parameters = 88
disallowed_import = 89


# Allow testing unannotated functions without too much fuss
Expand Down Expand Up @@ -237,6 +238,7 @@ class ErrorCode(enum.Enum):
ErrorCode.invalid_override_decorator: "@override decorator in invalid location",
ErrorCode.override_does_not_override: "Method does not override any base method",
ErrorCode.missing_generic_parameters: "Missing type parameters for generic type",
ErrorCode.disallowed_import: "Disallowed import",
}


Expand Down
33 changes: 33 additions & 0 deletions pyanalyze/name_check_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,16 @@ class DisallowCallsToDunders(StringSequenceOption):
name = "disallow_calls_to_dunders"


class DisallowedImports(StringSequenceOption):
"""List of imports that will trigger an error.

Entries may be top-level modules (e.g., "os") or dotted submodule paths (e.g., "os.path").

"""

name = "disallowed_imports"


class ForLoopAlwaysEntered(BooleanOption):
"""If True, we assume that for loops are always entered at least once,
which affects the potentially_undefined_name check. This will miss
Expand Down Expand Up @@ -2310,13 +2320,24 @@ def check_deprecation(self, node: ast.AST, value: Value) -> bool:

# Imports

def check_for_disallowed_import(self, node: ast.AST, name: str) -> None:
print("CHECK", name)
disallowed = self.options.get_value_for(DisallowedImports)
if name in disallowed:
self._show_error_if_checking(
node,
f"Disallowed import of module {name!r}",
error_code=ErrorCode.disallowed_import,
)

def visit_Import(self, node: ast.Import) -> None:
self.generic_visit(node)
if self.scopes.scope_type() == ScopeType.module_scope:
for name in node.names:
self.import_name_to_node[name.name] = node

for alias in node.names:
self.check_for_disallowed_import(node, alias.name)
self._try_to_import(alias.name)
# "import a.b" sets the name "a", but "import a.b as c" sets "c" to the value "a.b"
varname = (
Expand Down Expand Up @@ -2404,6 +2425,18 @@ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
for name in node.names:
self.future_imports.add(name.name)

if node.module is not None and node.level == 0:
self.check_for_disallowed_import(node, node.module)
for alias in node.names:
# Before 3.10 the alias doesn't have a lineno
if sys.version_info >= (3, 10):
error_node = alias
else:
error_node = node
self.check_for_disallowed_import(
error_node, f"{node.module}.{alias.name}"
)

self._maybe_record_usages_from_import(node)

# See if we can get the names from the stub instead
Expand Down
4 changes: 4 additions & 0 deletions pyanalyze/test.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ functions_safe_to_call = [
]
class_attribute_transformers = [
"pyanalyze.test_config.transform_class_attribute"
]
disallowed_imports = [
"getopt",
"email.quoprimime",
]
41 changes: 41 additions & 0 deletions pyanalyze/test_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,44 @@ def test_import_star(self):
assert_is_value(extensions, KnownValue(P.extensions))
not_a_name # E: undefined_name
""")


class TestDisallowedImport(TestNameCheckVisitorBase):
@assert_passes()
def test_top_level(self):
import getopt # E: disallowed_import

from getopt import GetoptError # E: disallowed_import

print(getopt, GetoptError) # shut up flake8

def capybara():
import getopt # E: disallowed_import
from getopt import GetoptError # E: disallowed_import

print(getopt, GetoptError)

@assert_passes()
def test_nested(self):
import email.quoprimime # E: disallowed_import
from email.quoprimime import unquote # E: disallowed_import

print(email, unquote)

def capybara():
import email.quoprimime # E: disallowed_import
from email.quoprimime import unquote # E: disallowed_import
from email import quoprimime # E: disallowed_import

print(email, unquote, quoprimime)

@assert_passes()
def test_import_from(self):
from email import quoprimime # E: disallowed_import

print(quoprimime)

def capybara():
from email import quoprimime # E: disallowed_import

print(quoprimime)