Skip to content

Extend W0102 dangerous-default-value rule to Include os.getenv and os.environ #10630

@dwsutton1

Description

@dwsutton1

Current problem

Hello,

I would like to propose an enhancement to the dangerous-default-value rule. Currently, this rule warns against using mutable default arguments, which can lead to bugs that are difficult to trace. I believe a common and similar risk exists when using os.getenv and os.environ in default arguments, and extending this rule to cover these cases would be beneficial.

Issue Explanation:

Using os.getenv or os.environ in function default arguments can lead to unexpected behavior if the environment changes. This is similar to the mutable default argument problem, where the default value is evaluated at the time of function definition, not at the time of function call. If the environment variable changes after the function is defined, the function may not behave as expected, which can introduce subtle bugs that are hard to detect.

Examples:

Here are some examples illustrating the potential issue:

import os

def get_config(value=os.getenv('CONFIG')):
    return value

# If the environment variable 'CONFIG' changes after the function is defined,
# the function will still return the old value as the default.
import os

def connect_to_service(api_key=os.environ['API_KEY']):
    # Connect using the API key
    pass

# If the 'API_KEY' environment variable is updated after the function definition,
# the function will not use the updated key unless explicitly passed.

Correct Code:

The correct code is very similar to examples already present in W0102

def connect_to_service(api_key=None):
    if api_key is None:
        api_key = os.environ['API_KEY']
    pass


def get_config(value=None):
    if value is None:
        value = os.getenv('CONFIG')
    return value

Benefits:

Helps maintain code reliability and predictability.
Reduces the risk of bugs that are difficult to trace.
Encourages best practices when dealing with environment variables.
I believe this change would be a valuable addition to Pylint, helping developers catch more potential issues early in the development process.

Desired solution

I propose extending the dangerous-default-value rule to include checks for os.getenv and os.environ when used in default arguments. This would help developers avoid potential bugs related to environment changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Enhancement ✨Improvement to a componentNeeds PRThis issue is accepted, sufficiently specified and now needs an implementation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions