metersk
metersk

Reputation: 12529

Why is method in class manipulating a __init__ variable

I have this class Record

class Record():
    def __init__(self, record):
        self.state_abbreviations = {'AL': 'Alabama'}
        self.raw_record = record
        self.is_valid = self.validate_record(self.raw_record)
        self.formatted_record = self.format_record(self.raw_record)


    def validate_record(self, record):
        if (record.get('provider_first_name') is None and 
            record.get('provider_last_name_legal_name') is None):
            return False
        return True

    def format_record(self, record):
        # swap state abbreviation for full state name
        record_state = record.get('provider_business_practice_location_address_state_name')
        full_state_name = self.state_abbreviations.get(record_state)
        record['provider_business_practice_location_address_state_name'] = full_state_name

        return record

when I instantiate it:

r = Record({'provider_first_name': 'is', 'provider_last_name_legal_name': 'fake',
            'provider_business_practice_location_address_state_name': 'AL'})

I would expect r.raw_record to give me

{'provider_business_practice_location_address_state_name': 'AL',
 'provider_first_name': 'is',
 'provider_last_name_legal_name': 'fake'}

but the output i am getting is:

{'provider_business_practice_location_address_state_name': 'Alabama',
 'provider_first_name': 'is',
 'provider_last_name_legal_name': 'fake'}

I'm confused on why the raw record is being manipulated by the format_record function.

Upvotes: 0

Views: 60

Answers (1)

damores
damores

Reputation: 2351

The dictionary you're passing to the Record constructor is being referenced by self.raw_record, which is in turn passed to the format_record method and modified there. In all those parts you're manipulating the same object, that's why you see the changes in raw_record.

If you want to avoid this, you could make a copy of the dictionary somewhere. For example, in your constructor:

self.formatted_record = self.format_record(self.raw_record.copy())

Upvotes: 1

Related Questions