Thursday, 16 September 2021

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

Friday, 13 August 2021

Getting the class name of an instance?

 Do you want the name of the class as a string?

instance.__class__.__name__


from: https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance

madzak / python-json-logger

 

Overview

This library is provided to allow standard python logging to output log data as json objects. With JSON we can make our logs more readable by machines and we can stop writing custom parsers for syslog type records.


from: https://github.com/madzak/python-json-logger#using-a-config-file

Saturday, 24 July 2021

Concatenate inputs in string while in loop

 SOURCES="a b c d e"

DESTINATIONS=""

for src in $SOURCES
do
    echo Input destination to associate to the source $src:
    read dest
    DESTINATIONS+=" ${dest}"
done
echo $DESTINATIONS


from: https://stackoverflow.com/questions/42934198/concatenate-inputs-in-string-while-in-loop

How to split a list by comma not space

sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; done
Hello
World
Questions
Answers
bash shell
script 

sorin@sorin:~$  


from: https://stackoverflow.com/questions/7718307/how-to-split-a-list-by-comma-not-space