473,480 Members | 1,855 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Style for modules with lots of constants

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.

--
Neil Cerutti
For those of you who have children and don't know it, we have a
nursery downstairs. --Church Bulletin Blooper
Nov 1 '06 #1
17 2045
"Neil Cerutti" <ho*****@yahoo.comwrote in message
news:sl********************@FIAD06.norwich.edu...
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.
Neil -

I recently had to add some new constants to pyparsing, representing LEFT and
RIGHT, but I didn't want to define such generic and
likely-to-collide-with-user-code variable names.

I settled on defining my own flavor of the Bag class, which I named
Constants since it is there specifically to define constants (although it
does nothing to enforce the "constant-ness" of the values).

class Constants(object)
pass

(I guess value immutability could probably be implemented using clever
implementations of __setattr__ and such, but is it really worth the
bother?).

Then I defined the context for my LEFT and RIGHT constants, which are being
created to specify operator associativity, and then my constant fields as
attributes of that object:

opAssoc = Constants(object)
opAssoc.RIGHT = 0
opAssoc.LEFT = 1

In client modules (that is, those that import your library) that don't like
"from pyparsing import *", they can just add opAssoc to the list of imported
names (as in "from pyparsing import opAssoc"), and all of the related
constant definitions come along for the ride.

In your example, this would look something like:

fileusage = Constants()
fileusage.Transcript = 1
fileusage.TextMode = 2

filemode = Constants()
filemode.Read = 1
filemode.Write = 2
filemode.Append = 4
filemode.WriteAppend = filemode.Write | filemode.Append

and so on. In the client modules they would simply enter "from glk import
fileusage, filemode". Or if they just "import glk", the references to the
constants look like "glk.filemode.Append", "flk.fileusage.TextMode", etc.,
and those garish and unsightly '_' separators are reduced to svelte little
'.'s.

I think this is a reasonable compromise in avoiding namespace pollution,
without inflicting unseemly text entry overhead on your module clients.

-- Paul
Nov 1 '06 #2
Neil Cerutti:
scriptref = glk.fileref_create_by_prompt('Transcript+TextMode' ,
'WriteAppend', 0)
That "+" sign seems useless. A space looks enough to me. The functions
can accept case-agnostic strings and ignore spaces inside them.
Example:
('transcript textmode ', 'writeappend', 0)

Parsing the combinable bitfield contants might be slowish, though.
I think you have to test if this is true for your situation. Management
of interned strings is probably fast enough (compared to the rest of
things done by the Python interpreter) for many purposes.

Bye,
bearophile

Nov 1 '06 #3
On 2006-11-01, be************@lycos.com <be************@lycos.comwrote:
Neil Cerutti:
>scriptref = glk.fileref_create_by_prompt('Transcript+TextMode' ,
'WriteAppend', 0)

That "+" sign seems useless. A space looks enough to me. The
functions can accept case-agnostic strings and ignore spaces
inside them. Example:
('transcript textmode ', 'writeappend', 0)
That's pretty cool. Not as pretty, but easier for users,
possibly.
>Parsing the combinable bitfield contants might be slowish,
though.

I think you have to test if this is true for your situation.
Management of interned strings is probably fast enough
(compared to the rest of things done by the Python interpreter)
for many purposes.
Agreed. I meant I'd have to later test if it's were fast enough.

--
Neil Cerutti
Nov 1 '06 #4
"Paul McGuire" <pt***@austin.rr._bogus_.comwrote in message
news:XU***************@tornado.texas.rr.com...
Errata:
opAssoc = Constants(object)
Urk! Should be "opAssoc = Constants()"
and so on. In the client modules they would simply enter "from glk import
fileusage, filemode". Or if they just "import glk", the references to the
constants look like "glk.filemode.Append", "flk.fileusage.TextMode", etc.,
Should be "glk.fileusage.TextMode".

-- Paul
Nov 1 '06 #5
On 2006-11-01, Paul McGuire <pt***@austin.rr._bogus_.comwrote:
I recently had to add some new constants to pyparsing,
representing LEFT and RIGHT, but I didn't want to define such
generic and likely-to-collide-with-user-code variable names.

