Thursday 16 September 2021

How to convert Nonetype to int or string?

 int(value or 0)


from: https://stackoverflow.com/questions/3930188/how-to-convert-nonetype-to-int-or-string

how to dynamically create an instance of a class in python?

 all you will need to do is

klass = globals()["class_name"]
instance = klass()


from: https://stackoverflow.com/questions/3451779/how-to-dynamically-create-an-instance-of-a-class-in-python

Python mock multiple return values

Answer #1:

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'


from: https://www.py4u.net/discuss/16628 

Monday 13 September 2021

Check if a given key already exists in a dictionary and increment it

 I prefer to do this in one line of code.

my_dict = {}

my_dict[some_key] = my_dict.get(some_key, 0) + 1


from: https://stackoverflow.com/questions/473099/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it