By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,538 Members | 869 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,538 IT Pros & Developers. It's quick & easy.

Python Feature Request: Explicit variable declarations

P: n/a
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python, and even
professionals, since this helps prevent typo errors like:

sunlognitude = sunlongitude + 180.0

where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.

Apr 14 '07 #1
Share this Question
Share on Google+
26 Replies


P: n/a
On Apr 14, 11:21 am, samj...@gmail.com wrote:
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python, and even
professionals, since this helps prevent typo errors like:

sunlognitude = sunlongitude + 180.0

where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.
Please read this:
http://www.python.org/doc/faq/progra...tatic-analysis

PyChecker and Pylint might help you.

- Paddy.

Apr 14 '07 #2

P: n/a
sa*****@gmail.com wrote:
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python, and even
professionals, since this helps prevent typo errors like:

sunlognitude = sunlongitude + 180.0

where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.
I have no formal training in programming and thus have had to shake off
all of the worst habits afflicting amateurs on my path to the modest
proficiency I enjoy now. So let me assure you that this is something I
can honestly say is just about the least of your worries and
consequently has no place clogging up a language like python.

But, if you have masochistic tendencies and want a lot of overhead in
your programming, you can always bind yourself mercilessly to classes:
class C(object):
declared = ['bob', 'carol', 'ted', 'alice']
def __setattr__(self, anattr, aval):
if anattr not in C.declared:
raise TypeError, "Just can't hook you up, bro."
else:
self.__dict__[anattr] = aval
E.g.:

pyclass C(object):
.... declared = ['bob', 'carol', 'ted', 'alice']
.... def __setattr__(self, anattr, aval):
.... if anattr not in C.declared:
.... raise TypeError, "Just can't hook you up, bro."
.... else:
.... self.__dict__[anattr] = aval
....
pyc = C()
pyc.bob = 42
pyc.bob
42
pyc.x = 69
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __setattr__
TypeError: Just can't hook you up, bro.
Extending this ugliness to type-checking is left as an exercise for the
reader. Using metaclasses for such nonsense is left as an exercise for
metaclass maniacs.

James
Apr 14 '07 #3

P: n/a
sa*****@gmail.com schrieb:
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.
I believe it has been requested before, but I'm too lazy now to search
for prior discussion. The request is sane, but is also incomplete: there
is no syntax suggested for the actual declarations of local variables,
and no discussion whether this is meant to apply to local variables
only, or also to global variables and object attributes.

I think there is a fairly low chance that such a request will be
considered. It's a big change (implementation-wise, and
documentation-wise), and likely controversial. So one would have
to write a PEP first (see PEP 1 for details).

Regards,
Martin
Apr 14 '07 #4

P: n/a
sa*****@gmail.com wrote:
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python, and even
professionals, since this helps prevent typo errors like:

sunlognitude = sunlongitude + 180.0

where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.
Just as a side-note, if you used a+=1 instead of a=a+1 then you wouldn't
have this problem.
Languages like Perl and VB need a strict mode because they will
auto-vivify variable for you. I.e. they will bring variables to life
with defined or undefined values if you use them in a l-value (left hand
side of an assignment) without having declared them prior. If you do
that in Python you get an exception.

Apr 14 '07 #5

P: n/a
Languages like Perl and VB need a strict mode because they will
auto-vivify variable for you. I.e. they will bring variables to life
with defined or undefined values if you use them in a l-value (left hand
side of an assignment) without having declared them prior. If you do
that in Python you get an exception.
I don't comprehend. I can just type a = 5 in a new Python session and
I get no exception. Python currently does not require variables to be
declared before they are used on the LHS.

Apr 14 '07 #6

P: n/a
"jamadagni" <sa*****@gmail.comha scritto nel messaggio
news:11**********************@p77g2000hsh.googlegr oups.com...
>Languages like Perl and VB need a strict mode because they will
auto-vivify variable for you. I.e. they will bring variables to life
with defined or undefined values if you use them in a l-value (left hand
side of an assignment) without having declared them prior. If you do
that in Python you get an exception.

I don't comprehend. I can just type a = 5 in a new Python session and
I get no exception. Python currently does not require variables to be
declared before they are used on the LHS.
I think (s)he meant right hand.
Apr 14 '07 #7

