Singleton class Instantiation: RecursionError: maximum recursion depth exceeded - python-3.x

I'am trying to implement Singleton class. This is my code:
class ImageUtils:
__instance = None
def __init__(self):
""" Virtually private constructor. """
if ImageUtils.__instance != None:
raise Exception("This class is a singleton!")
else:
ImageUtils.__instance = self
#staticmethod
def getInstance():
"""Static access method"""
if ImageUtils.getInstance() == None:
ImageUtils()
return ImageUtils.__instance
I test it like this:
s = ImageUtils()
print(s)
s = ImageUtils.getInstance()
print(s)
s = ImageUtils.getInstance()
print(s)
I get this error:
if ImageUtils.getInstance() == None: RecursionError: maximum recursion depth exceeded
Now, when I test the code here: Python Design Pattern Singletons, it gives me the expected result of printing the Singleton instance's memory location, three times.
Question: When I copy and paste the code given in the link, I get the expected result. However, the implementation of the ImageUtils class gives me RecursionError. Why is that? Any help is highly appreciated.

In the def getInstance():
if ImageUtils.getInstance() == None
should instead be
if ImageUtils.__instance == None

Related

Nested function in Python class

i have a little "basic understanding" Python problem.
So let me explain my problem.
At first a very simple code snippet.
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
return self.__sentence[::-1]
if __name__ == '__main__':
print(Revert("Stackoverflow").get_sentence())
print(Revert("Stackoverflow").revert_sentence())
So this show normal function calling of python functions.
But how can i transform this code so i can call the revert function like this:
print(Revert("Stackoverflow").get_sentence().revert_sentence())
Maybe I'm miss the forest through the trees. But I didn't get it how to do this.
I already tried to solve the problem with innermethods but this didn't work for me
...
def get_sentence(self):
def revert_sentence():
self.revert_sentence()
return self.__sentence
...
Many thanks in advance
Implement __str__ to return the actual string. Then in the existing methods, return the object. This way you can chain. But when print is applied to it, that __str__ method will kick in:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self
def revert_sentence(self):
return Revert(self.__sentence[::-1])
# Some more such methods ...
def upper(self):
return Revert(self.__sentence.upper())
def first(self, count):
return Revert(self.__sentence[:count])
def dotted(self):
return Revert(".".join(self.__sentence))
# For getting a string
def __str__(self):
return self.__sentence
print(Revert("Stackoverflow").get_sentence().revert_sentence())
print(Revert("Stackoverflow")
.revert_sentence()
.first(8)
.upper()
.revert_sentence()
.first(4)
.dotted()) # "O.V.E.R"
Note that now the .get_sentence() method is not really doing much, and you can always strip it from a chain.
Here You go:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
# It's important to know that you are making changes in the same instance of the object
self.__sentence = self.__sentence[::-1]
return self
def pseudo_revert(self):
# Return a new object with reverted string, but this instance still has original string intact.
return Revert(self.__sentence[::-1])
if __name__ == '__main__':
r1 = Revert("Stackoverflow")
r2 = Revert("Stackoverflow")
print(r1.get_sentence()) # Stackoverflow
print(r1.revert_sentence().get_sentence()) # wolfrevokcatS
print(r1.get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
print(r2.pseudo_revert().get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
Hope this helps you understand the object, instance of an object, and method of object distinctly.

Is it possible to make a class which lets you stack enum Flags?

I'd like to use named constants whereever possible instead of providing literal values or longish function signatures with a lot of boolean args.
Therefore i like pythons enum.Flag or enum.Enum.
More precisely, I would like to pass an argument to a function which holds a bit combination of enum.Flags. And i would like to avoid writing module.TheFlags.flagX for every set flag I would like to pass to the function. The flags should replace the boolean args.
I came up with following code:
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
class FuncFlags:
def __init__(self):
self._flags = AvailableFlags(0)
#property
def flag1(self):
self._flags |= AvailableFlags.flag1
return self
#property
def flag2(self):
self._flags |= AvailableFlags.flag2
return self
def __str__(self):
return str(self._flags.value)
def func(setup_flags: FuncFlags):
print(setup_flags)
if __name__ == "__main__":
func(FuncFlags().flag1)
func(FuncFlags().flag2)
func(FuncFlags().flag1.flag2)
func(FuncFlags())
It creates instances of FuncFlags and then mis-uses the properties to set single flags returning the changed object itself.
However, one would expect that the property does NOT change object state.
Therefore, this is obviously not a clean solution despite that it works, though.
So, my question is, how this can be implemented in a clean, reusable way?
I'm not really clear on what you are trying to accomplish, but perhaps this helps?
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
flag1, flag2 = AvailableFlag
def func(setup_flags: AvailableFlags):
print(setup_flags)
if __name__ == "__main__":
func(flag1)
func(flag2)
func(flag1|flag2)
func()
Meanwhile, I found an answer by adding another level of indirection.
I want to share it here if it is of interest for someone else.
Object state is maintained as every invokation of a flag creates a new instance from the current instance by setting an additional flag.
If we attempt to access an undefined flag an exception is raised (not shown).
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
class FlagHelper:
def __init__(self, cls, value = 0):
self._cls = cls
self._flags = self._cls(value)
def __getattr__(self, item):
if item in self._cls.__members__:
return self.__class__(self._flags | getattr(self._cls, item))
getattr(self._cls, item) # Let attribute error pass through
def __str__(self):
return str(self._flags.value)
class FuncFlags(FlagHelper):
def __init__(self, value = 0):
super().__init__(AvailableFlags, value)
def func(setup_flags: FuncFlags):
print(setup_flags)
if __name__ == "__main__":
ff = FuncFlags()
func(ff.flag1)
func(ff.flag2)
func(ff.flag1.flag2)
func(ff)
Output:
1
2
3
0

Using descriptor causes Recursion Error: maximum recursion depth

Why does the usage of this descriptor cause Recursion Error?
class Capitalized:
def __set__(self, instance, value):
instance.name = value.upper()
class Person(object):
name = Capitalized()
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'{self.name} is {self.age} yr(s) old'
Person('dave', 25) # !Error
I get the following error:
RecursionError: maximum recursion depth exceeded while calling a Python object
However, if I don't use name = Capitalized(), everything is fine (well, except that I can't use the descriptor). I am using python v3.9.1.
You are constructing your classes in a way, so that __set__ is calling itself again and again. instance.name = value.upper() is calling Capitalized.__set__
To avoid this you may use a private attribute like this:
class Capitalized:
def __set__(self, instance, value):
print('setting')
instance._name = value.upper()
def __get__(self, instance, objtype=None):
return instance._name
Change instance._name to instance.name and you will see the infinite recursion.

How to work with a python collections.deque of custom class instances?

I am trying to utilize python deque from collections module where the element inside the deque is a custom class instances. I want to know how I can erase/delete an object? Can I use the builtin methods like deque.remove(element) if yes, how? How would it find my custom object?
class Buffer(object):
""" """
def __init__(self, name, size_total, size_in_cache):
self.name = name
self.size_total = size_total
class Storage(object):
"""
"""
def __init__(self, capacity):
self.CAPACITY = capacity
self.contents = collections.deque()
self.capacity_used = 0
def push_to_contents(self, buffer_name, buffer_size):
buf = Buffer(buffer_name, buffer_size)
self.contents.appendleft(buf)
def delete_from_contents(self, buffer_name)
""" HOW??
How can I use self.contents.remove() here>
"""
The way collections.deque.remove operates is by comparing the argument to each item in the deque. If it finds something which is equal to the argument, it removes it. Otherwise, it raises a ValueError.
Since a Buffer object, as you've implemented it, doesn't know how to compare itself with other objects, Python defaults (using the object parent class) to comparing the id values.
However, if you were to implement the __eq__ method for your class, you could accomplish what you're looking for.
E.g.,
def __eq__(self, other):
if isinstance(other, Buffer):
return self.name == other.name and self.size_total == other.size_total
elif isinstance(other, str):
return self.name == other
else:
return NotImplemented
EDIT:
This is all fine and good if you're using Python 3. In Python 2, you have to implement __ne__ ("not equal") as well. It can be as simple as
def __ne__(self, other):
return not self == other
Python 3 takes care of this for you automatically.

call a method of a class in another method in that same class in python

how i can call a method in a class to another method in that same class in python3?
class foo
def method1(self):
return something
def method2(self):
print(method1())
my actual code is :
class MSD:
#it find maximum shared divisible of two number
def __init__(self,firstNumber1,secondNumber1):
self.firstNumber=firstNumber1
self.secondNumber=secondNumber1
def alldivisible(self):
__all_divisible_list1 =[]
__all_divisible_list2=[]
for i in range(1, int(self.firstNumber)+1):
if self.firstNumber % i == 0:
__all_divisible_list1 = __all_divisible_list1+[i]
for i in range(1, int(self.secondNumber)+1):
if self.secondNumber % i == 0:
__all_divisible_list2 = __all_divisible_list2 + [i]
common_divisible_list = set(__all_divisible_list1) & set(__all_divisible_list2)
return max(common_divisible_list)
class fractionStuff:
def __init__(self,first_fraction1,secound_fraction1):
self.firstFraction=((first_fraction1)).split("/")
self.secoundFraction=((secound_fraction1).split('/'))
def sumCalculate(self):
print()#HERE
here i wanna find divisible of two numbers which i wanna define.
what i must do? i need write my function out of class?
The self reference is required:
class Foo:
def method1(self):
return "something"
def method2(self):
print(self.method1())
All access to the members of a class is through the self parameter. That's not just attribute variables, it's methods as well.
print(self.method1())

Resources