__new__() does not return anything, on singletong pattern

Mario Figueiredo marfig at gmail.com
Thu Mar 12 15:44:53 EDT 2015


On Thu, 12 Mar 2015 22:29:24 +1100, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:

>
>I would have a loadfile() method which takes a filename on disk, opens the
>file and passes the contents (or the open file object) to another method,
>load() to do the actual work:
>
>
>class Map:
>    def __new__(cls, width, height, fill, treasure=None):
>        # Include additional args as needed.
>        map = super().__new__.(cls)
>        map.width = width
>        map.height = height
>        map.fill = fill
>        map.treasure = treasure
>        return map
>
>    @classmethod
>    def loadfile(cls, filename):
>        with open(filename, 'r') as f:
>            map = cls.load(f)
>        return map
>
>    @classmethod
>    def load(cls, f):
>        # validate and parse file contents
>        # extract width, height, fill, etc.
>        map = cls(width, height, fill, treasure)
>        return map
>
>
>To get an empty map, you pass the load method a file-like object that
>contains whatever an empty map data file will contain. That could literally
>be an external file, if you so choose, or you could simply read it from a
>global constant or even an embedded string/bytes object:
>
>    @classmethod
>    def new(cls):
>        """Return a new empty map."""
>        emptymap = b"blah blah blah width=100 height=100 fill=1"
>        f = io.StringIO(emptymap)
>        return cls.load(f)
>
>
>This, naturally, assumes that your map format is simple enough and small
>enough that an empty map can be embedded into your code. If an empty map is
>4MB on disk, you probably don't want to do this :-)
>
>Alternatively, set the default arguments to the __new__ constructor to be
>whatever values an empty map uses:
>
>    def __new__(cls, width=100, height=100, fill=1, treasure=None):
>        ...
>
>
>and now your "create empty map" command just calls Map() with no arguments.
>    

Your solution is excelent!

Leveraging the __new__ method is something I wasn't considering. It
gracefully deals with the absence of __init__, not forcing me to raise
an exception or document the class to warn against its use.

Thanks a bunch.



More information about the Python-list mailing list