-2

I have a function in python with 3 arguments:

def checkmsg(text, type, mac):

and the type and mac are 2 variables that i pass, type can be Alarms or Warnings, and mac: 1 or 2 so i need to store the text element (it can be a single element or an array) in a status variable (i have 4 variables in a class)

status.Alarms1, status.Alarms2, status.Warnings1, status.Warnings2

so i need first to check if the text element is the same as the one in the status, if different do something and then store it, so my questions are how can i access to the content and than update the content of the status variable having to choose it from the 2 variable passed to the function ?

P.S. (I can change the structure of the status 4 variable if it helps)

Alexander Pivovarov
  • 4,850
  • 1
  • 11
  • 34
Darkmagister
  • 53
  • 1
  • 6

1 Answers1

1

Answering your question directly:

from dataclasses import dataclass


@dataclass
class Status:
    Alarms1: str
    Alarms2: str
    Warnings1: str
    Warnings2: str


status = Status(Alarms1="", Alarms2="", Warnings1="", Warnings2="")

def checkmsg(text, type_, mac):
    var = f"{type_}{mac}"
    old_text = getattr(status, var)
    if text != old_text:
        print(f"Setting {text} as new value of {var}")
        setattr(status, var, text)
    else:
        print(f"{var} is already set to {text}")

checkmsg("whatever", "Warnings", 1)
checkmsg("whatever more", "Alarms", 2)
checkmsg("whatever again", "Warnings", 1)
checkmsg("whatever more", "Alarms", 2)

And when run, it'll print

Setting whatever as new value of Warnings1
Setting whatever more as new value of Alarms2
Setting whatever again as new value of Warnings1
Alarms2 is already set to whatever more

However, DO NOT DO THIS. This is black magic you don't need. Use dictionary to store your status.

avysk
  • 1,973
  • 12
  • 18