Skip to content

Commit d44ed4e

Browse files
committed
Create putting_type_information_in_a_variable_name.rst.
1 parent 92025fd commit d44ed4e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
Putting type notation in a variable name
2+
========================================
3+
4+
Summary
5+
-------
6+
7+
Putting type notation in a variable name is potentially misleading, because there is nothing in the Python language which can actually enforce that the variable type actually matches the type notation described in the name. Consider removing the type notation.
8+
9+
Description
10+
-----------
11+
12+
Python is a duck-typed language. Just because a variable is described as an integer, does not mean that it actually is an integer. This can be very dangerous for any programmer who acts on the variable assuming that it is an integer. Note that the practice of including type notation in variable names is also called Hungarian Notation.
13+
14+
Examples
15+
----------
16+
17+
Using type notation in variable names
18+
.....................................
19+
20+
The module below demonstrates the dangers of variables whose names include type notation. Just because a variable is called ``n_int`` does not mean that the variable actually contains an integer for its value.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
n_int = "Hello, World!"
27+
28+
4 / n_int # mistakenly assuming that n_int is a number
29+
30+
31+
Solutions
32+
---------
33+
34+
Remove type notation
35+
....................
36+
37+
Although the modifed module below does not fix the underlying problem of attempting to divide a number by a string, the code is generally less misleading, because there is no misleading description in the variable name ``n`` that ``n`` is a number.
38+
39+
.. code:: python
40+
41+
n = "Hello, World!"
42+
43+
4 / n # still a problem, but less likely to occur now
44+
45+
References
46+
----------
47+
`Stack Overflow - Hungarian Notation <http://stackoverflow.com/questions/8791533/does-it-make-sense-to-use-hungarian-notation-prefixes-in-interpreted-languages>`_

0 commit comments

Comments
 (0)