Search code examples
pythondynamic-function

Python: exec() and lists of objects


I'm trying to create a dynamic function currently only consisting of the following:

"chosen = random.choice([<ClassLibrary.Field object at 0x0330FA48> , <ClassLibrary.Field object at 0x0330FAA8> , <ClassLibrary.Field object at 0x0330FB08> , <ClassLibrary.Field object at 0x0330FB98> , <ClassLibrary.Field object at 0x0330FC28> , <ClassLibrary.Field object at 0x0330FCB8> , <ClassLibrary.Field object at 0x0330FD48> , <ClassLibrary.Field object at 0x0330FDD8> , <ClassLibrary.Field object at 0x0330FE68>])"

Meaning that I have a variable which is set equal to a random element from the list. However I am getting a syntax error on it, presumably because the list objects are references to those objects' space in memory? choice() works with the original list like so:

chosen = random.choice(ticTacToe.fields)

The error I'm getting is:

  File "C:\Users\churc\Documents\P7\P7 Modular Playtesting\ticTacToe2.py", line 267, in <module>
    eval(FunctionLibrary.makeExecutableStatement(ticTacToe.players[1].actions[0].statements[0]))
  File "<string>", line 1
    chosen = random.choice([<ClassLibrary.Field object at 0x0330FA48> , <ClassLibrary.Field object at 0x0330FAA8> , <ClassLibrary.Field object at 0x0330FB08> , <ClassLibrary.Field object at 0x0330FB98> , <ClassLibrary.Field object at 0x0330FC28> , <ClassLibrary.Field object at 0x0330FCB8> , <ClassLibrary.Field object at 0x0330FD48> , <ClassLibrary.Field object at 0x0330FDD8> , <ClassLibrary.Field object at 0x0330FE68>]) 
           ^
SyntaxError: invalid syntax
[Finished in 0.1s with exit code 1]

Anyone know what I'm doing wrong? And how to correct it?


Solution

  • <ClassLibrary.Field object at 0x0330FA48> is not valid python syntax since it's just an output string for objects instances. There's not enough information to provide a full answer relative to what your code should do, but judging from what you have written I'd suggest to use random.choice() on a list of ClassLibrary.Field instances that you previously declared.

    Example:

    instances_list = [ ClassLibrary.Field() for instance in range(4) ]
    chosen = random.choice(instances_list)