473,581 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: type-checking support in Python?

En Mon, 06 Oct 2008 11:19:58 -0300, Joe Strout <jo*@strout.net escribió:
Finally, one thing I've considered is adopting some identifier prefixes
indicating type. Maybe "iFoo" for integer, "fFoo" for floating-point
numbers, "d" for dictionary, "l" for list, "t" for tuple, "o" for
object, and "v" for variable types that may be more than one of the
above. I gather (from just a couple days of browsing) that such a
naming convention isn't common in the Python community, but is there
anyone else here who does it? I'd rather adopt an existing standard
(even if it's not widely used) than make one up.
Apart from the wise words that others have said, I'd add that I see no
point in identifier prefixes when they merely indicate "type" (in the
Python sense or even a broader sense) - called "system Hungarian notation"
by some.
In contrast, the prefix used in "apps Hungarian notation" declares the
"kind" or "intent" of the variable, and it may be useful in some cases.
This appears to be the original intent of Charles Simonyi when he wrote
his paper [1]; the differences between both approaches are discussed here
[2].
As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm². So it's important
to keep track of which unit some variable represents - its type would be
always float, and that carries no information; but its unit *is* important
informacion, so I sometimes use a postfix to indicate that.
Variable names should be *meaningful* - before automatically sticking an
"f" or "i" or "m_" prefix to something, think what you gain from it. If
you always represent a street address using a string in your application,
"szAddress" (or "sAddress") don't give you any more information than
"address" alone, so the prefix is useless.

[1] http://msdn.microsoft.com/en-us/library/Aa260976.aspx
[2] http://blogs.msdn.com/ericlippert/ar.../12/52989.aspx

--
Gabriel Genellina

Oct 7 '08 #1
13 1570
In message <ma************ *************** ***********@pyt hon.org>, Gabriel
Genellina wrote:
As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm².
Isn't the right way to handle that to attach dimensions to each number?
Oct 7 '08 #2
On 7 Ott, 08:36, Lawrence D'Oliveiro <l...@geek-
central.gen.new _zealandwrote:
In message <mailman.2089.1 223358567.3487. python-l...@python.org >, Gabriel

Genellina wrote:
As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm².

Isn't the right way to handle that to attach dimensions to each number?
Can you afford to avoid floats and ints? Attaching suffixes is the
best one can do with the builtin types.
In C++ one can check dimensions at compile time (http://www.boost.org/
doc/libs/1_36_0/doc/html/boost_units.htm l) with a modest increase of
cumbersomeness, but Python would need very heavyweight classes
containing a value and its dimension and a replacement of all needed
functions and operations.

Regards,
Lorenzo Gatti
Oct 7 '08 #3
En Tue, 07 Oct 2008 03:36:12 -0300, Lawrence D'Oliveiro
<ld*@geek-central.gen.new _zealandescribi ó:
In message <ma************ *************** ***********@pyt hon.org>, Gabriel
Genellina wrote:
>As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm².

Isn't the right way to handle that to attach dimensions to each number?
Maybe, but I prefer the values to be plain float objects. In my case it's
not that units are dynamic themselves: "this" file format has depth in
feet, "that" one uses meters, but that's known from start. I think I'd
attach units to values if they were dynamic and I had to reproduce the
original format exactly, but hasn't happened yet (fortunately).

--
Gabriel Genellina

Oct 7 '08 #4
Bas
On Oct 7, 8:36 am, Lawrence D'Oliveiro <l...@geek-
central.gen.new _zealandwrote:
In message <mailman.2089.1 223358567.3487. python-l...@python.org >, Gabriel

Genellina wrote:
As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm².

Isn't the right way to handle that to attach dimensions to each number?
What they taught me as a physics undergrad is to always convert random
units given as input to SI units as soon as possible, do all your
calculations internally in SI units and (only if really needed)
convert back to arbitrary units on output. Now, 15 years later, I am
still trying to stick to this rule whenever possisble. This convention
allows you to 'forget' about units and save your pre/post-fixes for
the exceptional case:
inch = 0.0254
lenght_inch = some_user_input _in_inch()
length = length_inch * inch

I have heard about some python package which overloads numbers and
calculations to include units (quick google found unum, not sure if
that is the only one). I guess that unless you are dealing with life-
critical equipment or are using extreme programming, this is overkill
(but I guess python is not really the right language for that anyway,
imagine a garbage collection just when you want to launch your
shuttle).

Bas
Oct 7 '08 #5
On Oct 7, 5:24*am, Bas <wegw...@gmail. comwrote:
On Oct 7, 8:36 am, Lawrence D'Oliveiro <l...@geek-

central.gen.new _zealandwrote:
In message <mailman.2089.1 223358567.3487. python-l...@python.org >, Gabriel
Genellina wrote:
As an example, in the oil industry here in my country there is a mix of
measurement units in common usage. Depth is measured in meters, but pump
stroke in inches; loads in lbs but pressures in kg/cm².
Isn't the right way to handle that to attach dimensions to each number?

What they taught me as a physics undergrad is to always convert random
units given as input to SI units as soon as possible, do all your
calculations internally in SI units and (only if really needed)
convert back to arbitrary units on output.
(snip)

If you think it's a potential source of error, a lightweight version
wouldn't be hard to implement. This one is absolute minimal, using
strings for the units. Multiplication is harder, since you want 'foot
pounds' == 'pound feet'.
>>class UnitScalar:
.... def __init__( self, val, type ):
.... self.val, self.type= val, type
.... def __add__( self, other ):
.... assert self.type== other.type, 'Must be same type'
.... return self.__class__( self.val+ other.val,
self.type )
.... def __repr__( self ):
.... return '<UnitScalar %f %s>'% ( self.val, self.type )
....
>>a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'feet' )
a+ b
<UnitScalar 5.000000 feet>
>>a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'inches' )
a+ b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __add__
AssertionError: Must be same type
Oct 7 '08 #6
hi,

