<s> from django . utils . functional import cached_property <EOL> import sellmo . apps . customer as _customer <EOL> NO_DEFAULT = object ( ) <EOL> class AddressHelper ( object ) : <EOL> _mutated_addresses = None <EOL> def __init__ ( self , obj , fk ) : <EOL> self . _obj = obj <EOL> self . _fk = fk <EOL> @ cached_property <EOL> def _addresses_queryset ( self ) : <EOL> return _customer . models . Address . objects . filter ( ** { self . _fk : self . _obj } ) <EOL> def get ( self , address_type , default = NO_DEFAULT ) : <EOL> try : <EOL> return self [ address_type ] <EOL> except KeyError : <EOL> if default is not NO_DEFAULT : <EOL> return default <EOL> raise <EOL> def __getitem__ ( self , address_type ) : <EOL> address = None <EOL> if self . _mutated_addresses is not None : <EOL> address = self . _mutated_addresses . get ( address_type , None ) <EOL> else : <EOL> try : <EOL> address = self . _addresses_queryset . get ( <EOL> address_type = address_type ) <EOL> except self . _addresses_queryset . model . DoesNotExist : <EOL> pass <EOL> if address is None : <EOL> raise KeyError ( address_type ) <EOL> return address <EOL> def __setitem__ ( self , address_type , value ) : <EOL> if self . _mutated_addresses is None : <EOL> self . _mutated_addresses = { <EOL> address . address_type : address <EOL> for address in self . _addresses_queryset <EOL> } <EOL> value . address_type = address_type <EOL> self . _mutated_addresses [ address_type ] = value <EOL> def __delitem__ ( self , address_type ) : <EOL> if self . _mutated_addresses is None : <EOL> self . _mutated_addresses = { <EOL> address . address_type : address <EOL> for address in self . _addresses_queryset <EOL> } <EOL> del self . _mutated_addresses [ address_type ] <EOL> def __contains__ ( self , address_type ) : <EOL> if self . _mutated_addresses is not None : <EOL> return address_type in self . _mutated_addresses <EOL> else : <EOL> return self . _addresses_queryset . filter ( <EOL> address_type = address_type ) . count ( ) == <NUM_LIT:1> <EOL> def __iter__ ( self ) : <EOL> addresses = self . _addresses_queryset <EOL> if self . _mutated_addresses is not None : <EOL> addresses = self . _mutated_addresses . values ( ) <EOL> for address in addresses : <EOL> yield address <EOL> def __len__ ( self ) : <EOL> if self . _mutated_addresses is not None : <EOL> return len ( self . _mutated_addresses ) <EOL> else : <EOL> return self . _addresses_queryset . count ( ) <EOL> def save_or_delete_addresses ( self ) : <EOL> if self . _mutated_addresses is not None : <EOL> for address in self . _mutated_addresses . values ( ) : <EOL> setattr ( address , self . _fk , self . _obj ) <EOL> address . save ( ) <EOL> stale = self . _addresses_queryset . exclude ( <EOL> pk__in = [ <EOL> address . pk for address in self . _mutated_addresses . values ( ) <EOL> ] <EOL> ) <EOL> stale . delete ( ) <EOL> self . _mutated_addresses = None <EOL> try : <EOL> del self . _addresses_queryset <EOL> except AttributeError : <EOL> pass </s>
