0

I'm rather new to Python and programming in general, so I apologise in advance if my terminology is incorrect.

hue_alert_delay = 0

def delays(name, delay):
    global hue_alert_delay

    if name == 'hue_alert_delay':
        for i in range(0, delay):
            hue_alert_delay += 1
            time.sleep(1)

        hue_alert_delay = 0

delays('hue_alert_delay', 60)

What I'm trying to achieve:

I would like the function to convert the 'name' parameter, which is a string input, into a pre-exiting variable, which will negate the need for multiple IF statements.

The above example includes only one IF statement, but for my project there will be a lot more and I would rather keep the function clean and simple.

This won't work, but it's what I'm trying to aim for:

hue_alert_delay = 0

def delays(name, delay):
    global name

    for i in range(0, delay):
        name += 1
        time.sleep(1)

    hue_alert_delay = 0

delays('hue_alert_delay', 60)

Any assistance would be appreciated.

0

3 Answers 3

1

Use a dict:

values = {
    'hue_alert_delay': 0
}

def delays(name, delay):
    values[name] += 1

Whenever you feel like using "variable variables", what you most likely really want is a dict storing key-value associations. Yes, there are other ways to do literally what you want, but that soon leads to insane code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much
0

Use a dictionary like so.

vars = {'hue_alert_delay':0}
def delays(name, delay):
  for i in range(0, delay):
      vars[name] += 1
      time.sleep(1)
  vars[name] = 0

You can also use globals()[name] but I won't recommend it.

4 Comments

The global keyword is unnecessary here. You're not trying to reassign to that name at any point. You're just mutating that object.
Thank you very very much, I applied this principle to my project and it worked perfectly.
I'm rather new to forums too :). Should I update the post some how to explain that it's resolved?
@Sparkacus No, you should click on the tick and mark this as the answer if it worked for you.
0

Use a dictionary:

vars = {'hue_alert_delay':0}

def delays(name, delay):
    for i in range(delay):
        vars[name] += 1
        time.sleep(1)

    vars[name] = 0

delays('hue_alert_delay', 60)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.