0

I am working on a system to pass through the functionality of the GPIO pins on a Raspberry Pi to a Java program and I am running into an issue with GPIOzero. To properly reference the GPIO pins, I need to dynamically create and access the variables attached to the GPIO pins. I found this piece of code to create the variable dynamically, but nothing I search for seems to be able to call the variable dynamically too.

    globals()[f"my_variable{i}"] = f"Hello from variable number {i}!"
    
print(my_variable3)
# Hello from variable number 3!

Ideally, instead of the print statement just printing a certain variable, it would be able to print any variable based off of a value, something sort of like this:

x = 3
print(my_variable{x})

Thanks for your help!

1 Answers1

1

You might want to do that with the same tool you use to set it. Here is an example:

i = 5

# Dynamic definition.
globals()[f"my_variable{i}"] = "Nice variable you got here!"

# Dynamic read.
print(globals()[f"my_variable{i}"])

cfgn
  • 201
  • 2
  • 10