Home > Enterprise >  Syntax error with exec call to an object in Python 3
Syntax error with exec call to an object in Python 3

Time:02-02

I really don't understand what causes the problem, could someone point it out for me please?

with shelve.open(obj_path) as obj:
    for as_num in obj['as_number_list']:  # ignore warning, obj['as_number_list'] is a list
        temp = charge_as(obj['as_'   str(as_num)])  # temp is an object
        as_test = temp  # doing like this is ok
        print(type(as_test))
        exec("as_{}_obj = {}".format(as_num, temp))  # **error here**

And it gives syntax error like this:

<class 'instruments.AS'>
Traceback (most recent call last):
  File "...", line 45, in <module>
    exec("as_{}_obj = {}".format(as_num, temp))
  File "<string>", line 1
    as_1_obj = <instruments.AS object at 0x000002A86732E290>
               ^
SyntaxError: invalid syntax

I tried

exec("as_{}_obj = {}".format(as_num, temp.__dict__))

no error is shown but now as_{}_obj is of class 'dict' instead of class 'instruments.AS'

CodePudding user response:

line 45: exec("as_{}_obj = temp".format(as_num))

  • Related