dependencies icon indicating copy to clipboard operation
dependencies copied to clipboard

Shortcut syntax for pluck object.

Open proofit404 opened this issue 5 years ago • 0 comments

Supersedes #289

@attrs
class Book:
    title = attrib()
    author = attrib()

    def is_written_by(self, writer):
        return self.author == writer


@attrs
class LoggedBook:
    book = attrib()
    logger = attrib()

    def is_written_by(self, writer):
        self.logger.debug('Arguments: %s', writer)
        result = self.book.is_written_by(writer)
        self.logger.debug('Result: %s', result)
        return result


@attrs
class CachedBook:
    book = attrib()
    cache = {}

    def is_written_by(self, writer):
        if writer not in self.cache:
            self.cache[writer] = self.book.is_written_by(writer)
        return self.cache[writer]

Regular syntax to express such relation would be:

from dependencies import Injector, pluck

class Container(Injector):
    book = pluck(CachedBook, book=pluck(LoggedBook, book=Book))
    logger = Logger
    title = 'foo'
    author = 'bar'

However, requirement to repeat book= and nested pluck with high nesting would be tedious. So we could suggest short syntax for such simple cases.

from dependencies import Injector, pluck

class Container(Injector):
    book = pluck(CachedBook, LoggedBook, Book)
    logger = Logger
    title = 'foo'
    author = 'bar'

So, we will have the same short syntax as in decorate object proposal. But without limitation discussed in the original issue. Ability to use nested pluck objects with a different keyword arguments would solve the problem.

proofit404 avatar Feb 19 '21 13:02 proofit404