-4

What i want to do is to make a procedural variable name for a pygame draw function inside a for loop. But i just cant figure out how to do it.

I tried to follow some guides that i saw about dynamic names but they only showcased making a variable name for ints and strings.

I want to give all of rectangles their own name with a number at the end to show in what loop they were created. But i do not know how change the name of the variable from one loop to the other

This is the variable i need to name: pygame.draw.rect(screen, self.color, (self.pos[0] + self.scale * i , (self.pos[1] + (self.scale * x)), self.scale, self.scale))

Example: rect_(procedural number) = pygame.draw.rect(screen, self.color, (self.pos[0] + self.scale * i , (self.pos[1] + (self.scale * x)), self.scale, self.scale))

def invRect(self):
  tset = 0
  for x in range(self.rows):
    for i in range(self.columns):
      tset += 1
      this is the function i want to give a dynamic name ----->  pygame.draw.rect(screen, self.color, (self.pos[0] + self.scale * i , (self.pos[1] + (self.scale * x)), self.scale, self.scale))
      
buran
  • 13,682
  • 10
  • 36
  • 61
Alex GkG
  • 13
  • 3
  • I think you might be looking for [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial) – DeepSpace Nov 21 '22 at 12:55
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables). Note, from the example it's clear you want to dynamically create names and assign the return object from function, not the function itself. Anyway, it's antipattern. – buran Nov 21 '22 at 12:55
  • 1
    Why not keeping them inside a dictionary? – Abdullah Akçam Nov 21 '22 at 12:59
  • Also check [Ned Batchelder's _Keep data out of your variable names_](https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) and http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – buran Nov 21 '22 at 13:05

1 Answers1

0

You can make a dict which stores pointer to a function (if you do not add parentheses the variable acts as a function). If you add parentheses it only stores the result of the function -> return value.

funcs = dict({})

funcs[variable_name] = pygame.draw.rect

afterwards you can call it as

funcs[variable_name](parameters)
JohnyCapo
  • 170
  • 10
  • 1
    Note, from the "example" - OP does not want to create multiple functions. He wants to dynamically create names to which he assign the rectangle object returned from multiple calls of the same function `pygame.draw.rect()`. Which is a **wrong** thing to do. – buran Nov 21 '22 at 13:14