473,729 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
+ 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_PageDow n.

Calls to Glk functions are thus ugly and tedious.

scriptref = glk.fileref_cre ate_by_prompt(
glk.fileusage_T ranscript | glk.fileusage_T extMode,
glk.filemode_Wr iteAppend, 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_cre ate_by_prompt(' Transcript+Text Mode',
'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 2070
"Neil Cerutti" <ho*****@yahoo. comwrote in message
news:sl******** ************@FI AD06.norwich.ed u...
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_PageDow n.

Calls to Glk functions are thus ugly and tedious.

scriptref = glk.fileref_cre ate_by_prompt(
glk.fileusage_T ranscript | glk.fileusage_T extMode,
glk.filemode_Wr iteAppend, 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(objec t)
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(objec t)
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.Trans cript = 1
fileusage.TextM ode = 2

filemode = Constants()
filemode.Read = 1
filemode.Write = 2
filemode.Append = 4
filemode.WriteA ppend = 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.A ppend", "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_cre ate_by_prompt(' Transcript+Text Mode',
'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_cre ate_by_prompt(' Transcript+Text Mode',
'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.r r._bogus_.comwr ote in message
news:XU******** *******@tornado .texas.rr.com.. .
Errata:
opAssoc = Constants(objec t)
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.A ppend", "flk.fileusage. TextMode", etc.,
Should be "glk.fileusage. TextMode".

-- Paul
Nov 1 '06 #5
On 2006-11-01, Paul McGuire <pt***@austin.r r._bogus_.comwr ote:
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.Trans cript = 1
fileusage.TextM ode = 2

filemode = Constants()
filemode.Read = 1
filemode.Write = 2
filemode.Append = 4
filemode.WriteA ppend = 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.A ppend", "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.pytho n:
>
class Constants(objec t)
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(objec t)
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.pytho n:
>>
class Constants(objec t)
pass

(I guess value immutability could probably be implemented using clever
implementation s 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(objec t)
opAssoc.RIGH T = 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.cons tant 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.pytho n:
>>opAssoc = Constants(objec t)
opAssoc.RIG HT = 0
opAssoc.LEF T = 1
>This is nice, but you can cut down on some of the cruft:
>Constants.LE FT = 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

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

Similar topics

4
1460
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 platforms, but recently we have discovered an annoying problem. In a module, there is the following code fragment: Deg2Rad = math.pi/180.0 angleEPS = 0.5
108
6416
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 describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
144
6906
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 initiative. Typically I find that coding standards are written by some guy in the company who has a way of coding that he likes and then tries to force everybody else to write code the way he likes it, not for any rational reason, but simply for the...
39
2206
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 ? style A: .... .... int a = 1; if(0==a) {
13
2361
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 (replacement for PHP's include() statement). My problem is, in PHP if you open a database connection it's always in scope for the duration of the script. Even if you use an abstraction layer ($db = DB::connect(...)) you can `global $db` and bring...
1
1313
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 guides for C-modules. I realize that I need to make some changes to follow http://www.python.org/doc/essays/styleguide.html better. Does anyone have an appropriate URL for me to follow for this task? Is one of the C-module guides appropriate? I...
18
2751
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 from the experts. I feel there's a tradeoff between clear, easily readdable and extensible code on one side, and safe code providing early errors and useful tracebacks on the other. I want both! How do you guys do it? What's the pythonic way? Are...
1
1197
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
1312
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 suggest that the from module import Class style is acceptable; is there a big "if you know what are doing" before, which I'm unable to see? Regards Marco
0
8927
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8764
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9156
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8159
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6026
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4798
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2694
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2166
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.