473,770 Members | 1,778 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this a good idea or a waste of time?

Would it be considered good form to begin every method or function with
a bunch of asserts checking to see if the parameters are of the correct
type (in addition to seeing if they meet other kinds of precondition
constraints)? Like:

def foo(a, b, c, d):
assert type(a) == str
assert type(b) == str
assert type(c) == int
assert type(d) == bool
# rest of function follows

This is something I miss from working with more stricter languages like
C++, where the compiler will tell you if a parameter is the wrong type.
If anything, I think it goes a long way towards the code being more
self documenting. Or is this a waste of time and not really "the
Python way"?

-- Arcadio

Aug 24 '06
24 1806
On 2006-08-28, Scott David Daniels <sc***********@ acm.orgwrote:
Antoon Pardon wrote:
>On 2006-08-25, Simon Forman <ro*********@ya hoo.comwrote:
>>...
Generally asserts should be used to "enforce" invariants of your code
(as opposed to typechecking), or to check certain things while
debugging.

I don't understand this argument. Can't type checking be seen as
enforcing a code invariant?
But it is practically never the "right" invariant.
And who decides what is and what is not the "right" invariant?
You don't usually
mean type(x) == int, but rather something like x is a prime between 2
and 923. Or 5< x**4 < 429, or _something_ problem specific. saying
that x must be an int is almost always simultaneously too specific and
too general.
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.

--
Antoon Pardon
Aug 28 '06 #11
Antoon Pardon wrote:
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.
I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.

Aug 28 '06 #12
asincero wrote:
Would it be considered good form to begin every method or function
with a bunch of asserts checking to see if the parameters are of the
correct type [...]

This is something I miss from working with more stricter languages
like C++, where the compiler will tell you if a parameter is the
wrong type. If anything, I think it goes a long way towards the code
being more self documenting. Or is this a waste of time and not
really "the Python way"?
Definitely "unpythonic ".

It's generally better to ask if an object "acts right" rather than if
it "is right". In other words, if you're going to add two objects,
it's more important that they support addition than that they
are integers, longs, floats, or matrices. This makes your code
more portable, because people might create new numeric types
(say "measuremen ts" or "rationals" ). If you leave things open,
then the author of such modules can use your code (they may
have to test special cases if their objects don't behave the same
way as you expect them to, but that becomes their problem).
On the other hand, if your code just arbitrarily breaks because
the objects fail a typecheck, that's an unnecessary obstacle.

If you need assertions, it's better to ask more specifically what will
break the code (e.g. objects that don't support addition -- which
you can check by doing an addition or by looking for th __add__
method. But then, if you need addition support, then your code
probably already has an addition, so why not just let it fail there?).

So be more minimal and throw in checks for specific problems --
especially the ones that would cause a wrong result rather than
an exception.

