2

Looks like I'm either missing something basic or something complicated. I want to store and use a callable as a class variable in a base class to redefine it in subclasses.

from core.singleton import Singleton

import yaml


class Item:
    def __init__(self, arg1, arg2):
        self.a = arg1
        self.b = arg2

    @staticmethod
    def from_yaml(id, data):
        # some complicated logic to calculate arguments
        return Item(arg1, arg2)


class BaseDatabase(metaclass=Singleton):
    filename = None
    item_class_factory = None

    def __init__(self):
        # do some checks
        with open(self.filename) as f:
            self._data = yaml.load(f, yaml.Loader)

    def find(self, id):
        if id in self._data:
            # the line below generates ```TypeError: from_yaml() takes 2 positional arguments but 3 were given```
            return self.item_class_factory(id, self._data[id])  


class ItemDatabase(BaseDatabase):
    filename = 'data/itemsA.yaml'
    item_class_factory = Item.from_yaml


class AnotherDatabase(BaseDatabase):
    filename = 'data/itemsB.yaml'
    item_class_factory = Item.from_yaml

    def find_by_name(self, name):
        # some extended logic
    

What am I doing wrong? When I try to execute this code I get Type Error about one extra argument passed to the factory method I'm trying to store in a class variable. Evidently, self is being passed to. How to avoid it?

Oleg Titov
  • 1,100
  • 1
  • 8
  • 13

0 Answers0