Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

factory pattern with lambda

How would you create a factory based method using lambda?

function signature looks like this. Factory gets a string parameter and returns the instance.

class Foo:

    @abstractmethod
    def store(factory: Callable[[str], Bar])
       obj = factory("abc") // store or call to get instance


class Bar:
    def __init__(self):
        pass

How to call this method using lambda?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Foo.store(lambda k: Bar(k))

Error

Parameter ‘factory’ unfilled

>Solution :

Since store() is called on the class, not an instance, it needs to be declared as a static method.

class Foo:

    @staticmethod
    def store(factory: Callable[[str], Bar]):
        obj = factory("abc")  # store or call to get instance

Otherwise, it’s expected to be called on an instance, and the first argument should be self, which receives the instance.

Also, obj is just a local variable. If you want this to persist, you need to use Foo.obj.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading