Python 3.2.1: exec ('x = y ()') sets the value in the toy example, but not in the full code

I use the exec () operator to set the value, for example:

foo = 3
def return_4():
    return 4
instruction = 'foo = return_4()'
exec(instruction)                     # <---- WHERE THE MAGIC HAPPENS
print(foo)

It looks like 4 as I expect.

My program has operations for manipulating a Rubik cube. In this stripped-down version, I will do four things:

  • I will create a cube by filling one face (with the abbreviations "front upper left" and "front lower right", etc.).

  • I will have a function that rotates this face.

  • I will have an interpreter function that takes a cube and a list of instructions, and applies these instructions to the cube, returning the modified cube. Here, where I use "exec" (and where I think a break occurs).

  • Finally, I launched the interpreter on my partial cube with instructions for turning the face once.

+

my_cube = [['FTL', 'FTM', 'FTR',
            'FML', 'FMM', 'FMR',
            'FBL', 'FBM', 'FBR'],
            [],[],[],[],[]] # other faces specified in actual code

def rotate_front(cube):
    front = cube[0]
    new_front = [front[6],front[3],front[0],
                 front[7],front[4],front[1],
                 front[8],front[5],front[2]]
    # ...
    ret_cube = cube
    ret_cube[0] = new_front
    # pdb says we are returning a correctly rotated cube,
    # and calling this directly returns the rotated cube
    return ret_cube

def process_algorithm(cube=default_cube, algorithm=[]):
    return_cube = cube
    for instruction in algorithm:
        exec('return_cube = ' + instruction + '(return_cube)')  # <--- NO MAGIC!
        # ACCORDING TO pdb, return_cube HAS NOT BEEN ROTATED!
    return return_cube

process_algorithm(cube = my_cube, algorithm = ['rotate_front'])

exec (x = y) x = eval (y), , , .   return_cube = eval ( + '(return_cube)')

, , . , ? ( - , , ? , ...)

, .

+2
2

Python 2.x, exec - , LOAD_GLOBAL LOAD_FAST LOAD_NAME , . , , , .

, Python 3.x, exec , , , , .

exec(some_code, globals())

global my_var , , .

, ...

, exec eval? algorithm?


, algorithm var , , , .

None .

+5

, , . Python 3.2.2 Windows. . JBernardo "" .

( " " ):

>>> foo = "global-foo"
>>> exec('foo = "global-bar"')
>>> foo
'global-bar'

( ):

>>> def setIt():
        foo = "local-foo"
        exec('foo = "local-bar"')
        return foo

foo = "global-foo"
>>> setIt()
'local-foo'
>>> foo
'global-foo'

globals() ( locals()):

>>> def setIt():
        foo = "local-foo"
        exec('foo = "local-bar"', globals())
        return foo

>>> foo = "global-foo"
>>> setIt()
'local-foo'
>>> foo
'local-bar'

.

+3

All Articles