Python singleton / object instantiation

2024/9/8 10:20:24

I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:

_Singleton__instance = Noneclass Singleton:def __init__(self):global __instanceif __instance == None:           self.name = "The one"__instance = selfelse:self = __instance

This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):

>>> import singleton
>>> x = singleton.Singleton()
>>> x.name
'The one'
>>> singleton._Singleton__instance.name
'The one'
>>> y = singleton.Singleton()
>>> y.name
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']

Is it possible to do what i'm trying? If not is there another way of doing this?

Any suggestions welcome.

Cheers.

Answer

Assigning to an argument or any other local variable (barename) cannot ever, possibly have ANY effect outside the function; that applies to your self = whatever as it would to ANY other assignment to a (barename) argument or other local variable.

Rather, override __new__:

class Singleton(object):__instance = Nonedef __new__(cls):if cls.__instance == None:cls.__instance = object.__new__(cls)cls.__instance.name = "The one"return cls.__instance

I've done other enhancements here, such as uprooting the global, the old-style class, etc.

MUCH better is to use Borg (aka monostate) instead of your chosen Highlander (aka singleton), but that's a different issue from the one you're asking about;-).

https://en.xdnf.cn/q/73103.html

Related Q&A

Single-Byte XOR Cipher (python)

This is for a modern cryptography class that I am currently taking.The challenge is the cryptopals challenge 3: Single-Byte XOR Cipher, and I am trying to use python 3 to help complete this.I know that…

Basemap Heat error / empty map

I am trying to plot a scattered heat map on a defined geo location. I can very well plot a normal scattered map with no background but I want to combine it with a given lat and lon. I get the following…

Keras custom loss function per tensor group

I am writing a custom loss function that requires calculating ratios of predicted values per group. As a simplified example, here is what my Data and model code looks like: def main():df = pd.DataFrame…

How does numpy.linalg.inv calculate the inverse of an orthogonal matrix?

Im implementing a LinearTransformation class, which inherits from numpy.matrix and uses numpy.matrix.I to calculate the inverse of the transformation matrix.Does anyone know whether numpy checks for or…

pandas: Using color in a scatter plot

I have a pandas dataframe:-------------------------------------- | field_0 | field_1 | field_2 | -------------------------------------- | 0 | 1.5 | 2.9 | -------------------…

Framing Errors in Celery 3.0.1

I recently upgraded to Celery 3.0.1 from 2.3.0 and all the tasks run fine. Unfortunately. Im getting a "Framing Error" exception pretty frequently. Im also running supervisor to restart the t…

decorator() got an unexpected keyword argument

I have this error on Django view:TypeError at /web/host/1/ decorator() got an unexpected keyword argument host_id Request Method: GET Request URL: http://127.0.0.1:8000/web/host/1/edit Django Versio…

Conflict between sys.stdin and input() - EOFError: EOF when reading a line

I cant get the following script to work without throwing an EOFError exception:#!/usr/bin/env python3import json import sys# usage: # echo [{"testname": "testval"}] | python3 test.p…

Requests - inability to handle two cookies with same name, different domain

I am writing a Python 2.7 script using Requests to automate access to a website that sets two cookies with the same name, but different domains, E.g. Name mycookie, Domain www.example.com and subdomain…

Python logging from multiple processes

I have a possibly long running program that currently has 4 processes, but could be configured to have more. I have researched logging from multiple processes using pythons logging and am using the So…