I am writing an application which needs to find out the schema of a database, across engines. To that end, I am writing a small database adapter using Python. I decided to first write a base class that outlines the functionality I need, and then implement it using classes that inherit from this base. Along the way, I need to implement some constants which need to be accessible across all these classes. Some of these constants need to be combined using C-style bitwise OR.
My question is,
MAP_FIXED | MAP_FILE | MAP_SHARED
style code that C allows.For the former, I came across threads where all the constants were put into a module first. For the latter, I briefly thought of using a dict of booleans. Both of these seemed too unwieldly. I imagine that this is a fairly common requirement, and think some good way must indeed exist!
Convention means a certain way in which things are done within a community to ensure order. Similarly, Coding conventions are also a set of guidelines, but for a programming language that recommends programming style, practices, and methods.
Python uses four types of constants: integer, floating point, string, and boolean.
what is the standard way of sharing such constants?
Throughout the standard library, the most common way is to define constants as module-level variables using UPPER_CASE_WITH_UNDERSCORES names.
what is the right way to create constants that can be combined? I am referring to MAP_FIXED | MAP_FILE | MAP_SHARED style code that C allows.
The same rules as in C apply. You have to make sure that each constant value corresponds to a single, unique bit, i.e. powers of 2 (2, 4, 8, 16, ...).
Most of the time, people use hex numbers for this:
OPTION_A = 0x01 OPTION_B = 0x02 OPTION_C = 0x04 OPTION_D = 0x08 OPTION_E = 0x10 # ...
Some prefer a more human-readable style, computing the constant values dynamically using shift operators:
OPTION_A = 1 << 0 OPTION_B = 1 << 1 OPTION_C = 1 << 2 # ...
In Python, you could also use binary notation to make this even more obvious:
OPTION_A = 0b00000001 OPTION_B = 0b00000010 OPTION_C = 0b00000100 OPTION_D = 0b00001000
But since this notation is lengthy and hard to read, using hex or binary shift notation is probably preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With