Opened 16 months ago

Closed 16 months ago

Last modified 16 months ago

#34765 closed Bug (invalid)

call_command reuses already loaded command causing stale class variable value usage

Reported by: MaziyarMK Owned by: nobody
Component: Core (Management commands) Version: 4.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,

If a custom command has custom class variables that are used in handle(), previously set values are re-used on the next call to the same command because a new instance is not initialized.

because of:

        if isinstance(app_name, BaseCommand):
            # If the command is already loaded, use it directly.
            command = app_name
        else:
            command = load_command_class(app_name, command_name)

https://github.com/django/django/blob/8edaf07a28a3e3848ab1edbdcd2fdc25e6bd6015/django/core/management/__init__.py#L272

I have seen this cause issues when the same command is called several times in a test.

Proposed solution:
Either warn the user about defining custom class level variables, or don't re-use the initialized command, instead kill the old object and create a new one on each use. As an optimizaiton we can require this only on custom commands, and let the base commands keep using the optimized-path with cached command instance.

Bug introduced in: https://github.com/django/django/commit/901c3708fb8a2e51bddd37358f8e536282a8c266

Change History (3)

comment:1 by MaziyarMK, 16 months ago

Summary: call_command reuses already loaded command causing stale class variable usagecall_command reuses already loaded command causing stale class variable value usage

comment:2 by MaziyarMK, 16 months ago

Resolution: invalid
Status: newclosed

comment:3 by Natalia Bidart, 16 months ago

Keywords: call_command removed

Hello,

Thank you for report, though the issue you are describing is how class variables work in Python. This is not a Django specific issue, perhaps you should consider storing you state-data as an instance variable instead.

If you need further help, please consider using any of the user support channels from this link.

Note: See TracTickets for help on using tickets.
Back to Top