I settled on defining my own flavor of the Bag class, which I
named Constants since it is there specifically to define
constants (although it does nothing to enforce the
"constant-ness" of the values).

In your example, this would look something like:

fileusage = Constants()
fileusage.Transcript = 1
fileusage.TextMode = 2

filemode = Constants()
filemode.Read = 1
filemode.Write = 2
filemode.Append = 4
filemode.WriteAppend = filemode.Write | filemode.Append

and so on. In the client modules they would simply enter "from
glk import fileusage, filemode". Or if they just "import glk",
the references to the constants look like
"glk.filemode.Append", "flk.fileusage.TextMode", etc., and
those garish and unsightly '_' separators are reduced to svelte
little '.'s.

I think this is a reasonable compromise in avoiding namespace
pollution, without inflicting unseemly text entry overhead on
your module clients.
That's looks quite tempting. Thanks!

It will be nice to provide a short way to import all the
constants at once, instead of having to write 'from glk import {a
long list}' in the common case that they want all the constants.

--
Neil Cerutti
Potluck supper: prayer and medication to follow. --Church Bulletin
Blooper
Nov 1 '06 #6
Paul McGuire wrote in news:XU***************@tornado.texas.rr.com in
comp.lang.python:
>
class Constants(object)
pass

(I guess value immutability could probably be implemented using clever
implementations of __setattr__ and such, but is it really worth the
bother?).

Then I defined the context for my LEFT and RIGHT constants, which are
being created to specify operator associativity, and then my constant
fields as attributes of that object:

opAssoc = Constants(object)
opAssoc.RIGHT = 0
opAssoc.LEFT = 1
This is nice, but you can cut down on some of the cruft:

class Constants( object ):
pass

Constants.RIGHT = 0
Constants.LEFT = 1

## client code ...
print Constants.LEFT

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Nov 1 '06 #7

"Rob Williscroft" <rt*@freenet.co.ukwrote in message
news:Xn**********************************@216.196. 109.145...
Paul McGuire wrote in news:XU***************@tornado.texas.rr.com in
comp.lang.python:
>>
class Constants(object)
pass

(I guess value immutability could probably be implemented using clever
implementations of __setattr__ and such, but is it really worth the
bother?).

Then I defined the context for my LEFT and RIGHT constants, which are
being created to specify operator associativity, and then my constant
fields as attributes of that object:

opAssoc = Constants(object)
opAssoc.RIGHT = 0
opAssoc.LEFT = 1

This is nice, but you can cut down on some of the cruft:

class Constants( object ):
pass

Constants.RIGHT = 0
Constants.LEFT = 1

## client code ...
print Constants.LEFT

Rob.
One man's cruft is another man's clarity. The reason I used instances
instead of just the Constants class was so that I could define a little more
descriptive context for the constants, rather than simply a shortcut for
importing lots and lots of constant definitions. I expect I will want to
define some more constants for other parts of pyparsing, and the instance
scoping helps organize them, that's all. It's really a style/taste issue at
this point. What you've written will certainly work, and if Neil has many
constants in his module, what you suggest would be a way to import them all
at once.

-- Paul
Nov 1 '06 #8
Rob Williscroft:
This is nice, but you can cut down on some of the cruft:

class Constants( object ):
pass

Constants.RIGHT = 0
Constants.LEFT = 1

## client code ...
print Constants.LEFT
Another possibility is to define such constants as strings instead of
integers:

_allflags = ("left",
"right",
# other constants...
# other constants...
)

class Flags(): pass

for _flag in _allflags:
setattr(Flags, _flag, _flag)

#print Flags.__dict__

Then the user can use Flags.left+" "+Flags.... , or just the "left"
string.
Then maybe for each attribute like the "left" constant, a "left_doc"
attribute can be added to Flags with a textual explanation of the
meaning of the "left" constant.

If your module has a short name, then maybe it's better to just use
such string constants as modulename.constant instead of Flags.constant,
using globals()[_flag] = _flag

Bye,
bearophile