P: n/a
Army1987 wrote:
"jamadagni" <sa*****@gmail.comha scritto nel messaggio
news:11**********************@p77g2000hsh.googlegr oups.com...
>>Languages like Perl and VB need a strict mode because they will
auto-vivify variable for you. I.e. they will bring variables to life
with defined or undefined values if you use them in a l-value (left hand
side of an assignment) without having declared them prior. If you do
that in Python you get an exception.
I don't comprehend. I can just type a = 5 in a new Python session and
I get no exception. Python currently does not require variables to be
declared before they are used on the LHS.

I think (s)he meant right hand.

Yes I did sorry about that. If an assignment had hands then I would
have been right ;).
Apr 14 '07 #8

P: n/a
Dennis Lee Bieber wrote:
On 14 Apr 2007 06:35:34 -0700, "jamadagni" <sa*****@gmail.comdeclaimed
the following in comp.lang.python:
In Python, the "variable" NAME does NOT define storage; unlike most
other classical languages where the "variable name" is a storage
address, and the value of the RHS is COPIED to that address. Python does
not do such copying. Names are references to the RHS object itself.

a = 5

means that somewhere in memory is an integer object with the value "5";
the name "a" is now "pasted onto" that integer object.

b = a

finds the object that has the name "a" stuck to it, and sticks a second
name "b" onto the same object. There is still only one "5" in memory.
I can try this in interactive mode:
>>a = 5
b = a
a += 1
print b
5

So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
would expect b to be increased, just as a. But after increasing a, b is
still 5...

Lists behave as described above, integers and floats don't.

By the way, a classic language like C has features like this too;
they're called pointers.
Apr 14 '07 #9

P: n/a
Bart Willems wrote:
Dennis Lee Bieber wrote:
>On 14 Apr 2007 06:35:34 -0700, "jamadagni" <sa*****@gmail.comdeclaimed
the following in comp.lang.python:
In Python, the "variable" NAME does NOT define storage; unlike most
other classical languages where the "variable name" is a storage
address, and the value of the RHS is COPIED to that address. Python does
not do such copying. Names are references to the RHS object itself.

a = 5

means that somewhere in memory is an integer object with the value "5";
the name "a" is now "pasted onto" that integer object.

b = a

finds the object that has the name "a" stuck to it, and sticks a second
name "b" onto the same object. There is still only one "5" in memory.

I can try this in interactive mode:
>>a = 5
>>b = a
>>a += 1
>>print b
5

So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
would expect b to be increased, just as a. But after increasing a, b is
still 5...

Lists behave as described above, integers and floats don't.

By the way, a classic language like C has features like this too;
they're called pointers.
I think that after a += 1, a memory location with a 6 is created and now
a points to that because += has assignment buried in it.
Apr 14 '07 #10

P: n/a
Bart Willems wrote:
I can try this in interactive mode:
>>a = 5
>>b = a
>>a += 1
>>print b
5

So, if /a/ and /b/ where pointing to the *same* "5" in memory,
They do:
>>a = 5
b = a
a is b
True
>>a += 1
a is b
False

.... but not after a is rebound to a new int.
then I would expect b to be increased, just as a. But after
increasing a, b is still 5...
int objects are immutable. Thus, when rebinding a (as happens here
in "a += 1"), a new instance of int is created and "a" points to
it.
By the way, a classic language like C has features like this too;
they're called pointers.
C's int* behaves differently.

Regards,
Björn

--
BOFH excuse #163:

no "any" key on keyboard

Apr 14 '07 #11

P: n/a
On Saturday 14 April 2007, James Stroud wrote:
I think that after a += 1, a memory location with a 6 is created and now
a points to that because += has assignment buried in it.
Bingo.

a+=1 will (basically) translate to either "a=a.__iadd__(1)"
or "a=a.__add__(1)" depending on whether __iadd__ is defined of not.
>>'__iadd__' in dir(5)
False
>>'__add__' in dir(5)
True