On Oct 7, 3:24*am, Bas <wegw...@gmail. comwrote:
I have heard about some python package which overloads numbers and
calculations to include units (quick google found unum, not sure if
that is the only one). I guess that unless you are dealing with life-
critical equipment or are using extreme programming, this is overkill
(but I guess python is not really the right language for that anyway,
imagine a garbage collection just when you want to launch your
shuttle).
FWIW, the python papers volume 3 issue 1 is mentionning another
package, 'scalar':
http://archive.pythonpapers.org/TheP...ume3Issue1.pdf
http://russp.us/scalar.htm

cheers,
sebastien.
Oct 7 '08 #7
I also wrote a units package which I'm using for a project of my own
(a spiking neural network simulator package called 'Brian'), released
separately as a package called Piquant which you can get at
sourceforge:

http://sourceforge.net/projects/piquant

I'm also looking for people to help improve it (get in touch!). The
way the package works is to have a Quantity class derived from float,
with extra operations. One thing that is different from the other
packages out there (and the reason I went to the effort of writing my
own package rather than using unum or scalar) is that we also have a
QuantityArray or qarray class that derives from numpy.ndarray. There
are at the moment two supported types of qarray, with homogeneous
units (one unit for the whole array), and heterogeneous units
(different unit for each item in the array). At the moment the
heterogeneous units implementation is horrible and very slow, but I
have a plan for a nicer version at some point (based on numpy's
broadcasting rules, so allowing you to have one unit for each row or
each column in a matrix for example).

