Skip to content

Fix #13881: Add plugin to disallow bytearray as filename in compile() #14173

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

Open
wants to merge 3 commits into
base: main
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
2 changes: 2 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[mypy]
plugins = compile_filename.plugin
Empty file added plugins/__init__.py
Empty file.
Empty file.
32 changes: 32 additions & 0 deletions plugins/compile_filename/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from mypy.plugin import FunctionContext, Plugin
from mypy.types import Instance, Type


class CompileFilenamePlugin(Plugin):
def get_function_hook(self, fullname: str):
# Hook only the built-in compile function
if fullname == "builtins.compile":
return compile_hook
return None


def compile_hook(ctx: FunctionContext) -> Type:
# Arguments to compile: source, filename, mode, ...
# filename is arg index 1 (zero-based)
if len(ctx.arg_types) > 1 and ctx.arg_types[1]:
filename_type = ctx.arg_types[1][0] # first argument passed for filename param
if is_bytearray_type(filename_type):
ctx.api.fail("Passing 'bytearray' as filename to 'compile()' is not allowed", ctx.args[1][0])
return ctx.default_return_type


def is_bytearray_type(typ: Type) -> bool:
# Check if the type is exactly bytearray
if isinstance(typ, Instance):
# The full name for builtins.bytearray is 'builtins.bytearray'
return typ.type.fullname == "builtins.bytearray"
return False


def plugin(version: str):
return CompileFilenamePlugin
Loading