Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically select and pass named parameters in Python?

Tags:

python

payload is a comma separated chunk of data that represents the readings from an inverter. These readings need to be stored in a table called InverterHistory. There will not always be a value for each field. The model already has been setup to allow null/blank for the fields. So I am trying to check to see if there is a value present before assigning it to a field. Here is what I have so far:

i = Inverter.objects.get(mac=u)
payload.reverse()

try:
    ac_volts_a = str(payload.pop())
    ac_volts_b = str(payload.pop())
    ac_volts_c = str(payload.pop())
    ac_current_a = str(payload.pop())
    ac_current_b = str(payload.pop())
    ac_current_c = str(payload.pop())
    dc_volts = str(payload.pop())
    dc_current = str(payload.pop())
    kw_out = str(payload.pop())
    mwh_total = str(payload.pop())
    current_time  = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")

    i_data = InverterHistory(
        inverter = i,
        if ac_volts_a: 
            voltage_ac_a = float(ac_volts_a),
        if ac_volts_b: 
            voltage_ac_b = float(ac_volts_b),   
        if ac_volts_c: 
            voltage_ac_c = float(ac_volts_c),
        if ac_current_a: 
            current_ac_a = float(ac_current_a), 
        if ac_current_b: 
            current_ac_b = float(ac_current_b),
        if ac_current_c: 
            current_ac_c = float(ac_current_c),
        if dc_volts: 
            voltage_dc = float(dc_volts),   
        if dc_current: 
            current_dc = float(dc_current), 
        if kw_out: 
            kwout = float(kw_out),
        if mwh_total: 
            mwh = float(mwh_total),
        recordTime  = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
    i_data.save()
except Exception, e:
    print >> sys.stderr, "Error While Recording Inverter History"
    print >> sys.stderr, e
    raise Http404

I am fairly new to python and don't know how to properly code the above. When I try to compile the code I am getting an error where the if statements start. How can i fix the above code so it will compile and work as desired?

like image 608
Linger Avatar asked Dec 15 '22 21:12

Linger


1 Answers

When you write i_data = InverterHistory(...), you are creating an object of type InverterHistory and the ... are the parameters you pass to the constructor. Constructing an object in Python is like calling a function or a method and you cannot put logic inside the parenthesis. So, you are getting an error because it is incorrect syntax to put an if statement there.

What you need to do is move your logic out of the parenthesis and put all your variables inside a Python dict. You can then pass that dict as parameter to your call to InverterHistory.

params = {
    'inverter': i,
    'recordTime': datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
}
if ac_volts_a:
    params['voltage_ac_a'] = float(ac_volts_a)
if ac_volts_b: 
    params['voltage_ac_b'] = float(ac_volts_b)

# Do the same with all your attributes
# ...

# Then you can create your object and pass it the dictionary you have created
i_data = InverterHistory(**params)

The **params unpacks the dictionary. This means that the interpreter will take all the key: value from the dictionary and turn them into key=value. This way, each param for which the if statement was True will be passed as a named parameter to InverterHistory

like image 199
Rodrigue Avatar answered Mar 04 '23 21:03

Rodrigue