Nov 1 '06 #9
Paul McGuire wrote in news:KN***************@tornado.texas.rr.com in
comp.lang.python:
>>opAssoc = Constants(object)
opAssoc.RIGHT = 0
opAssoc.LEFT = 1
>This is nice, but you can cut down on some of the cruft:
>Constants.LEFT = 1
One man's cruft is another man's clarity.
:-)
The reason I used instances
instead of just the Constants class was so that I could define a
little more descriptive context for the constants,
Sorry I don't know what you mean here, could I have an example ?
rather than simply
a shortcut for importing lots and lots of constant definitions. I
expect I will want to define some more constants for other parts of
pyparsing, and the instance scoping helps organize them, that's all.
Again I'm struggling to see how using an instance is any different from
just using the class ?

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Nov 1 '06 #10
>The reason I used instances instead of just the Constants
>class was so that I could define a little more descriptive
context for the constants,

Sorry I don't know what you mean here, could I have an example

It helps in the recognition if you have separation between
something like

turnDirection.LEFT

and

alignment.LEFT

They may be the same or different value for LEFT, but by grouping
them in a "descriptive context", it's easy to catch mistakes such as

paragraph.align(turnDirection.LEFT)

when what you want is

paragraph.align(alignment.LEFT)

and, as an added bonus, prevents name clashes such as

turnDirection.LEFT = 2
alignment.LEFT = 0

With the grab-bag o' constants, you have to use old-school
C-style in your modern name-space'd Python:

gboc.TURN_LEFT = 2
gboc.ALIGN_LEFT = 0

or even worse, you'd end up with cruftage where you have

gboc.LEFT = 2
gboc.ALIGN_LEFT = 0 #created a month later as needed

and then accidentally call

paragraph.align(gboc.LEFT)

when you mean

paragraph.align(gboc.ALIGN_LEFT)

This is what I understand the grandparent's post to be referring
to by "descriptive context".

-tkc

Nov 1 '06 #11

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.

--
Neil Cerutti
For those of you who have children and don't know it, we have a
nursery downstairs. --Church Bulletin Blooper
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.

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.

- Pad.

Nov 1 '06 #12
Tim Chase wrote in news:mailman.1617.1162412498.11739.python-
li**@python.org in comp.lang.python:
>>The reason I used instances instead of just the Constants
class was so that I could define a little more descriptive
context for the constants,

Sorry I don't know what you mean here, could I have an example


It helps in the recognition if you have separation between
something like

turnDirection.LEFT
class turnDirection( object ) : pass
turnDirection.LEFT = 0
turnDirection.RIGHT = 1
>
and

alignment.LEFT
class alignment( object ) : pass
alignment.LEFT = 3
>
They may be the same or different value for LEFT, but by grouping
them in a "descriptive context", it's easy to catch mistakes such as

paragraph.align(turnDirection.LEFT)

when what you want is

paragraph.align(alignment.LEFT)

and, as an added bonus, prevents name clashes such as

turnDirection.LEFT = 2
alignment.LEFT = 0

With the grab-bag o' constants, you have to use old-school
C-style in your modern name-space'd Python:

gboc.TURN_LEFT = 2
gboc.ALIGN_LEFT = 0

or even worse, you'd end up with cruftage where you have

gboc.LEFT = 2
gboc.ALIGN_LEFT = 0 #created a month later as needed

and then accidentally call

paragraph.align(gboc.LEFT)

when you mean

paragraph.align(gboc.ALIGN_LEFT)

This is what I understand the grandparent's post to be referring
to by "descriptive context".
Fair enough, but there is nothing in this that can't be done with
pure (instance free) classes as shown above, with the advantage
that the client just imports the name for the set of constants
they want to use, and uses them with no need to construct.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Nov 1 '06 #13
Neil Cerutti <ho*****@yahoo.comwrites:
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.
One thing that has been implicit in other replies is the naming
convention for constants. There's nothing stopping a user from
re-binding a name in Python, so we use the convention that constants
are named with UPPER_CASE to indicate they shouldn't be re-bound.

