noob question

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jun 27 08:23:34 EDT 2005


On Mon, 27 Jun 2005 07:14:07 +0000, Alan Gauld wrote:

> The only place I've ever found Hungarian notation useful was
> in C which is a weird mix of static typing and no-typing,
> and there the prefix code gives a clue as to what kind of
> value you might expect to find. But when I moved to C++ I
> dropped the prefixes because they added no value.
> 
> In Python Hungarian notation is meaningless since variables
> aren't typed anyway.

Not quite true. Objects are typed in Python:

py> type('')
<type 'str'>
py> type(1)
<type 'int'>

but names ("variables", almost) can be dynamically changed from one type
to another:

py> x = 1 # x starts as an int
py> x = '~' # now it is a string
py> x = [1] # and now a list

Even though names can refer to an object of any type, the actual
objects themselves are always strongly typed: "hello" is always a
string, {} is always a dict, and so on.

The best use of Hungarian notation is the original use, as introduced in
the application development team at Microsoft (before the operating system
team got their hands on it, and broke it).

Rather than prefixing variable names with the type which the compiler
already knows (eg "sName" for a string, "iAge" for an integer), the
original use of Hungarian notation was to use a prefix which explains what
the data is for: the "type" of object, but not types which compilers
understand.

Here are some good uses for Hungarian notation:

ixCurrent = 0  # ix~ means index into a list or array
cFound = 0 # c~ means a count
dxObject = object.width() # d means difference

No compiler in the world can tell that adding the width of an object in
pixels to the count of how many objects were found gives a meaningless
result. But a human programmer should immediately see the bug in:

ixHam = dxEgg + cTomato

even if they don't remember what Ham, Egg and Tomato represent.

Remember that space probe a few years back that crashed into Mars because
some NASA engineer forgot to convert metric to imperial or vice versa?
That sort of mistake is easy to make when you have something like this:

initialSpeed = 3572.8 # feet per second
# ~~~
# five pages of code
# ~~~
deceleration = 3.5 # metres per second squared
# ~~~
# five more pages of code
# ~~~
timeNeeded = initialSpeed/deceleration

Now imagine seeing this line instead:

timeNeeded = iInitialSpeed/mDeceleration

With just a glance you can see that there needs to be a conversion from
imperial (i~) to metric (m~) or vice versa, or else your $20 billion
dollar space probe turns the engines off too early and becomes a $20
billion hole in the ground.



The history and justification for Hungarian notation is explained here:

http://www.joelonsoftware.com/articles/Wrong.html


-- 
Steven.




More information about the Python-list mailing list