suggestions for functional style (singleton pattern?)

yves at zioup.com yves at zioup.com
Sat Feb 28 23:29:03 EST 2015


On 2015-02-28 20:45, Mario Figueiredo wrote:

> Problem 1:
> With the exception of get_all_files(), all your functions do is to
> call another standard function. This decreases performance
> unnecessarily and may mislead the users of your API into thinking
> these functions perform some different type of average or min/max
> operations.

I tried to create a simple example to make a point, I wouldn't create function
wrappers like this. I'll to think of a better example, this was to get the
discussion going.

> Problem 3:
> At the very least they should be moved inside the class so it becomes
> clear to anyone caring that these functions really only matter in the
> context of the DirStats object.

Trying to write in a more functional way, not OO here, the functions could be
used by more than one class. I understand OO, use it a lot, but sometimes try
to move beyond that.

> Problem 4:
> You speak of a singleton. But you haven't implemented one. It is not
> clear from your code if this class should be a singleton. I'm guessing
> not. Singletons are in fact rare. Well, let me put it another way:
> Good reasons to code a singleton are rare.

Thanks. I hadn't realise "singleton" meant a class built such that it could
not be instanciated more than once, I thought it corresponded to a pattern
where only one object is ever created from a given class.

> But, if you ever wish to implement a singleton, the following pattern
> mostly works and is short and to the point:
> 
>     class Map():
>         _instance = None
> 
>         def __new__(cls, *args, **kwargs):
>             if Map._instance is None:
>                 Map._instance = super(Map, cls).__new__(cls)
>             return Map._instance
> 
>     >>> a = Map()
>     >>> b = Map()
>     >>> a is b
>     True

Thanks.

> Problem 5:
> A pet peeve of mine. If you aren't going to use a variable, make that
> explicit in your code by taking advatange of Python wonderful language
> features.

Good point - thanks.

--
http://yves.zioup.com
gpg: 4096R/32B0F416





More information about the Python-list mailing list