So therefore "a+=1" becomes "a=a.__add__(a, 1)"
That make is relatively obvious that a '6' would be created and assigned back
to a.
You can have some fun with this using the 'is' operator. Remember that 'is'
compares objects and not values. So different objects can be equal, but
aren't the same. Thus:
>>a=[1,2,3]
b=[1,2,3]
a == b
True
>>a is b
False

To demonstrate the idea of name binding:
>>a=500
b=500
a == b
True
>>a is b
False
>>b=a
a is b
True

So typing the literal '500' creates an integer object with the value 500. By
typing it twice, two different objects of identical value are created
and "put in" two variables. However, by assigning one from the other, the
same object (created by the literal '500') is assigned to both variables.
This is why Python calls assignments "bindings"; you're realling just binding
the object from the right side to the name on the left.
For confusion's sake, here's what happens if you use smaller numbers:
>>a=1
b=1
a is b
True
>>3-2 is a
True

That happens because CPython (a particular and very common implementation of
Python) pre-creates objects for all small integers (something like <=100).
This saves memory, because all values of '1' are the same! So the
literal '1' simply gets a reference to the existing object of value '1',
rather than creating a new one (like the literal '500' does). The same is
also true for strings with len<=1.

Apr 14 '07 #12

P: n/a
On Sat, 14 Apr 2007 15:55:03 +0000, Dennis Lee Bieber wrote:

Names are references to the RHS object itself.

a = 5

means that somewhere in memory is an integer object with the value "5";
the name "a" is now "pasted onto" that integer object.
That's not correct, as it implies that the object 5 knows which names (if
any) it is associated with. That's not the case: objects don't know which
names point to them.

What actually happens is that the current namespace gains an entry "a",
which points to the existing object 5.

b = a

finds the object that has the name "a" stuck to it, and sticks a second
name "b" onto the same object.
It most certainly does not. What it does is add another name into the
namespace, "b", and points it to the same object as "a" already points to.

We shouldn't be frightened of introducing namespaces to newbies. They
have to learn sooner or later, and they aren't hard to learn. Sometimes
over-simplifying is worse than not simplifying at all.

A namespace is just a thing in memory that the Python compiler looks up
names. They are very important to Python.

--
Steven.

Apr 15 '07 #13

P: n/a
On Sat, 14 Apr 2007 16:03:03 -0400, Bart Willems wrote:

I can try this in interactive mode:
>>a = 5
>>b = a
>>a += 1
>>print b
5

So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
would expect b to be increased, just as a.
This is what you are implicitly _thinking_:

"a" points to a memory location, holding a few bytes with the bit pattern
0x05. When I add 1 to it, the bytes change to 0x06.

But integers in Python aren't bit patterns, they are objects. You can't
make the 5 object have value 6, that would be terrible:

py5 + 5 # remember that 5 has been changed to have value six!
12

So a += 1 rebinds the name "a" to the object 6. The name "b" still points
to the object 5, because you didn't do anything to "b".

Now, for extra credit: can you explain why this happens?
>>alist = [0]
blist = alist
alist += [1]
blist
[0, 1]

--
Steven.

Apr 15 '07 #14

P: n/a
Dennis Lee Bieber <wl*****@ix.netcom.comwrote:
...
In Python, the "variable" NAME does NOT define storage; unlike most
other classical languages where the "variable name" is a storage
address, and the value of the RHS is COPIED to that address. Python does
not do such copying. Names are references to the RHS object itself.
Right, but that's just like today's most popular languages -- Java and
C# -- with the one difference that in those languages "boxed" types
(elementary numbers, in Java) have different semantics.
Languages with "variable declarations" are pre-allocating object
space that can only hold objects of that type (ignoring VB "variant").
Again, this is not true for the most popular languages, Java and C# --
in those cases, excepting boxed types, variable declarations are
"pre-allocating" space for references, which can refer to any type
derived from theirs (so, e.g., in Java, "Object x;" means x can refer to
anything at all except a boxed type such as float).

I think you're confusing two issues with languages' underlying models:
boxes (C, Fortran, etc) vs tags (Java, Python, etc) for variables; and
declarations vs not. APL uses boxes but no declarations, etc, etc: you
can find all four variants!-)
Alex
Apr 15 '07 #15

