Set variables with uppercase letter in Python

Asked

Viewed 412 times

-1

Well, I’m learning python and from time to time I’ll read other dev’s codes to learn something and variables appear with uppercase letters.

Examples: RETRIABLE_STATUS_CODES = [500, 502, 503, 504], MAX_RETRIES = 10

My question is, when should I use variables of this type? Thank you from now.

  • It’s not specific to Python but it might help: https://answall.com/q/386953/101 Actually given the low quality of the question I think the answer there is the best you can get. https://answall.com/q/160947/101, https://answall.com/q/239964/101, https://answall.com/q/243958/101 and https://answall.com/q/31646/101

1 answer

1


Generally, uppercase variables are "constants", that is, a variable whose value is not changed in execution. In Python, it is not mandatory to use upper-case variables for this, but many developers do because in many languages this is a code convention or rule such as Java and Ruby.

This way of creating variables is also used by developers when they want, for example, to define the configuration of something. See these two simple examples below:

First example:

class Conta(object):

    PESSOA_FISICA = 1
    PESSOA_JURIDICA = 2

    def __init__(self,tipo):

        if tipo == Banco.PESSOA_FISICA:
            print("Você entrou com uma conta de pessoa física.")

        elif tipo == Banco.PESSOA_JURIDICA:
            print("Você entrou com uma conta de pessoa jurídica.")

        else:
            raise ValueError('O parâmetro "tipo" deve ser PESSOA_FISICA ou PESSOA_JURIDICA')

Second example:

import pygame

WINDOW_GEOMETRY = [800,400]
WINDOW_TITLE = "Example"

pygame.display.set_mode( WINDOW_GEOMETRY )
pygame.display.set_caption( WINDOW_TITLE )

Anyway, almost whenever you see a fully uppercase variable you already know that it is a constant and that it certainly serves to be used in some configuration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.