[SOLVED] In for loops, is there a way to execute a module function with attributes assigned by the for loop?

Issue

Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")

My output (no color changes):

  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]

Solution

Apologies, I searched around some more and found an answer by user Kasper I couldn’t before, which I implemented to my code like so:

from colorama import init, Fore, Style
init()

colors = dict(Fore.__dict__.items())

for color in colors.keys():
    print(colors[color] + f"  [{color}]")

Answered By – Denu Datus

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.