Search code examples
pythonnamingpep8

PEP 8 - Module name vs variable name for instance


Suppose I have a Python module my_class.py (see PEP 8 convention for modules) that holds a class MyClass (see PEP 8 convention for classes).

Now I want to instantiate that class in a module in the same package and would normally do

from .my_class import MyClass
my_class = MyClass()

since PEP 8 proposes this naming scheme for instance variable names here.

However, in this context, my_class already refers to the module my_class.py and the instance variable would therefore shadow the module.

Do PEP 8 or any other sources give any direction on how to proceed here, or is it just up to the developer to think of a different but less intuitive name for the variable?


Solution

  • In your example, you have explicitly imported MyClass.

    While the module my_class is imported it will not be assigned a variable in your local scope and hence you will not be shadowing it by using my_class for your MyClass instance.

    Update

    When importing a module within the same package it looks like a reference is added to the local scope, however, there is no risk in using the same name. Variables in Python are references to an object rather than the object.

    When you reassign a reference (eg use the name for another object) the object is deleted if there are no other references to the object. In the case of modules they are added to sys.modules when imported, in which case there is always another reference and they are not deleted.