473,765 Members | 2,203 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 #1
24 1804
In <11************ **********@p79g 2000cwp.googleg roups.com>, asincero
wrote:
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"?
Not really the Python way I'd say. What if `c` is of type `long` for
instance? Your code would stop with an assertion error for a value that
should work. Strict type checking prevents "duck typing" which is a quite
fundamental concept in Python.

Ciao,
Marc 'BlackJack' Rintsch
Aug 24 '06 #2

ArcadioWould it be considered good form to begin every method or
Arcadiofunction with a bunch of asserts checking to see if the
Arcadioparamete rs are of the correct type (in addition to seeing if
Arcadiothey meet other kinds of precondition constraints)?

If it works for you. It's not generally considered Pythonic though. You
should probably read up on "duck typing". Some food for thought: Do you
normally care that the object passed to foo() is a real honest-to-goodness
file object, or do you just care that it has a write() method? You will
learn soon enough if it doesn't, and not that much later than if you have an
assert at the beginning of your function. Of course, sometimes you do truly
care about the type of an object. Then you test. When you care.

ArcadioThis is something I miss from working with more stricter
Arcadiolanguage s like C++, where the compiler will tell you if a
Arcadioparamete r is the wrong type.

It's a mistake to think that Python's typing is somehow less strict than
C++'s. It's not like Perl where 1 + "2" is valid. It's simply that its
type checks are performed at run-time, not at compile-time. If you're
desparate to have some assistance with your code before you run it, check
out pylint and pychecker.

Skip
Aug 24 '06 #3

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 (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
Many developers who move from a statically-typed languages to dynamic
ones go through this same sort of thought process. I was no different
in that regard, but as I've done more and more Python, I've found that
I just don't encounter type issues all that often. Above all, I see
duck typing as a net benefit - its inherent flexibility far outweighs
the lack of "compile-time" type safety, in my mind.

Along these lines, I'll point you to this article by Bruce Eckel called
"Strong Typing vs. Strong Testing":
http://www.mindview.net/WebLog/log-0025. The bottom line: Focus on unit
tests rather than explicit type checks when you want to verify the
runtime safety of your code. You'll find many more errors this way.

Hope this helps...
--dave

Aug 25 '06 #4
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 (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
That's bad form. If you insist on doing something like this, at least
use "isinstance (a, str)" instead of typeof. But even that breaks duck
typing; if a is a unicode string, that'll fail when the function may
work fine for unicode strings.

You could, of course, test explicitly for the interface you need (e.g.
if you need a to have "lower" and "rjust" methods, do assertion tests
for them). But in practice you're generally better off simply using
the object and getting the exception a few lines lower.

Much of the power of dynamic typing comes from the duck typing concept,
so you should really try to familiarize yourself with it.
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.
Stricter is the wrong word. Python is strictly typed. The difference
here is dynamic vs. static typing.
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"?
There are 3 main things that you can do to help here:
1. Choose better names for the arguments so that it's obvious what they
are. I don't advocate Hungarian naming, normally something like "url"
or "shoeSize" will be strongly indicative of what kinds of values are
acceptable.
2. Write docstrings. That will not only document the types but also
how they're used, what gets returned, and perhaps limits on exactly
what ranges of values are acceptable.
3. Write unit tests. They'll catch far more errors than static typing
ever will.

Aug 25 '06 #5
On 24 Aug 2006 20:53:49 -0700, sj*******@yahoo .com <sj*******@yaho o.comwrote:
That's bad form. If you insist on doing something like this, at least
use "isinstance (a, str)" instead of typeof. But even that breaks duck
typing; if a is a unicode string, that'll fail when the function may
work fine for unicode strings.
To check both str and unicode, you could use "isinstance (a, basestring)".
Aug 25 '06 #6
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 (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
Generally asserts should be used to "enforce" invariants of your code
(as opposed to typechecking), or to check certain things while
debugging.

FWIW, if I saw code that that you presented here I'd assume the
programmer who wrote it was either very new(-bie-ish) or just very very
paranoid, so I guess I could say it's not pythonic... :-)

BTW, speaking of "strictness ", "more stricter" is invalid English,
just "stricter" is the "correct" form. ;-)

Peace,
~Simon

Aug 25 '06 #7

"Simon Forman" <ro*********@ya hoo.comwrote:

8<-------------------------------------------------------------

| BTW, speaking of "strictness ", "more stricter" is invalid English,
| just "stricter" is the "correct" form. ;-)

or alternatively the construct "more strict" is also acceptable - Hendrik
Aug 25 '06 #8
On 2006-08-25, Simon Forman <ro*********@ya hoo.comwrote:
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 (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

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?

--
Antoon Pardon
Aug 28 '06 #9
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. 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.

--Scott David Daniels
sc***********@a cm.org
Aug 28 '06 #10

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

Similar topics

24
3612
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
2713
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
1080
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
1728
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
1372
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
2662
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
3651
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
6054
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
9568
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
10156
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...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
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...
1
7375
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
6649
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
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2805
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.