473,655 Members | 3,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type checking

Explicit type checking is not typically seen in Python code, and usually
that's not a big problem; most typing errors are likely to raise a TypeError
or AttributeError sooner than later. There are cases, though, where typing
errors are not caught (at least not early) because different classes happen
to have methods with the same name; that's really subtle with the special
methods like __eq__, __hash__, etc. that are common to all (or at least
many) classes.

It happened to me when I was passing arguments of some type B to a function
instead of the correct type A; these arguments were entered as keys in a
dictionary, and since both A and B were hashable the interpreter didn't
complain. Of course, when later I was trying to retrieve the A()s I thought
I had entered, I couldn't find them (debugging was even harder in this case
because B was essentially a wrapper for A and the __str__ of both classes
was deliberately the same, so the A()s appeared to be in the dict; that's
not the issue here though).

I wonder if people have come up with such pitfalls in practice or I was just
careless. In any case, I was tempted enough to write a simple extensible
runtime type checking module, which can be handy, at least during
development. It's extensible in the sense that a "type" can be any
constraint, not just a python type or class. Here's an example of usage:

def foo(name, age, children, phonebook):
assert TypeChecker.ver ify(
(age, int),
(name, TupleOf((str,st r))),
(children, ListOf(Child)),
(phonebook, DictOf(str, ContainerOf(Pho ne))))

foo(name = ("Paul", "Smith"),
age = 23,
children = [Child(), Child()],
phonebook = {
"Mike": (Phone(), Phone()),
"office": [Phone()]
})

ContainerOf, TupleOf, ListOf and DictOf are all extensions of the abstract
TypeChecker class, providing some limited but common templated-type
checking. Of course in practice most complex structures (e.g. phonebook)
would be encapsulated in a class, so it's questionable whether such
functionality adds up anything to a list of "assert isinstance(obje ct,type)"
statements. Any ideas or suggestions are welcome.

George
Jul 18 '05 #1
3 2349
George Sakkis wrote:
I wonder if people have come up with such pitfalls in practice or I was just
careless. In any case, I was tempted enough to write a simple extensible
runtime type checking module, which can be handy, at least during
development. It's extensible in the sense that a "type" can be any
And in other places: some functions need to behave differently depending
on the types of their arguments. When interfaces come into play,
isinstance() just doesn't cut it.
ContainerOf, TupleOf, ListOf and DictOf are all extensions of the abstract
TypeChecker class, providing some limited but common templated-type
checking. Of course in practice most complex structures (e.g. phonebook)
would be encapsulated in a class, so it's questionable whether such
functionality adds up anything to a list of "assert isinstance(obje ct,type)"
statements. Any ideas or suggestions are welcome.


Along with TupleOf, ListOf, DictOf, etc., include interface checkers,
such as SequenceOf and MappingOf. People will love you for it.

Jul 18 '05 #2
Christopher T King <sq******@WPI.E DU> wrote in message news:<Pi******* *************** *************** *@ccc1.wpi.edu> ...

(...) some functions need to behave differently depending
on the types of their arguments (...)


Uhm.. this doesn't seem very OO to me; if a function needs to behave
differently for different argument types, it's an indication that it
should be defined as method, overriden for each type of interest (or
multiple-dispatched if more than one arguments are involved).

George
Jul 18 '05 #3
George, don't forget to have a look at the Traits package of scipy.

HTH
Franz

George Sakkis wrote:
Explicit type checking is not typically seen in Python code, and usually
that's not a big problem; most typing errors are likely to raise a TypeError
or AttributeError sooner than later. There are cases, though, where typing
errors are not caught (at least not early) because different classes happen
to have methods with the same name; that's really subtle with the special
methods like __eq__, __hash__, etc. that are common to all (or at least
many) classes.

It happened to me when I was passing arguments of some type B to a function
instead of the correct type A; these arguments were entered as keys in a
dictionary, and since both A and B were hashable the interpreter didn't
complain. Of course, when later I was trying to retrieve the A()s I thought
I had entered, I couldn't find them (debugging was even harder in this case
because B was essentially a wrapper for A and the __str__ of both classes
was deliberately the same, so the A()s appeared to be in the dict; that's
not the issue here though).

