__new__() does not return anything, on singletong pattern
Mario Figueiredo
marfig at gmail.com
Wed Mar 11 19:33:17 EDT 2015
I'm fairly new to Python, so I don't know if the following is me
abusing the programming language idioms, or simply a mistake of my IDE
code inspection routine.
I have a singleton Map class which is defined like so:
class Map:
_instance = None
def __new__(cls):
if Map._instance is None:
Map._instance = super(Map, cls).__new__(cls)
return Map._instance
def __init__(self, filename):
# Instantiates from the contents of a binary file
I am now trying to add another way of constructing an instance of this
class. (I need to be able to create a dirty empty instance that is
going to be used by the separate map editor script).
I added the following method to the class definition, above:
@classmethod
def generate(cls, width, height, fill=terrain[6]):
if Map._instance is None:
Map._instance = super(Map, cls).__new__(cls)
else:
raise Exception('Cannot generate an instance of Map.')
Map._instance.author = None
Map._instance.name = None
Map._instance.description = None
# etc...
self.cells = [Cell(fill)] * width * height
return Map._instance
The following code runs just fine. But PyCharm flags the assignment
with a warning telling me that generate() does not return anything and
the I lose code completion on the mmap variable.
if __name__ == '__main__':
mmap = Map.generate(12, 24)
print(mmap.width, mmap.height, mmap.author)
I need to understand if this is just a glitch of the IDE or I am doing
indeed something that is frowned upon and ended up caught in a
misleading static analysis warning.
More information about the Python-list
mailing list