Style for modules with lots of constants

Neil Cerutti horpner at
Thu Nov 2 15:20:46 CET 2006

On 2006-11-01, Paddy <paddy3118 at> wrote:
> Neil Cerutti wrote:
>> The Glk API (which I'm implementing in native Python code)
>> defines 120 or so constants that users must use. The constants
>> already have fairly long names, e.g., gestalt_Version,
>> evtype_Timer, keycode_PageDown.
>> Calls to Glk functions are thus ugly and tedious.
>>     scriptref = glk.fileref_create_by_prompt(
>>             glk.fileusage_Transcript | glk.fileusage_TextMode,
>>             glk.filemode_WriteAppend, 0)
>> Please give me some good style advice for this situation.
>> I know some modules are designed to be used as 'from XXX import
>> *'. Since the Glk API is heavily influenced by its inception in
>> C this might not be a huge problem. All the functions in the API
>> have glk_ prepended, since C has no namespaces. I think it makes
>> sense to stick the glk_'s back on the functions and instruct
>> users to 'from Glk import *', but I know it doesn't conform with
>> Python practice, and Python has plenty of modules that were
>> originally designed in C, but don't insist on polluting the
>> global namespace.
>> Would it better to use strings instead? Some Python builtins use
>> them as a way to avoid creating of global constants.
>>     scriptref = glk.fileref_create_by_prompt('Transcript+TextMode',
>>             'WriteAppend', 0)
>> Parsing the combinable bitfield contants might be slowish,
>> though.
>> Thanks for taking the time to consider my question.
> I'd check the C code to first see if I could extract the C
> constant definitions and automatically   convert them into
> Python names vvia a short program. That way, I'd remove any
> transcription errors.

That's an excellent idea. I've moved all the constants to a
seperate file; it should be possible to write a Python script to
generate it from glk.h. If I ultimately decide to use strings
instead of identifiers, the program would generate a big
dictionary declaration instead of the Constants() instances.

> I favour the constants class mentioned by others , but would
> not mess with any of the long constant names as it helps those
> who know the original C, and also helps when users need to rely
> on original C documentation.

I have the luxury of stylistically modifying the C API to suit
Python and Python programmer's needs. I will have to take on the
burden of documenting the Python GLK API.

Neil Cerutti

More information about the Python-list mailing list