Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conventions on creating constants in Python

Tags:

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,

  1. what is the standard way of sharing such constants?
  2. 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.

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!

like image 464
susmits Avatar asked Aug 16 '11 13:08

susmits


People also ask

What are conventions in Python?

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.

How many types of constants are there in Python?

Python uses four types of constants: integer, floating point, string, and boolean.


1 Answers

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.

like image 81
Ferdinand Beyer Avatar answered Sep 30 '22 17:09

Ferdinand Beyer