P: n/a
On Apr 14, 3:56 pm, "Martin v. Löwis" <mar...@v.loewis.dewrote:
for prior discussion. The request is sane, but is also incomplete: there
is no syntax suggested for the actual declarations of local variables,
and no discussion whether this is meant to apply to local variables
only, or also to global variables and object attributes.
I suggest that the C syntax be followed:

int a, b, c
a = "foo" should raise a TypeError

But as has been pointed out in the intervening messages which are
slightly OT, the line int a, b, c should mean:

"a, b and c are meant to be labels of integer objects so don't allow
them to be labels of other kinds of objects without redeclaration",

and NOT the following:

"create three memory spaces for integers with labels a, b and c"

as it would be in C. This ensures that Python's behaviour of:
>>a = 2
b = a
a is b
True

continues even after int a, b. If the C meaning were taken, a is b
would never be True.

I do not see why this cannot be applicable to global variables also.
When explicit type declarations is enabled, no label can be used
implicitly for an object unless it has been declared that that label
is meant for that kind of object. If that label is reassigned to an
object of a different type, a TypeError should be raised. If a label
that has not been declared is used for an object, a
VariableNotDeclaredError should be raised.

This can be used for object attributes also. When a programmer creates
a class, he would be expected to type-declare the members.

This also means that function arguments and return values should be
type-declared:

def bool printNameAndAge ( str name, int age ) :
_print name
_print age
_return True

This option should be set for each source file. Otherwise it will
raise errors in modules which were written without type declaration
(and maybe in modules written in C too ??).

I realize this may be a big thing to include in a language which has
been traditionally dynamically-typed, but it can ease transitions to
lower-level languages like C, especially since one of the most
important uses of Python is learning programming. It is also useful to
pure Python programmers as said above for error-catching.

Apr 15 '07 #16

P: n/a
>>>>"Martin" == Martin v Löwis <ma****@v.loewis.dewrites:
sa*****@gmail.com schrieb:
>Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.
I believe it has been requested before, but I'm too lazy now to search
for prior discussion.
I remember the benevolent dictator's blogs on this. Googling for "optional
static typing" brought up these references:

http://www.artima.com/weblogs/viewpost.jsp?thread=85551
http://www.artima.com/weblogs/viewpost.jsp?thread=87182

and an older one:

http://www.python.org/~guido/static-typing/
The request is sane, but is also incomplete: there
is no syntax suggested for the actual declarations of local variables,
and no discussion whether this is meant to apply to local variables
only, or also to global variables and object attributes.
None of the above links talk about variable declarations but object
attributes are considered.

Ganesan

--
Ganesan Rajagopal

Apr 15 '07 #17

P: n/a
James Stroud wrote:
Bart Willems wrote:
>Dennis Lee Bieber wrote:
[...]
>Lists behave as described above, integers and floats don't.

By the way, a classic language like C has features like this too;
they're called pointers.

I think that after a += 1, a memory location with a 6 is created and now
a points to that because += has assignment buried in it.
This is the difference between mutable and immutable types.
>>a = 5
b = a
a += 1
a
6
>>b
5
>>a = [1,2,3,4,5]
b = a
a += [6,7,8]
a
[1, 2, 3, 4, 5, 6, 7, 8]
>>b
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 15 '07 #18

P: n/a
On 14 Apr 2007 03:21:18 -0700, sa*****@gmail.com <sa*****@gmail.comwrote:
....
I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python,
As a C and C++ programmer (not a C/C++ programmer), I have to say that
it doesn't bother me much. An optional feature like this would just
annoy me if I encountered code using it.

....
where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.
Well, he won't *wonder* -- Python will be rather explicit about it.
"Later" is the key word here -- this bug may lay around waiting for
ten years before someone triggers it.

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn!
Apr 19 '07 #19

P: n/a
On 4/14/07, James Stroud <js*****@mbi.ucla.eduwrote:
sa*****@gmail.com wrote:
But, if you have masochistic tendencies and want a lot of overhead in
your programming, you can always bind yourself mercilessly to classes:
class C(object):
declared = ['bob', 'carol', 'ted', 'alice']
def __setattr__(self, anattr, aval):
if anattr not in C.declared:
raise TypeError, "Just can't hook you up, bro."
else:
self.__dict__[anattr] = aval
You could also do this with __slots__, like:
>>class C(object):
.... __slots__ = ['bob','carol','ted','alice']
....
>>c = C()
c.bob = 42
c.bob
42
>>c.x = 69
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'x'
although, I personally have never found the need nor desire to use __slots__
>
E.g.:

