[Answered ]-Is it possible for a Python mixin to access a global variable?

2👍

Realizing that APILoggingMixin.finalize_response takes self which is a CategoryDetail instance, we could attach logger to CategoryDetail

class CategoryDetail(...):
    logger = logger

class APILoggingMixin(object):
    def finalize_response(self, ...):
        self.logger.info('Some message.')

# Or through get_logger()
class CategoryDetail(...):
    def get_logger(self):
        return logger

class APILoggingMixin(object):
    def finalize_response(self, ...):
        self.get_logger().info('Some message.')

    def get_logger(self):
        raise NotImplementedError

# Or take advantage of the fact that `self.__module__` equals to `__name__` in the module of `CategoryDetail`
class APILoggingMixin(object):
    def finalize_response(self, ...):
        logger = logging.getLogger(self.__module__)
        logger.info('Some message.')
👤okm

Leave a comment