Created
July 3, 2020 19:50
-
-
Save rayansostenes/a684d588ab598466172113c3c55f0fbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class lazy_loading_property: | |
attr_name: str | |
method_name: str | |
def __init__(self, method_name): | |
self.method_name = method_name | |
def __set_name__(self, owner, name): | |
if not hasattr(owner, self.method_name): | |
raise TypeError(f'method {self.method_name} does not exists') | |
elif not callable(getattr(owner, self.method_name)): | |
raise TypeError(f'{self.method_name} is not callable') | |
self.attr_name = name | |
def load_data(self, instance): | |
if not getattr(instance, f'_{self.method_name}_called', False): | |
getattr(instance, self.method_name)() | |
setattr(instance, f'_{self.method_name}_called', True) | |
def __get__(self, instance=None, owner=None): | |
if instance is None: | |
return self | |
self.load_data(instance) | |
return instance.__dict__[self.attr_name] | |
def __set__(self, instance=None, value=None): | |
if instance is None: | |
raise AttributeError('Cannot modify class only instances') | |
instance.__dict__[self.attr_name] = value | |
class Person: | |
name = lazy_loading_property('load_db_a') | |
address = lazy_loading_property('load_db_b') | |
def __init__(self, cpf): | |
self.cpf = cpf | |
def load_db_a(self): | |
print('load_db_a was called') | |
self.name = 'Meu nome' | |
def load_db_b(self): | |
print('load_db_b was called') | |
self.address = 'This is my addres' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment