Friday 26 November 2021

typing.Callable

 

Callable type; Callable[[int], str] is a function of (int) -> str.

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType. A plain Callable is equivalent to Callable[..., Any], and in turn to collections.abc.Callable.

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

Deprecated since version 3.9: collections.abc.Callable now supports []. See PEP 585 and Generic Alias Type.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate. See PEP 612 for more information.

 

from:  https://docs.python.org/3/library/typing.html#typing.Callable

Tuesday 23 November 2021

Python - object MagicMock can't be used in 'await' expression

 You can get mocks to return objects that can be awaited by using a Future. The following is a pytest test case, but something similar should be possible with unittest.

async def test_that_mock_can_be_awaited():
    mock = MagicMock(return_value=Future())
    mock.return_value.set_result(123)
    result = await mock()
    assert result == 123

In your case, since you're patching Service (which gets passed in as mock), mock.return_value = Future() should do the trick.


from: https://stackoverflow.com/questions/51394411/python-object-magicmock-cant-be-used-in-await-expression

Friday 15 October 2021

partial string formatting

 s = '{foo} {bar}'

s.format(foo='FOO', bar='{bar}')


from: https://stackoverflow.com/questions/11283961/partial-string-formatting

Saturday 9 October 2021

How to check if one dictionary is a subset of another larger dictionary?

 

In Python 3, you can use dict.items() to get a set-like view of the dict items. You can then use the <= operator to test if one view is a "subset" of the other:

d1.items() <= d2.items()

In Python 2.7, use the dict.viewitems() to do the same:

d1.viewitems() <= d2.viewitems()

In Python 2.6 and below you will need a different solution, such as using all():

all(key in d2 and d2[key] == d1[key] for key in d1)

 

from:  https://stackoverflow.com/questions/9323749/how-to-check-if-one-dictionary-is-a-subset-of-another-larger-dictionary

Friday 1 October 2021

Sort JSON object using json.dumps()

 # Import the JSON module

import json

# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": 100},
            {"name": "Monitor", "brand": "Dell", "price": 120},
            {"name": "Mouse", "brand": "Logitech", "price": 10}]

# Read and print the original data
print("The original data:\n{0}".format(products))
# Convert into the JSON object after sorting
sorted_json_data = json.dumps(products, sort_keys=True)
# Print the sorted JSON data
print("The sorted JSON data based on the keys:\n{0}".format(sorted_json_data))


from: https://linuxhint.com/sort-json-objects-python/

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

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

Thursday 10 June 2021

mock any type = mock.ANY

 mock.ANY

Asserting successive calls to a mock method

 >>> from unittest.mock import call, Mock

>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)


from: https://stackoverflow.com/questions/7242433/asserting-successive-calls-to-a-mock-method

Wednesday 2 June 2021

Set nested dict value and create intermediate keys

 from collections import defaultdict

recursivedict = lambda: defaultdict(recursivedict)
mydict = recursivedict()


from: https://stackoverflow.com/questions/10218486/set-nested-dict-value-and-create-intermediate-keys

Monday 10 May 2021

Singleton pattern and factory pattern of common Python design patterns

 

1. Singleton mode

Singleton pattern (Singleton Pattern) is a commonly used software design pattern, the main purpose of this pattern is to ensure that only one instance of a class exists. When you want to have only one instance of a class in the entire system, singleton objects can come in handy.
For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the content of the configuration file needs to be used in many places during the running of the program, that is to say, many instances of AppConfig objects need to be created, which results in the existence of multiple AppConfig instance objects in the system, which will seriously waste memory Resources, especially if the configuration file has a lot of content. In fact, for a class like AppConfig, we want only one instance object to exist during the running of the program. Note: Importing modules in python is a singleton mode.

Exercise: Create a Sun class

class Sun(object):
    #Define a variable
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            #If __instance has no value, assign a value to the __instance variable
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            #If __instance has a value, return directly.
            return cls.__instance

sun = Sun()
print(id(sun))#2185130970304
sun1=Sun()
print(id(sun1))#2185130970304
#sun and sun1 have the same id value
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Second, the factory model

Factory pattern is a design pattern used to create objects in software development.
When a "type" is input when the program is run, the corresponding object needs to be created here. This uses the factory model. In such a situation, the implementation code is based on the factory pattern, which can achieve scalable and maintainable code. When adding a new type, it is no longer necessary to modify the existing class, only adding subclasses that can generate a new type.
Use factory mode application scenario: You can use factory mode when you don’t know what kind of object the user wants to create.
example:

class Car(object):

    def run(self):
        print('Running rubbing')

    def stop(self):
        print('Wooing parking')

class BMW(Car):

    def run(self):
        print('BMW--->>Running)

    def stop(self):
        print('BMW---Wooing parking')

class Benz(Car):
    def run(self):
        print('Mercedes--->>Running)

    def stop(self):
        print('Mercedes--->>Wooing parking')

class Skoda(Car):
    def run(self):
        print('Skoda--->>Running)

    def stop(self):
        print('Skoda --->>Wooing parking')

class CarFactory(object):

    def new_car(self,name):

        if name == 'BMW':
            bmw = BMW()
            return bmw

        if name == 'Benz':
            benz = Benz()
            return benz

        if name == 'skd':
            return Skoda()

class CarStore(object):
    def __init__(self,factory):
        self.factory=factory

    def order(self,name):
        new_car=self.factory.new_car(name)
        return new_car
        
car_factory=CarFactory()
car_store=CarStore(car_factory)
car= car_store.order('skd')
car.run()
car.stop()


from: https://www.programmersought.com/article/66934024946/