pyclass C(object):
... declared = ['bob', 'carol', 'ted', 'alice']
... def __setattr__(self, anattr, aval):
... if anattr not in C.declared:
... raise TypeError, "Just can't hook you up, bro."
... else:
... self.__dict__[anattr] = aval
...
pyc = C()
pyc.bob = 42
pyc.bob
42
pyc.x = 69
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __setattr__
TypeError: Just can't hook you up, bro.
Extending this ugliness to type-checking is left as an exercise for the
reader. Using metaclasses for such nonsense is left as an exercise for
metaclass maniacs.

James
--
http://mail.python.org/mailman/listinfo/python-list
Apr 19 '07 #20

P: n/a
Jorgen Grahn <gr********@snipabacken.dyndns.orgwrote:
As a C and C++ programmer (not a C/C++ programmer), I have to say that
Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...?
Alex

Apr 20 '07 #21

P: n/a
In <1h**************************@mac.com>, Alex Martelli wrote:
Jorgen Grahn <gr********@snipabacken.dyndns.orgwrote:
>As a C and C++ programmer (not a C/C++ programmer), I have to say that

Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...?
Isn't it 1 unless `C` is 0? The increment happens after the division,
right? :-)

Ciao,
Marc 'BlackJack' Rintsch
Apr 20 '07 #22

P: n/a
En Fri, 20 Apr 2007 00:41:04 -0300, Alex Martelli <al***@mac.comescribió:
Jorgen Grahn <gr********@snipabacken.dyndns.orgwrote:
>As a C and C++ programmer (not a C/C++ programmer), I have to say that

Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...?
C/C++ == 1 most of the time (being C of any integer type, of course - for
arbitrary instances, see the always missing documentation).

--
Gabriel Genellina
Apr 20 '07 #23

P: n/a
On Apr 14, 6:21 am, samj...@gmail.com wrote:
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables.
The thoughts of the inventor of Python on "Adding Optional Static
Typing to Python" are at http://www.artima.com/weblogs/viewpost.jsp?thread=86641
.. I wonder if the idea will be implemented in Python 3.0.

Apr 20 '07 #24

P: n/a
sa*****@gmail.com a écrit :
Hello. Please tell me whether this feature request is sane (and not
done before) for python so it can be posted to the python-dev mailing
list. I should say first that I am not a professional programmer with
too much technical knowledge.

I would like to have something like the "option explicit" statement in
Visual Basic which turns on C-like checking for declaration of
variables. This is highly helpful for people who are coming from C/C+
+, for people who are learning programming using Python, and even
professionals, since this helps prevent typo errors like:

sunlognitude = sunlongitude + 180.0

where the user has inadvertantly typed "g" before "n" and will later
wonder why his application is not working as expected.
if you find declarative static typing programmer-friendly, then Python
is definitively not for you, and you'd better look for something else
(Java ?). FWIW, the first and main reason for stating typing is about
compiler's hint and raw performances, not "type-safety".

(A professional programmer with restricted technical knowledge and
absolutely no need for this kind of "help")
Apr 20 '07 #25

P: n/a
The thoughts of the inventor of Python on "Adding Optional Static
Typing to Python" are at http://www.artima.com/weblogs/viewpost.jsp?thread=86641
. I wonder if the idea will be implemented in Python 3.0.
No. He says it in another newer post and in PEP 3099, AFAIK.
--
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Apr 20 '07 #26

P: n/a
Dennis Lee Bieber wrote:
Unless it should be interpreted as (C/C)++, which would result in
2
No, since postfix ++ "returns before and increments after". But what
you say is true for ++(C/C).

Regards,
Björn

--
BOFH excuse #274:

It was OK before you touched it.

Apr 20 '07 #27

This discussion thread is closed

Replies have been disabled for this discussion.