Python Feature Request: Explicit variable declarations

S

samjnaa

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.
 
P

Paddy

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/progr...-to-help-find-bugs-or-perform-static-analysis

PyChecker and Pylint might help you.

- Paddy.
 
J

James Stroud

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.:

py> 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
....
py> c = C()
py> c.bob = 42
py> c.bob
42
py> c.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
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

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
 
N

nikolas pontikos

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.
 
J

jamadagni

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.
 
A

Army1987

jamadagni said:
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.
 
D

Dennis Lee Bieber

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.

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.

In a classical language (BASIC, for example)

a = 5

means "find or allocate a memory cell, copy the integer '5'" into that
memory cell.

b = a

is "find or allocate a memory cell, copy the contents found in the
memory cell assigned to 'a' into the new cell". There are now two places
in memory containing "5"


The LHS of a statement in Python does not create object storage --
object storage is only the result of the RHS, and the LHS only attaches
a reference to that storage.

The LHS of a statement in other languages either reuses storage
previously allocated to the variable, or creates new storage for the
variable, and duplicates the value found at whatever storage is used by
the RHS.

Languages with "variable declarations" are pre-allocating object
space that can only hold objects of that type (ignoring VB "variant").
That variable is always the same memory space -- unlike Python where the
space is created by the actions of a RHS, and the name is just attached
to it.

--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
B

Bart Willems

Dennis said:
On 14 Apr 2007 06:35:34 -0700, "jamadagni" <[email protected]> declaimed
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: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.
 
J

James Stroud

Bart said:
I can try this in interactive mode:
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.
 
B

Bjoern Schliessmann

Bart said:
I can try this in interactive mode:
5

So, if /a/ and /b/ where pointing to the *same* "5" in memory,

They do:
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
 
D

DillonCo

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.
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: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: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.
 
D

Dennis Lee Bieber

I can try this in interactive mode:
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...
Did you compare the IDs of a and b?
3302000 3302000 3302000

All three have the same /object/ ID

"a" has changed ID... "b" and "5" haven't.

"b" is still /attached/ to the "5" object... but "a" was
disconnected from the object that is "5" and attached to the object in
memory that is "6"

The memory objects are just 5 and 6. "a" and "b" are names that move
among objects as needed by the "assignment"
By the way, a classic language like C has features like this too;
they're called pointers.

In C terms, ALL Python variable NAMES are pointers; and assignment
changes the address the variable name points to... "a += 1" does not
change the object at the memory location that "a" had been referencing,
but instead computed a new object at some other location, and made "a"
reference that new object.
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
S

Steven D'Aprano

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.
 
S

Steven D'Aprano

I can try this in interactive mode:
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:

py> 5 + 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]
 
D

Dennis Lee Bieber

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.
I'm using a simplistic model, but never meant to imply the object
knows the name itself... at least to me the name is not /inside/ the
object (hence not known by the object) (think of the object as an
anonymous box containing a value)... The various names are on slips of
paper that get taped to the outside of the box (or to strings that get
taped to the box, if one wants to consider a namespace as a container of
its own, with the slips of paper -- the strings then weave through the
system to where the object itself is located).

--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
A

Alex Martelli

Dennis Lee Bieber said:
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
 
J

jamadagni

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:
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.
 
G

Ganesan Rajagopal

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top