473,324 Members | 2,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Static Typing in Python

How do I force static typing in Python?

-Premshree Pillai

=====
-Premshree
[http://www.qiksearch.com/]

__________________________________________________ ______________________
Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more.
Go to: http://in.insurance.yahoo.com/licspecial/index.html

Jul 18 '05 #1
15 2635
"Premshree Pillai" <pr**************@yahoo.co.in> wrote in message
news:ma**************************************@pyth on.org...
How do I force static typing in Python?
By using another language. Try Java.

John Roth
-Premshree Pillai

=====
-Premshree


Jul 18 '05 #2
Premshree Pillai schrieb:
How do I force static typing in Python?


You have to enforce it by code instead of declaration, i.e. you
have to do runtime type checking. This could be done e.g. within
a class:

class doesTypeChecking:
def __init__self():
aString = ""
aFloat = 0.0

def __setAttr__(self, attr, value):
if type(self.__dict__[attr] != type(value):
raise ValueError, "Type mismatch for attribute %s\n" % attr

Similar code could be used to check parameters of a function/
method.

Have looked at pychecker? It's not part of the python
distribution but it could help here.

Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplusr.de
-------------------------------------------------------------------
Jul 18 '05 #3
Peter Maas schrieb:
class doesTypeChecking:
def __init__self():


Correction:
def __init__(self):

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplusr.de
-------------------------------------------------------------------
Jul 18 '05 #4
Peter Maas <fp********@netscape.net> writes:
Premshree Pillai schrieb:
How do I force static typing in Python?


You have to enforce it by code instead of declaration, i.e. you
have to do runtime type checking.


Just what do you understand "static typing" to mean ?
Jul 18 '05 #5
Peter Maas schrieb:
class doesTypeChecking:
def __init__(self):
aString = ""
aFloat = 0.0


sorry, I was too hasty. Here is the tested code:

class doesTypeChecking:
def __init__(self):
self.__dict__["aString"] = ""
self.__dict__["aFloat"] = 0.0

def __setattr__(self, attr, value):
if type(self.__dict__[attr]) != type(value):
raise ValueError, "Type mismatch for attribute %s\n" % attr

Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplusr.de
-------------------------------------------------------------------
Jul 18 '05 #6
On 12 Mar 2004 13:56:53 +0100, Jacek Generowicz
<ja**************@cern.ch> wrote:
Peter Maas <fp********@netscape.net> writes:
Premshree Pillai schrieb:
> How do I force static typing in Python?


You have to enforce it by code instead of declaration, i.e. you
have to do runtime type checking.


Just what do you understand "static typing" to mean ?

Doesn't that usually mean typing with a high noise-to-signal ratio?
Lots of punctuation and such.
;-)
--dang
Jul 18 '05 #7
Jacek Generowicz <ja**************@cern.ch> writes:
Peter Maas <fp********@netscape.net> writes:
Premshree Pillai schrieb:
How do I force static typing in Python?


You have to enforce it by code instead of declaration, i.e. you
have to do runtime type checking.


Just what do you understand "static typing" to mean ?


I ask because I am prepared to accept that you have a different
working definition of "static typing" from mine, but people who
actually want static typing typically want it because they think it
gives them the following advantages:

a) type errors caught at compile time,

b) faster program exectution.

The code you showed:
class doesTypeChecking:
def __init__(self):
self.__dict__["aString"] = ""
self.__dict__["aFloat"] = 0.0

def __setattr__(self, attr, value):
if type(self.__dict__[attr]) != type(value):
raise ValueError, "Type mismatch for attribute %s\n" % attr


will catch no type errors at compile time, and will slow down
execution, so I suspect that Premshree will be disapponinted with it.
(BTW, my definition of "static typing" is "type checking is done at
compile time" ... your example really looks like dynamic typing to
me ... albeit with some restrictions on attribute types.)
Premshree: Python is dynamically typed. There is no way to enforce
static typing. There is something called "pychecker" which
might be of some help to you. Why do you think that you
want static typing in Python ?
Jul 18 '05 #8
Dang Griffith <no*****@noemail4u.com> writes:
On 12 Mar 2004 13:56:53 +0100, Jacek Generowicz
<ja**************@cern.ch> wrote:

Just what do you understand "static typing" to mean ?

Doesn't that usually mean typing with a high noise-to-signal ratio?


What, you mean like this:

std::list<std::pair<int, std::string> > l;
l.push_back(std::pair<int, std::string>(1,"hello"));

as opposed to

l = [(1, 'hello')]

?

I like your definition :-)
Jul 18 '05 #9
On Sat, 13 Mar 2004 07:07:50 +0000 (GMT), Premshree Pillai
<pr**************@yahoo.co.in> wrote:
--- Jacek Generowicz <ja**************@cern.ch>
Yes, I am aware that Python is dynamically typed, and
so is Perl, right? In Perl, we have the "use strict
vars" pragma to force variable declaration. Is there
something like it in Python?
No, but you can use pychecker to get similar results.
Don't you think forced variable declaration is an
important requirement in a language?


Not really. Forced variable initialization is what's important.
Unlike C, et al, and Perl, variables don't have a default
initial value. If you try reference a variable that hasn't been
initialized ("bound to a value", in python lingo), python raises a
NameError exception.

--dang
p.s.
I know technically Perl initializes to 'undef', but it's magically
treated as 0 or an empty string, depending on context, so the
effect is much the same.
Jul 18 '05 #10

"Premshree Pillai" <pr**************@yahoo.co.in> wrote in message
Anyway, what I want is to force variable declaration.
In perl we have the "use strict vars" pargma...I need
something like that...


For those of us who do not know Perl, and there are many, I suspect, on
this Python newsgroup, that means nothing ;-).

