0
import json
# import Adafruit_DHT

CONFIG_FILE = "config.json"

class Config():
    def __init__(self):
        with open(CONFIG_FILE) as config_file:
            self.config_data = json.load(config_file)
            locals().update(self.config_data)
            print(Sensor_DHT11_PIN)

    def get(self, key):
        return self.config_data[key]

def Main ():
    var = Config()
    print(var.get("Sensor_DHT11_PIN"))

if __name__ == '__main__':
    Main()

#ERROR MESSAGE:

#$ python loadconfig.py
#4
#Traceback (most recent call last):
 # File "loadconfig.py", line 23, in <module>
  #  Main()
  #File "loadconfig.py", line 20, in Main
   # print(Sensor_DHT11_PIN)
#NameError: name 'Sensor_DHT11_PIN' is not defined

I want to be able to call a particular key from the dictionary and obtain that value, using the dictionary key as a variable, but when I run the function. I obtain the value trough the "get" function of the Config class but no as a varible drawn out of the dicitonary:

How can I make this possible?

glibdud
  • 7,550
  • 4
  • 27
  • 37
dpuIX
  • 13
  • 2
  • This `json.loads(config_file)`? (**loads**) – shaik moeed Oct 18 '19 at 12:48
  • 1
    Note that the [documentation](https://docs.python.org/3/library/functions.html#locals) indicates that the result of `locals()` should not be changed. – glibdud Oct 18 '19 at 12:53
  • The error is not with the `get()` method, but in the print statement inside `__init__()`. Can you please clarify why you use `locals()` there? – Moshe perez Oct 18 '19 at 12:54
  • the print statement inside init is simply checking if i can call the varible and obtain the value, which i cannot... but if i try that locals method on a dictionary in the python environment it works perfectly – dpuIX Oct 18 '19 at 13:27
  • i pulled that code from this... https://stackoverflow.com/questions/18090672/convert-dictionary-entries-into-variables-python but the difference is that i want to mantain the same name of the dictionary keys – dpuIX Oct 18 '19 at 13:29

0 Answers0