pythonpython-3.xname-conflict

How to name instance variables in Python?


I try to stick to the PEP8 coding conventions. I have a package called main. Inside the package there is a module called time, which has a class called Time inside. Now I have a bit of trouble finding a suitable name for my actual instance because time, which would be usually my choice, is already taken by the module and there seems to be a name-clash if I name it this way.

from main.time import Time

time = Time()
...
if time.status == main.time.STOPPED

Maybe I also placed the constant in the wrong module, but I thought that it would be better to have my constants at the place where they belong to. This is a constant used in my class Time (and the main module), so I can make sure that I don't mix it up with another constant called STOPPED used for player movement. Unfortunately I get an AttributeError: 'function' object has no attribute 'time'.

What would be the best solution here? Rename the constants to TIME_STOPPED and PLAYER_STOPPED and put them into a constants module? Naming my instance variable my_time or time_ or something like this is not really what I would like to do. What's the Pythonic way?


Solution

  • Using the name time is a bad choice to begin with, not just because you already have a module that is named time, but also because there is a standard library module named time.

    Anyways, this is not actually your problem (perhaps a clash with the STL module is, but you don't show enough code). The error AttributeError: 'function' object has no attribute 'time' means that main (in main.time) is a function, not module. Your line time = Time() is not the cause of this, but another function object called main inside your executable.