You cannot eval
assignments, eval
is basically just for evaluating things normally found on the right of an assignment statement.
You probably should be using exec
for this, provided you understand and mitigate the risks. For example, see the following code, loosely based on yours:
path = r'C:\Users\Boyon\Desktop\PhotoFile'
image = 'photo01.tif'
x = 1
exec('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
print('EXEC', A1, '\n')
x = 2
A1 = eval(r"str(path)+'\\'+str(image)+str(x)")
print('EVAL1', A1, '\n')
x = 3
eval('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
print('EVAL2', A1, '\n')
The first call, exec
, will work, and set the global A1
. The second will also work because you're not attempting an assignment. The third will fail:
EXEC C:\Users\Boyon\Desktop\PhotoFile\photo01.tif
EVAL1 C:\Users\Boyon\Desktop\PhotoFile\photo01.tif2
Traceback (most recent call last):
File "testprog.py", line 13, in <module>
eval('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
File "<string>", line 1
A3 = r"C:\Users\Boyon\Desktop\PhotoFile\photo01.tif"
^
SyntaxError: invalid syntax
Just keep in mind you can't use exec
to set local variables inside a function, see here for details but it's basically caused by the fact that the locals
dictionary passed by default to exec
is a copy of the actual locals (a dictionary built for heavily optimised internal structures).
However, you can pass your own dictionary to exec
to be treated as the locals and then use that to get at the variables that were set - there's just no easy way (or any way, really) to echo that back to the actual locals.
The following code shows how to do this:
path = '/tmp/PhotoFile'
image = 'photo01.tif'
# Construct dictionary to take "locals".
mydict = {}
for i in range(10):
exec(f"a{i} = '{path}/photo{9-i:02d}'", globals(), mydict)
# Show how to get at them.
for key in mydict:
print(f"My dictionary: variable '{key}' is '{mydict[key]}'")
And the output is:
My dictionary: variable 'a0' is '/tmp/PhotoFile/photo09'
My dictionary: variable 'a1' is '/tmp/PhotoFile/photo08'
My dictionary: variable 'a2' is '/tmp/PhotoFile/photo07'
My dictionary: variable 'a3' is '/tmp/PhotoFile/photo06'
My dictionary: variable 'a4' is '/tmp/PhotoFile/photo05'
My dictionary: variable 'a5' is '/tmp/PhotoFile/photo04'
My dictionary: variable 'a6' is '/tmp/PhotoFile/photo03'
My dictionary: variable 'a7' is '/tmp/PhotoFile/photo02'
My dictionary: variable 'a8' is '/tmp/PhotoFile/photo01'
My dictionary: variable 'a9' is '/tmp/PhotoFile/photo00'