Stefatronik
Stefatronik

Reputation: 332

Did I copy the class instance or the class handler here?

I want to sort class handlers by class properties. First I generate a list of class handlers, the following 5 lines are processed in a while loop.

# here a serial no was entered and validity checked
if snr_ok == True:
    device_list.append(Device(snr, prop_list))
    logging.info ("Added serial number " + snr + " with properties " + prop_list)
else: 
    pass
    
    """Group all instances of by property (which is a gas type)"""    
    calibration_gases = {'He':[], 'O2':[], 'N':[], 'Ar':[]}                    
    for gas in list(calibration_gases):
        for dev in device_list:
            if gas in dev.get_gaslist(): # get_gaslist returns a list of strings with some of the gases
                calibration_gases[gas].**append(dev)**
    print (calibration_gases)

By grouping the dev elements by gas type I add them to the calibration_gases dict. My question is: Is dev a copy of the class instance or is it a copy of the class handler? Or spoken in C: Is dev a pointer to the class instance or is it a copy of the class itself?

Upvotes: 0

Views: 57

Answers (1)

Jasmijn
Jasmijn

Reputation: 10452

Neither. Python doesn't have a call-by-value/call-by-reference distinction, instead using a call-by-object-identity paradigm. Unless you're explicitly copying something (for example using slicing, obj.copy() or copy.deepcopy), it doesn't happen.

What gets added to calibration_gases[gas] is the same object that can be found in device_list.

By the way, instead of for gas in list(calibration_gases): you could simply do for gas in calibration_gases:. Even better, you could do:

for gas, devices in calibration_gases.items():
    for dev in device_list:
        if gas in dev.get_gaslist():
            devices.append(dev)

Upvotes: 1

Related Questions