tjr


Jul 18 '05 #11
On Sat, 13 Mar 2004 14:59:42 +0000 (GMT), Premshree Pillai
<pr**************@yahoo.co.in> wrote:
--- Dang Griffith <go*****@lazytwinacres.net> wrote:
On Sat, 13 Mar 2004 07:07:50 +0000 (GMT), Premshree
Pillai
<pr**************@yahoo.co.in> wrote:
> --- Jacek Generowicz <ja**************@cern.ch>
>Yes, I am aware that Python is dynamically typed,

and
>so is Perl, right? In Perl, we have the "use strict
>vars" pragma to force variable declaration. Is

there
>something like it in Python?


No, but you can use pychecker to get similar
results.
>Don't you think forced variable declaration is an
>important requirement in a language?


Not really. Forced variable initialization is
what's important.
Unlike C, et al, and Perl, variables don't have a
default
initial value. If you try reference a variable that
hasn't been
initialized ("bound to a value", in python lingo),
python raises a
NameError exception.

--dang
p.s.
I know technically Perl initializes to 'undef', but
it's magically
treated as 0 or an empty string, depending on
context, so the
effect is much the same.
--
http://mail.python.org/mailman/listinfo/python-list


Not forcing variable initialization does have its
problems. Here's what I mean: http://www.livejournal.com/users/pre...d=53376#t53376


Yes, I agree. That is one reason I like Python.
It has forced variable *initialization*. You cannot use a variable
that has not been initialized. In fact, the act of initializing a
variable is what makes the variable exist.

I do not think forced *declaration* is important, except perhaps in
C/++/#/Java, Pascal, Ada, etc.

I see the typo in the pseudo-code example. PyChecker will catch that.
I typed in your code, converted it to Python, and ran pychecker on it:
Warnings...
bluesmoon.py:12: Local variable (my_varaible) not used

--dang
Jul 18 '05 #12
Dang Griffith <go*****@lazytwinacres.net> writes:
Not forcing variable initialization does have its problems. Here's
what I mean:
http://www.livejournal.com/users/pre...d=53376#t53376
Yes, I agree. That is one reason I like Python.
It has forced variable *initialization*. You cannot use a variable
that has not been initialized.


But there is nothing to prevent you from assigning to a previously
non-existing variable, which is what Premshree is concerned about.
In fact, the act of initializing a variable is what makes the
variable exist.


Exactly, make a typo, and the compiler won't notice.

This can indeed be a minor annoyance in interactive
exploration. However, the development of a real program, backed by a
test suite, will catch the problem in no time.

It's just one of the thousands of possible styles of bugs that you can
introduce into the program ... ALL of which will be caught by a decent
test suite. Adding restrictions to a language just to catch one of the
many of styles of possible bugs is counterproductive. Support your
development with a decent test suite, and use the most flexible
language you can get your hands on.
Jul 18 '05 #13
Premshree Pillai <pr**************@yahoo.co.in> wrote:
How do I force static typing in Python?


If you want

def foo(int bar):
print bar

then you probably want to give Pyrex a try.

Theek hai.

Ramón
Jul 18 '05 #14
On 15 Mar 2004 09:44:50 +0100, Jacek Generowicz
<ja**************@cern.ch> wrote:
Dang Griffith <go*****@lazytwinacres.net> writes:
>Not forcing variable initialization does have its problems. Here's
>what I mean:
>http://www.livejournal.com/users/pre...d=53376#t53376


Yes, I agree. That is one reason I like Python.
It has forced variable *initialization*. You cannot use a variable
that has not been initialized.


But there is nothing to prevent you from assigning to a previously
non-existing variable, which is what Premshree is concerned about.
In fact, the act of initializing a variable is what makes the
variable exist.


Exactly, make a typo, and the compiler won't notice.

This can indeed be a minor annoyance in interactive
exploration. However, the development of a real program, backed by a
test suite, will catch the problem in no time.


Ironically, the error in the code that Premshree referenced, once
fixed for Python syntax, get in an infinite loop. So, a test suite
will not catch the problem, because the test will never finish.

But obviously, if one is using test-driven development, it should
be pretty clear which code has a problem.

--dang
Jul 18 '05 #15
On Mon, 15 Mar 2004 10:47:08 +0000 (GMT), Premshree Pillai
<pr**************@yahoo.co.in> wrote:
I do not think forced *declaration* is important,
except perhaps in
C/++/#/Java, Pascal, Ada, etc.


Why the discrimination? Considering programming
languages in general, what do you have to say with
forced declaration?

I don't think the discrimination is justified
considering that all of them belong to the
procedural/OOP (read same) paradigm.


I was being half-facetious. I would have included languages
from other paradigms if I knew ones that required declaring
variable names. (They probably exist, but I don't know them.)
It is important in those languages because they require it to
compile/execute. I.e., you can't write a valid program in those
languages without statically declaring the variable names. In
addition, you must declare their compile-time (static) type. Those
are separate things, though part of a single statement in those
languages.

--dang
Jul 18 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Michael Muller | last post by:
Is there currently any plan to introduce static typing in any future version of Python? (I'm not entirely sure that "static typing" is the right term: what I'm talking about is the declaration of...
19
by: bearophile | last post by:
This is my first post here, I hope this is the right place to talk about such things. I have few comments and notes on the Python language. I've just started to learn it; this is negative because...
49
by: bearophileHUGS | last post by:
Adding Optional Static Typing to Python looks like a quite complex thing, but useful too: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I have just a couple of notes: Boo...
6
by: Christian Convey | last post by:
Hi guys, I'm looking at developing a somewhat complex system, and I think some static typing will help me keep limit my confusion. I.e.: ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.