Skip to content

_check_method_and_attr_name in invalid name checker allows names with three leading underscores #1344

@a1-su

Description

@a1-su

Currently, in the _check_method_and_attr_name function in invalid_name_checker.py, it allows three leading underscores instead of only two. While double leading underscores invoke Python's name-mangling rules, triple underscores have no special semantic meaning and should still be flagged by the invalid_name_checker.py.

def _check_method_and_attr_name(node_type: str, name: str) -> list[str]:
"""Returns a list of strings, each detailing how `name` violates Python naming conventions for
method and instance or class attribute names.
Returns an empty list if `name` is a valid method, instance, or attribute name."""
error_msgs = []
# Also consider the case of invoking Python's name mangling rules with leading dunderscores.
if not (_is_in_snake_case(name) or (name.startswith("__") and _is_in_snake_case(name[2:]))):
error_msgs.append(
f'{node_type.capitalize()} name "{name}" should be in snake_case format. '
f"{node_type.capitalize()} names should be lowercase, with words "
f"separated by underscores. A single leading underscore can be used to "
f"denote a private {node_type} while a double leading underscore invokes "
f"Python's name-mangling rules."
)
return error_msgs

When name.startswith("__") is checked and the first two underscores are sliced out with _is_in_snake_case(name[2:]), it doesn't account for the _is_in_snake_case method allowing an optional leading underscore.

def _is_in_snake_case(name: str) -> bool:
"""Returns whether `name` is in snake_case.
`name` is in snake_case if:
- `name` starts with a lowercase letter or an underscore (to denote private fields) followed
by a lowercase letter,
- each word is separated by an underscore, and
- each word is in lowercase.
"""
pattern = "(_?[a-z][a-z0-9_]*)$"
return re.match(pattern, name) is not None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions