Python

Enumerations & Flags

18 flashcards · answers and spaced-repetition review in the KnowCard app

You model weekdays as plain ints (Monday = 1, ...). What real problems does this invite that an Enum prevents?
What does this print? ``` import enum class Day(enum.Enum): Mon = 1 print(Day.Mon == 1) ```
Given a plain Enum member, how do you get its display name versus its underlying stored value?
Two variables both hold Color.RED from the same Enum. Should you compare them with is or ==, and why does it matter?
What are the two ways to look up an Enum member from data — one from its stored value, one from its name string?
What does this print? ``` class Day(enum.Enum): Mon = 1 Tue = 2 Holiday = 1 for d in Day: print(d.name) ```
You defined an Enum where two members accidentally share the same value. How do you make Python reject that instead of silently creating an alias?
What does this print? ``` Color = enum.Enum( "Color", "RED GREEN BLUE") print(Color.GREEN.value) ```
When defining an Enum, what does enum.auto() do, and what value does the first auto member get?
What does this print? ``` class Day(enum.IntEnum): Mon = 1 Tue = 2 print(Day.Mon < 10, Day.Mon + Day.Tue) ```
IntEnum members behave like ints, which sounds convenient. What's the real risk that makes plain Enum the safer default?
What does this print? ``` class TL(enum.Flag): Red = enum.auto() Amber = enum.auto() Green = enum.auto() print(TL.Red.value, TL.Amber.value, TL.Green.value) ```
With a Flag enum, how do you combine two flags, and how do you correctly test whether a given flag is set in a combination?
What does this print? ``` class TL(enum.Flag): Red = enum.auto() Amber = enum.auto() Green = enum.auto() s = TL.Red | TL.Amber print(bool(s & TL.Green)) ```
Why would you reach for Flag/IntFlag instead of a plain Enum when modelling a set of on/off options like file permissions?
What's the difference between Flag and IntFlag for a combined value, in terms of how the result can be used?
What does this print? ``` class Day(enum.Enum): Mon = 1 print(Day.Mon) print(Day.Mon.name) ```
Every Enum example assigns integers to the members (Monday = 1, ...). Are you restricted to ints for a member's internal value?

Start learning today

Free to start — download the app or use it in your browser.

Get it on App StoreGet it on Google Play