I wonder if people have come up with such pitfalls in practice or I was just
careless. In any case, I was tempted enough to write a simple extensible
runtime type checking module, which can be handy, at least during
development. It's extensible in the sense that a "type" can be any
constraint, not just a python type or class. Here's an example of usage:

def foo(name, age, children, phonebook):
assert TypeChecker.ver ify(
(age, int),
(name, TupleOf((str,st r))),
(children, ListOf(Child)),
(phonebook, DictOf(str, ContainerOf(Pho ne))))

foo(name = ("Paul", "Smith"),
age = 23,
children = [Child(), Child()],
phonebook = {
"Mike": (Phone(), Phone()),
"office": [Phone()]
})

ContainerOf, TupleOf, ListOf and DictOf are all extensions of the abstract
TypeChecker class, providing some limited but common templated-type
checking. Of course in practice most complex structures (e.g. phonebook)
would be encapsulated in a class, so it's questionable whether such
functionality adds up anything to a list of "assert isinstance(obje ct,type)"
statements. Any ideas or suggestions are welcome.

George

Jul 18 '05 #4

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

Similar topics

23
2833
by: sashan | last post by:
I'm a Python newbie. I have been using c++ for 5 years and before that I was programming in Pascal. The one thing that annoys me about python is dynamic typing because I find myself making typographical errors of the sort that would under C++ be picked up by the compiler at compiler time. With Python I have to wait for the error to appear at runtime in order for me to correct it. I find this inefficient. Any advice about how to get around...
9
3654
by: Jon Perez | last post by:
I have a C extension function into which I pass a list of lists of tuples: , , , ] I then unpack the values (down to the tuple elements) into their C values using:
5
2995
by: Tongu? Yumruk | last post by:
I have a little proposal about type checking in python. I'll be glad if you read and comment on it. Sorry for my bad english (I'm not a native English speaker) A Little Stricter Typing in Python - A Proposal As we all know, one of the best things about python and other scripting languages is dynamic typing (yes I know it has advantages and disadvantages but I will not discuss them now). Dynamic typing allows us to change types of...
6
14312
by: Web Developer | last post by:
Hi, I come across the term "type checking" very often in my readings on C++, and have never heard it in Java. Besides the simplistic answer that it checks the "type", what more does it mean? WD
33
707
by: Greg Roberts | last post by:
We have a large code base, mainly C but with some C++ which we wish to check for existing issues in an effort to be proactive. I have downloaded the open source GLINT program but am having big problems trying to get it to run. I will be looking at PC-Lint at http://www.gimpel.com/ Does anyone have any other recommendations, it can be commercial s/w for
3
2110
by: Vinodh Kumar P | last post by:
Whenever I read any C++ literature I find the words "C++ is statically type checked".OK.Agreed. Is there any language that supports "Dynamic type checking"? In such a case any type can be assigned to any other type during compile time?
20
2081
by: Xiaoshen Li | last post by:
Hi, I am reading the book "Concepts of programming languages" by R. W. Sebesta. He said: "One of the most important reasons why C is both liked and disliked is its lack of complete type checking. For example, functions can be written for which parameters are not type checked. Those who like C appreciate the flexibility; those who do not like it find it too insecure."
13
1572
by: Gabriel Genellina | last post by:
En Mon, 06 Oct 2008 11:19:58 -0300, Joe Strout <joe@strout.netescribió: Apart from the wise words that others have said, I'd add that I see no point in identifier prefixes when they merely indicate "type" (in the Python sense or even a broader sense) - called "system Hungarian notation" by some. In contrast, the prefix used in "apps Hungarian notation" declares the "kind" or "intent" of the variable, and it may be useful in some cases....
16
3449
by: Joe Strout | last post by:
Let me preface this by saying that I think I "get" the concept of duck- typing. However, I still want to sprinkle my code with assertions that, for example, my parameters are what they're supposed to be -- too often I mistakenly pass in something I didn't intend, and when that happens, I want the code to fail as early as possible, so I have the shortest possible path to track down the real bug. Also, a sufficiently clever IDE could use...
0
8380
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8296
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8710
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2721
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1928
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.