Actually I think it would be a really good idea for someone at some
point to make a standardised system for units and add it to numpy/
scipy. I'd love to do it myself, but at the moment I have grant
applications, papers to finish, etc... :-(

Dan

Sebastien Binet wrote:
hi,

On Oct 7, 3:24�am, Bas <wegw...@gmail. comwrote:
I have heard about some python package which overloads numbers and
calculations to include units (quick google found unum, not sure if
that is the only one). I guess that unless you are dealing with life-
critical equipment or are using extreme programming, this is overkill
(but I guess python is not really the right language for that anyway,
imagine a garbage collection just when you want to launch your
shuttle).

FWIW, the python papers volume 3 issue 1 is mentionning another
package, 'scalar':
http://archive.pythonpapers.org/TheP...ume3Issue1.pdf
http://russp.us/scalar.htm

cheers,
sebastien.
Oct 7 '08 #8
dg************* *@thesamovar.ne t wrote:
I also wrote a units package which I'm using for a project of my own
(a spiking neural network simulator package called 'Brian'), released
separately as a package called Piquant which you can get at
sourceforge:

http://sourceforge.net/projects/piquant

I'm also looking for people to help improve it (get in touch!). The
way the package works is to have a Quantity class derived from float,
with extra operations. One thing that is different from the other
packages out there (and the reason I went to the effort of writing my
own package rather than using unum or scalar) is that we also have a
QuantityArray or qarray class that derives from numpy.ndarray. There
are at the moment two supported types of qarray, with homogeneous
units (one unit for the whole array), and heterogeneous units
(different unit for each item in the array).
I have a unit system module (unity) in progress as well (it's working
but it's as yet unreleased), but which takes a different approach which
I think has more promise. Instead of having multiple united types
derived from different fundamental types, it has its own type Quantity
which takes two arguments: the amount and the units (which are further
data structures). That way, the amount and the units are kept
separately and the unit system doesn't know anything specific about the
amount and only deals with the unit system. Operations between
quantities enforce the type system (either combining the units for
operations like multiplication, or requiring that they be compatible for
operations like addition or comparison), and simply perform the
appropriate operations on the amount without enforcing any type. This
allows you to have united operations on integers, floating point
numbers, decimals, vectors, matrices, quaternions -- whatever values you
may want to support units.

Mine is more of a dimensional analysis tool (as well as a general unit
converter) since it allows you to define a basis of units, then define
units within that basis and manipulate them -- thus it remembers the
definitions of all the units it has encountered. You can define whole
new unit systems (e.g., c.g.s. vs. SI) and have them all relate to each
other, or even define brand new unit systems (e.g., man-day-widgets for
questions like, "If it takes one man three days to make two widgets, how
many widgets can five men make in two weeks?").

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
Those who forget the past are condemned to repeat it.
-- George Santayana
Oct 7 '08 #9
On Oct 7, 3:52*pm, Erik Max Francis <m...@alcyone.c omwrote:
dg.google.gro.. .@thesamovar.ne t wrote:
(e.g., man-day-widgets for
questions like, "If it takes one man three days to make two widgets, how
many widgets can five men make in two weeks?").
Wouldn't that be 'widgets per man-day'?
Oct 7 '08 #10

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

Similar topics

5
3388
by: bartek d | last post by:
Hello, Regarding my previous question about a class which is used to store a variable type vector. I tried to be more elaborate on the code. I'd be grateful for your suggestions. Am I going in the wrong direction with the implementation? I'm asking this because I don't have much experience with C++. Thanks in advance. The main problem...
0
1734
by: Morten Gulbrandsen | last post by:
Dear MySQL developers, Could some experienced Database developer please take a look at this ? It is supposed to be plain SQL2. How can it be coded under MySQL Especially all referential triggered actions.
4
2926
by: Jari Kujansuu | last post by:
I can successfully parse XML document using SAX or DOM and I can also validate XML document against schema. Problem is that my program should deal with user-defined schemas which means that when I parse some element from XML document I don't know until runtime the type of the element (it depends on the type used in user-defined schema). XML...
0
1491
by: chobin | last post by:
Hi all. I've a terrible question. I've to build one XML page (based on a xml schema) that implements a dynamic database. In particular, I would declare something like this: <?xml version="1.0" encoding="UTF-8"?> <virtuose xmlns="http://www.virtuose.it/ns/virtuose" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"...
4
547
by: Richard Lee | last post by:
Hi, I have a question when I do a data type cast. the common way when we do a cast, is we know the type we want to cast to, i.e. we want to cast object to string, object xyz = "question"; (string)xyz; now we only have a type object of System.String type
3
510
by: dgaucher | last post by:
Hi, I want to consume a Web Service that returns a choice, but my C++ client always receives the same returned type. On the other hand, when I am using a Java client, it is working fine (of course, the generated proxy is not the same). When I am looking at the C++ generated code, it seems fine, but when I am executing the code, I always...
11
1866
by: Johan | last post by:
Hi Can somebody explain to me why I get this warning message and how I can solve this warning message. Thanks a lot Johan In member function `void
3
2459
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going wrong? I am using g++ (GCC) 3.3.5 on a Debian Sarge system. The compiler complains: //**************************** //****************************...
5
2051
by: Fabio Fracassi | last post by:
Hi, I belive what i am trying to do is not possible, but I hope someone can change my mind. Here is some code i'd like to write: template <class type> class engine1 {}; template <class type> class engine2 {};
5
1515
by: Axter | last post by:
I'm fine tuning a scope_handle class that takes a policy class as the second template. http://code.axter.com/scope_handle.h Please see above link for full understanding of the problem. One thing I don't like about the way the current policy template is setup is that for the ptr_policy class the first template type is different from the...
0
7789
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...
0
8301
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8169
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...
0
6551
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...
1
5670
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...
0
5361
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...
0
3820
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1132
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...

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.