Cheers,
Terry
--
Terry Hancock (ha*****@Anansi Spaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com

Aug 29 '06 #13
On 2006-08-28, sj*******@yahoo .com <sj*******@yaho o.comwrote:
Antoon Pardon wrote:
>There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.

I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.
That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.

--
Antoon Pardon
Aug 29 '06 #14
At Tuesday 29/8/2006 01:28, Antoon Pardon wrote:
Antoon Pardon wrote:
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.
I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.

That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.
In any case, I don't see how this supports the original claim that
strict type checking input params is good practice.

Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 29 '06 #15
Antoon Pardon wrote:
On 2006-08-28, sj*******@yahoo .com <sj*******@yaho o.comwrote:
Antoon Pardon wrote:
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.
I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.

That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.
What the hell are you talking about?

I'm curious: what is the meaning, to you, of the word "this" in your
sentence above?
>
--
Antoon Pardon
Aug 29 '06 #16
On 2006-08-29, Gabriel Genellina <ga******@yahoo .com.arwrote:
At Tuesday 29/8/2006 01:28, Antoon Pardon wrote:
Antoon Pardon wrote:
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.

I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.

That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.

In any case, I don't see how this supports the original claim that
strict type checking input params is good practice.
I'm not defending that claim. I'm just putting question marks
with the claim that strict type checking input parameters is
bad practice.

--
Antoon Pardon
Aug 29 '06 #17
At Tuesday 29/8/2006 02:45, Antoon Pardon wrote:
>That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.
In any case, I don't see how this supports the original claim that
strict type checking input params is good practice.

I'm not defending that claim. I'm just putting question marks
with the claim that strict type checking input parameters is
bad practice.
I think others have shown enough examples of good things that can be
done by *not* enforcing a specific type...

Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 29 '06 #18
On 2006-08-29, Simon Forman <ro*********@ya hoo.comwrote:
Antoon Pardon wrote:
>On 2006-08-28, sj*******@yahoo .com <sj*******@yaho o.comwrote:
Antoon Pardon wrote:
There seem to be enough problems that work with ints but not with
floats. In such a case enforcing that the number you work with
is indeed an int seems fully appropiate.

I've _never_ seen a case where enforcing types in the manner of the OP
is appropriate.

It fails with trivial wrappers like

class myInt(int):
def printFormatted( self):
..........

Even looser checking with isinstance is rarely right. You may want to
exclude floats, but that doesn't mean you want to exclude int-like
objects that don't inherit from int.

That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.

What the hell are you talking about?
Yes, I should have been more clearer.
I'm curious: what is the meaning, to you, of the word "this" in your
sentence above?
That something like "type(x) == int" or "isinstance (x, int)" doesn't
allow to check for all int like objects, nor that there is some python
idiom that should allow you to test for such a thing (although it might
be circumvented).

With that second sentence I mean that there could exist a python
convention that prescribed that all int like objects had to be
subtypes of int. In that case code that followed the convention
could use "isinstance (x, int)" to check for int like objects.

--
Antoon Pardon
Aug 29 '06 #19
On 2006-08-29, Gabriel Genellina <ga******@yahoo .com.arwrote:
At Tuesday 29/8/2006 02:45, Antoon Pardon wrote:
>>That may be true. But one may wonder if this is a failing of the
programmer or a failing of the language that doesn't support
such things.

In any case, I don't see how this supports the original claim that
strict type checking input params is good practice.

I'm not defending that claim. I'm just putting question marks
with the claim that strict type checking input parameters is
bad practice.

I think others have shown enough examples of good things that can be
done by *not* enforcing a specific type...
That doesn't contradict that in other situations good things can be
done by enforcing specific type or at least limiting to a subset
of specific types.

--
Antoon Pardon
Aug 29 '06 #20

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

Similar topics

24
3613
by: matty | last post by:
Go away for a few days and you miss it all... A few opinions... Programming is a craft more than an art (software engineering, not black magic) and as such, is about writing code that works, first and foremost. If it works well, even better. The same goes for ease of maintenance, memory footprint, speed, etc, etc. Most of the time, people are writing code for a use in the *real world*, and not just as an academic exercise. Look at...
24
2715
by: Andrew Koenig | last post by:
PEP 315 suggests that a statement such as do: x = foo() while x != 0: bar(x) be equivalent to while True:
0
1081
by: Kate Stahl | last post by:
--_E4.3.C_FED..A. Content-Type: text/plain; Content-Transfer-Encoding: quoted-printable Investor Insights Newsletter features companies with revolutionary product= s and soaring revenues. We focus on stocks that are undervalued and have gone un= noticed that will increase dramatically to become one of our outstanding performer= s in the
5
1731
by: Hugo Elias | last post by:
Hi all, I have an idea for a better IDE. Though I don't have the skills required to write such a thing, if anyone's looking for a killer app, maybe this is it. If I'm typing at a rate of 10 characters per second (which is *very* fast for sustained code writing), then my computer is executing around 200,000,000 instructions as it waits for the next keystroke to
14
4649
by: dreamcatcher | last post by:
I always have this idea that typedef a data type especially a structure is very convenient in coding, but my teacher insisted that I should use the full struct declaration and no further explanations, so I wonder is there any good using typedef ? and I also know that when a data type being typedefed become an abstract data type, so what exactly is an abstract data type, is it any good ? -- Posted via http://dbforums.com
18
1373
by: vashwath | last post by:
Hi all, As per our coding rule, a line should not have more than 80 characters. When accessing a structure elements which are deeply nested, we are not able follow this rule. To acheive this Can we use macro? For example, struct1.str1.strct3=struct2.str2.st1.s1 + struct3.str3.st3.s3; #define STRUCT2 struct2.str2.st1.s1
43
2665
by: Sensei | last post by:
Hi! I'm thinking about a good programming style, pros and cons of some topics. Of course, this has nothing to do with indentation... Students are now java-dependent (too bad) and I need some serious motivations for many issues... I hope you can help me :) I begin with the two major for now, others will come for sure! - function variables: they're used to java, so no pointers. Personally I'd use always pointers, but why could be better...
54
3653
by: sam.s.kong | last post by:
Hi! I've been programming ASP for 5 years and am now learning PHP. In ASP, you can use GetRows function which returns 2 by 2 array of Recordset. Actually, it's a recommended way in ASP when you access DB as it disconnects the DB earlier. Also, it's handy as you can directly access any data in the array without looping.
21
6056
by: petermichaux | last post by:
Hi, I've been asking questions about library design over the last week and would like to get feedback on my overall idea for a JavaScript GUI library. I need a nice GUI library so there is a good chance I will write this as I need new widgets. I haven't found anything like this and I'm surprised/disapointed this doesn't already exist. My library prototype works nicely. I think parts of these ideas are not commonly used for JavaScript...
0
9617
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
9454
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
10257
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
8931
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
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
5354
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...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.