J4ns323
J4ns323

Reputation: 35

Is there a way to access just the value of object attribute when calling it as a variable

Is there a way to access the value of a variable without taking the variables name? I am trying to write a project which has an external constants file for colour definitions which I will use in the various programs to de-clutter my code.

The colours are set as RGB with the colour name such as:

BLACK = (0,0,0)

An example of the class which will use the colour is:

class Window:

    def __init__(self,w_width,w_height,w_colour,fps=60):
        pygame.init()
        self.w_width = w_width
        self.w_height = w_height
        self.fps = fps
        self.w_colour = w_colour
        self.screen = pygame.display.set_mode((self.w_width,self.w_height))
        self.clock = pygame.time.Clock()
        self.screen.fill(constants.self.w_colour)

And am coming into the error where constants.self.w_colour doesn't exist (which I understand as i'm assuming it is looking for a self.w_colour within the constants file which I know doesn't exist). But the value of self.w_colour could be BLACK or some other value which I know is contained in the constants file. I was wondering if there is a way to call the constants.self.w_colour by taking the value of self.w_colour and not python trying to follow it as a path?

Apologies if it doesn't make much sense but i've tried to describe it in the best way I can.

Upvotes: 1

Views: 67

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70377

I'm assuming you're throwing all of your constants in a file called constants.py somewhere. If so, the quick-and-dirty solution is to use __dict__.

import constants

my_favorite_color = constants.__dict__[color_name]

but that's messy and would confuse folks reading the code. If you intend that constants be accessed as a dictionary, then it would be best to make that explicit. In constants.py, consider

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# ... more colors

# Then at the bottom
COLORS = {
  'BLACK': BLACK,
  'WHITE': WHITE,
}

Then you can use it as

from constants import COLORS

my_favorite_color = COLORS[color_name]

It's a bit more verbose, but in the words of a wise man, "explicit is better than implicit".

Upvotes: 2

Related Questions