Is there a way to create multiple objects with generic names per function in python 3.8.6

Viewed 175

So for context: I'm trying to create a simple chess program in python with pygame (2.0.0). Since I don't want to create every single of the 64 tiles manually I am looking for a way to create them using a function. Since in chess tiles are named from a1 to h8 (files and ranks) I want the objects to have this kind of names (a1, a2,...). The tile-class is until now very simple:

class tile: 

    def __init__(self):
        self.piece = None

Then I made two lists: one for the files and one for the ranks. Then two for-loops (one in another) so that for every single combination it would create a tile-object:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']

for f in files:
    for r in ranks:
        f + r = tile()

Now my problem: python doesn't allow this ;( I want to create 64 tile-objects with names from a1 to h8. Is there any way for this?

2 Answers

While it is technically possible, I would heavily advise against manipulating variable scopes dynamically. The "intended" way of doing this is using a dictionary:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']

tiles = {}

for f in files:
    for r in ranks:
        tiles[f + r] = tile()

You can then access e.g. tile E4 through tiles["e4"].

It would make sense to store these tiles in a dict:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
tiles = {f'{file}{rank}': tile() for file in files for rank in ranks}

Another way would be to create a Chessboard class:

class Chessboard:
    def __init__(self, files, ranks):
        for file in files:
            for rank in ranks:
                setattr(self, f'{file}{rank}', tile())
                
                
chessboard = Chessboard(files, ranks)
Related