--
\ "Everything you read in newspapers is absolutely true, except |
`\ for that rare story of which you happen to have first-hand |
_o__) knowledge." -- Erwin Knoll |
Ben Finney

Nov 1 '06 #14
Neil Cerutti wrote:
On 2006-11-01, be************@lycos.com <be************@lycos.comwrote:
>Neil Cerutti:
>>scriptref = glk.fileref_create_by_prompt('Transcript+TextMode' ,
'WriteAppend', 0)
That "+" sign seems useless. A space looks enough to me. The
functions can accept case-agnostic strings and ignore spaces
inside them. Example:
('transcript textmode ', 'writeappend', 0)

That's pretty cool. Not as pretty, but easier for users,
possibly.
>>Parsing the combinable bitfield contants might be slowish,
though.
I think you have to test if this is true for your situation.
Management of interned strings is probably fast enough
(compared to the rest of things done by the Python interpreter)
for many purposes.

Agreed. I meant I'd have to later test if it's were fast enough.
I've found using plain strings as flags has several advantages.

The value 'textmode' is always 'textmode', there is no dependency on a module or
class being imported or initialized.

It avoids having to type namespace prefixes such as thismod.textmode, or
myclass.textmode or importing a bunch of values into global name space.

Strings comparisons in python are very fast.

The disadvantage is an invalid flag may pass silently unless you do some sort of
validation which may slow things down a bit.

Ron

Nov 1 '06 #15
Ron Adam:
The disadvantage is an invalid flag may pass silently unless you do some sort of
validation which may slow things down a bit.
That string validation is usually necessary.

Bye,
bearophile

Nov 2 '06 #16
On 2006-11-01, Paddy <pa*******@netscape.netwrote:
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
Nov 2 '06 #17
Paul McGuire wrote:
class Constants(object):
pass

Then I defined the context for my LEFT and RIGHT constants, which are being
created to specify operator associativity, and then my constant fields as
attributes of that object:

opAssoc = Constants(object)
opAssoc.RIGHT = 0
opAssoc.LEFT = 1
I like something like:

class Constants(object):
def __init__(self, **kw):
for name, val in kw.iteritems():
setattr(self, name, val)
Then:
opAssoc = Constants(RIGHT=0, LEFT=1)
In your example, this would look something like:

fileusage = Constants()
fileusage.Transcript = 1
fileusage.TextMode = 2
fileusage = Constants(Transcript=1, TextMode=2)
filemode = Constants(Read=1, Write=2, Append=4)
filemode.WriteAppend = filemode.Write | filemode.Append

class Constants then becomes a nice place to define methods
to convert values to associated names for debugging and such.

--Scott David Daniels
sc***********@acm.org
Nov 3 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1442
by: Tomasz Lisowski | last post by:
Hi, We are distributing our Python application as the short main script (.py file) and a set of modules compiled to the .pyc files. So far, we have always treated .pyc files as portable between...
108
6290
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would...
144
6727
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
39
2152
by: jamilur_rahman | last post by:
What is the BIG difference between checking the "if(expression)" in A and B ? I'm used to with style A, "if(0==a)", but my peer reviewer likes style B, how can I defend myself to stay with style A...
13
2318
by: Robin Haswell | last post by:
Hey people I'm an experience PHP programmer who's been writing python for a couple of weeks now. I'm writing quite a large application which I've decided to break down in to lots of modules...
1
1301
by: RayS | last post by:
I've begun a Python module to provide a complete interface to the Meade LX200 command set, and have searched for a style/development guide for Python Lib/site-packages type modules, but only saw...
18
2721
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning...
1
1186
by: Tommy Grav | last post by:
Hi, I am working on a package that contains a number of different modules: __init__.py constants.py conversion.py observation.py orbit.py
2
1293
by: Marco Bizzarri | last post by:
On Sat, Aug 30, 2008 at 2:20 PM, Fredrik Lundh <fredrik@pythonware.comwrote: Thanks Fredrik; I understand that is the underlying message of your article. I'm just confused because PEP8 seems to...
0
7046
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6908
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7048
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7088
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6741
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5342
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4485
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2997
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
183
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.