Search code examples
pythonclassobjectencapsulation

Object is not being defined outside the loop in python


import json

xyz={"john": """{"name": "john","id":"123"}""","tom" : """{"name":"tom","id":"456"}"""}

class abc(object):
  def __init__ (self,**d):
    self.name=d['name'];
    self.id=d['id'];

def main():
   ks=xyz.keys()
   for j in ks:
      lm1="xyz['%s']" %(j)
      ds=eval(lm1);
      ds1=json.loads(ds)
      ln="%s=abc(**ds1)" %(j)
      print(ln)
      exec(ln);
      ln2="%s.name" %(j)
      print(eval(ln2));
   print(john.name)
   print(tom.id)

if __name__ == "__main__":
   main();

and the error is

tom=abc(**ds1)
tom
john=abc(**ds1)
john
Traceback (most recent call last):
  File "new6.py", line 26, in <module>
    main();
  File "new6.py", line 22, in main
    print(john.name)
NameError: name 'john' is not defined

why am i not being able to access "tom.name","john.name" in main() block? where did i do wrong? and how can it be done in much simpler way? (i actually have a json file, dont bother much about the "xyz")


Solution

  • The behavior of this program is different between Python2.* and Python3*.

    1.) xyz.keys() gives a list in Python2.7, but needs to be cast from the dict_keys class to a list in Python3.6.

    2.) The behavior of exec is different between Python2.* and Python3.* See here for more details. Because of this, if you're running your program with Python3, john and tom haven't been defined, and you get an error when trying to access them.