coding style - where to declare variables

Peter J. Holzer hjp-python at hjp.at
Sun Jul 22 11:28:09 EDT 2018


On 2018-07-22 09:36:13 -0400, Richard Damon wrote:
> > On Jul 22, 2018, at 8:48 AM, Sharan Basappa <sharan.basappa at gmail.com> wrote:
> > 
> > In other programming languages (e.g. C, C++), as a good practice,
> > variables are declared right at the start of the program,

There is no "start of the program" in C or C++. I assume that "start of
the function" was meant since "start of the compilation unit" would mean
that all variables are global (at least within the compilation unit)
which hopefully nobody considers a good practice.

> > irrespective of where it is normally used. What is the practice in
> > Python?
> > 
> > I see that, most of the code, declare variables where it is used and
> > not at the start of the program.
> 
> I would disagree that it is universally considered good practice to
> declare everything at the front. (There is much disagreement on this,
> but most consider declare at first use to be preferred, where
> possible).


> Last century, C code required this to make things easier on the
> compiler,

Nope. The language description in the German translation of K&R I (1984)
already shows declarations at the beginning of each block, not just each
function. The main text doesn't seem to mention this and all examples
declare variables at the start of each function, so it is possible that
this feature was added between the release of the original (1978) and
the German translation. But in any case block scope existed by 1984,
well before the turn of the century.

So the authors of C considered block scoped variables desirable
from the beginning or at least added them quite early. I would therefore
assume that they considered declaring variables in a block as good
practice.

C++ introduced the possibility to declare variables at any point in a
block, not just the beginning. C copied this in C99. Again I would argue
that Stroustrup introduced the feature because he considered declaring
variables for the smallest possible scope as good practice, and that the
C committee copied it because they agreed.

        hp

-- 
   _  | Peter J. Holzer    | we build much bigger, better disasters now
|_|_) |                    | because we have much more sophisticated
| |   | hjp at hjp.at         | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20180722/a9f30fe5/attachment.sig>


More information about the Python-list mailing list