473,407 Members | 2,359 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,407 software developers and data experts.

Specifing arguments type for a function

I have a function

def f(the_arg):
....

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?

Thnx
PAolo

--
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
Jun 20 '06 #1
18 1437
Paolo Pantaleo wrote:
I have a function

def f(the_arg):
...

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?


Yes and no. You can ensure that the passed object is a list, by calling e.g.

def f(arg):
if not isinstance(arg, list):
raise "Not a list!"
Alternatively, you can just use it as an iterable - and the exception will
come from arg not being iterable.

But what you can't do is make python complain about this:

def f(arg):
for e in arg:
print e
f(100)

before actually calling f. It will always fail at runtime.

Diez
Jun 20 '06 #2
> Paolo Pantaleo wrote:
I have a function

def f(the_arg):
...

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?


Yes and no. You can ensure that the passed object is a list, by calling e.g.

def f(arg):
if not isinstance(arg, list):
raise "Not a list!"
Alternatively, you can just use it as an iterable - and the exception will
come from arg not being iterable.

But what you can't do is make python complain about this:

def f(arg):
for e in arg:
print e
f(100)

before actually calling f. It will always fail at runtime.

Diez


What about
def f(arg):
if type(arg)=='list':
#do something

--
---
Rony Steelandt
BuCodi
rony dot steelandt (at) bucodi dot com

Visit the python blog at http://360.yahoo.com/bucodi
Jun 20 '06 #3
> What about
def f(arg):
if type(arg)=='list':
#do something


Several things:

- list is a string in your code - which wont work:
type([]) == 'list' False

It needs to be list w/o quotes.
- you won't get sublclasses of list:
class Foo(list): .... pass
.... type(Foo()) == list

False

So better use isinstance, as I already mentioned.

Diez
Jun 20 '06 #4
Rony Steelandt wrote:
Paolo Pantaleo wrote:
I have a function

def f(the_arg):
...

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?

Yes and no. You can ensure that the passed object is a list, by
calling e.g.

def f(arg):
if not isinstance(arg, list):
raise "Not a list!"
Alternatively, you can just use it as an iterable - and the exception
will
come from arg not being iterable.

But what you can't do is make python complain about this:

def f(arg):
for e in arg:
print e
f(100)

before actually calling f. It will always fail at runtime.

Diez

What about
def f(arg):
if type(arg)=='list':


FWIW, type(<some_type>) returns a type object, not a string. So your
test will always fail. A right way to write this is:
if type(arg) is type([]):
...
#do something


Usually a very bad idea. It defeats the whole point of duck-typing. In
most cases, you don't care about the concrete class - all you want is an
object that implements an (implied) interface.

NB : I say 'usually' because there are a very few cases where testing
the concrete class can make sens - but there again, better to use
isinstance() than type().

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 20 '06 #5
Le Mardi 20 Juin 2006 12:29, Rony Steelandt a écrit*:
What about
def f(arg):
* * if type(arg)=='list':
* * * * #do something


And if arg's type is subclass of list ?
The problem with isinstance is : and if arg is not of type list but is a
sequence (a instance of UserList for example) ?

The general case in python is duck typing, that means you define apis that
accept file-like object, iterables, dict-like (mapping) objects, string like
objects...

The problem with iterables is that they don't all implement the __iter__
attribute, for compatibility purpose the right test should be :

if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling
code
--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 20 '06 #6
bruno at modulix wrote:
if type(arg) is type([]):


Just a tiny nitpick....
You can just use 'list' instead of 'type([])'

if type(arg) is list :
# blah blah
Regards
Sreeram
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEl9xDrgn0plK5qqURApfbAJ4n3Fluokwk0545LsDP6T BfwcO/1ACgjI3E
FtSBYn8mx3WQge58BsSiekY=
=TRfL
-----END PGP SIGNATURE-----

Jun 20 '06 #7
Le Mardi 20 Juin 2006 13:28, Maric Michaud a écrit*:
if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') :
* * raise ValueError('Function accepts only iterables') # or error handling
code


oops, hasattr of course :

if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 20 '06 #8
Maric Michaud wrote:
Le Mardi 20 Juin 2006 13:28, Maric Michaud a écrit :
if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling
code


oops, hasattr of course :

if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling


This is ok - in theory. In practice I've found that e.g. strings are
more often than not handled as scalars although they are typically
iterables. Also tuples may or may not be considered as iterables,
depending on what they are used for. The definition of scalar is
application-dependent, that's why there is not an isscalar() builtin.

George

Jun 20 '06 #9
K.S.Sreeram wrote:
bruno at modulix wrote:
if type(arg) is type([]):

Just a tiny nitpick....
You can just use 'list' instead of 'type([])'


I know. Note that I wrote "*A* right way to write this", not "*The*
right way..."

And FWIW, you could also use arg.__class__ instead of type(arg).

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 20 '06 #10
Paolo Pantaleo wrote:
I have a function

def f(the_arg):
...

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?


I wrote a cool function decorator just for that purpose. It's posted on
the Python Decorator Library at:

http://wiki.python.org/moin/PythonDe...348f78db34303e
If you use it, you will be able to simply write:

@accepts(list)
def f(the_arg):
...

and you will get a warning message if the_arg is not a list. Or, if you
want an exception raised, then just:

@accepts(list, debug=2)
def f(the_arg):
...

Let me know what you think, if you do end up using it. I'm eager for
feedback.

Jun 21 '06 #11
George Sakkis a écrit :
Maric Michaud wrote:

Le Mardi 20 Juin 2006 13:28, Maric Michaud a écrit :
if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling
code
oops, hasattr of course :

if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling

This is ok - in theory. In practice I've found that e.g. strings are
more often than not handled as scalars although they are typically
iterables.
hasattr('', '__iter__') False
Also tuples may or may not be considered as iterables,
depending on what they are used for. hasattr((), '__setitem__') False hasattr('', '__setitem__')

False
The definition of scalar is
application-dependent, that's why there is not an isscalar() builtin.

Jun 22 '06 #12
Paolo Pantaleo:
and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?


I suggest this very good library, typecheck:
http://oakwinter.com/code/typecheck/

Bye,
bearophile

Jun 22 '06 #13
Bruno Desthuilliers wrote:
George Sakkis a écrit :
This is ok - in theory. In practice I've found that e.g. strings are
more often than not handled as scalars although they are typically
iterables.
>>> hasattr('', '__iter__') False

hasattr('', '__iter__') or hasattr('', '__getitem__')
True
Also tuples may or may not be considered as iterables,
depending on what they are used for.

>>> hasattr((), '__setitem__') False >>> hasattr('', '__setitem__')

False


What does __setitem__ have to do with iterability ?

Jun 22 '06 #14
Dennis Lee Bieber wrote:
On 22 Jun 2006 16:48:47 -0700, "George Sakkis" <ge***********@gmail.com>
declaimed the following in comp.lang.python:
What does __setitem__ have to do with iterability ?


It confirms that the object is indexable, and mutable -- ie; a list,
not a tuple or a string.


Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ? I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications (e.g.
strings). It's not rocket science.

George

Jun 23 '06 #15
Dennis Lee Bieber wrote:
On 22 Jun 2006 22:55:00 -0700, "George Sakkis" <ge***********@gmail.com>
declaimed the following in comp.lang.python:

Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ? I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications (e.g.
strings). It's not rocket science.

And the absence of the setitem would indicate such an object -- it
may be iterable in terms of retrieving subparts, but atomic WRT
modification.

That, at least, is how I interpreted the introduction of the test...


Applications that don't need to treat strings as iterables of
characters wouldn't do so even if strings were mutable. Atomicity has
to do with whether something is considered to be composite or not, not
whether it can be modified.

George

Jun 23 '06 #16
George Sakkis wrote:
Dennis Lee Bieber wrote:
On 22 Jun 2006 16:48:47 -0700, "George Sakkis" <ge***********@gmail.com>
declaimed the following in comp.lang.python:

What does __setitem__ have to do with iterability ?
It confirms that the object is indexable, and mutable -- ie; a list,
not a tuple or a string.

Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ?


Nothing.
I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications (e.g.
strings). It's not rocket science.


No, it's not rocket science.

It's not rocket science neither to understand that, for the concrete
examples you used (ie strings and tuples), it's quite easy to detect'em
without testing the concrete type.

As you said, what is to be considered as scalar and what's to be
considered as sequence highly depends on the problem at hand. But doing
the distinction does not always implies testing concrete type or mro.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 23 '06 #17
George Sakkis wrote:
Dennis Lee Bieber wrote:
On 22 Jun 2006 22:55:00 -0700, "George Sakkis" <ge***********@gmail.com>
declaimed the following in comp.lang.python:
Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ? I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications (e.g.
strings). It's not rocket science.


And the absence of the setitem would indicate such an object -- it
may be iterable in terms of retrieving subparts, but atomic WRT
modification.

That, at least, is how I interpreted the introduction of the test...

Applications that don't need to treat strings as iterables of
characters wouldn't do so even if strings were mutable. Atomicity has
to do with whether something is considered to be composite or not, not
whether it can be modified.


Sure. Do you have any generic solution for this ?
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 23 '06 #18
Paolo Pantaleo wrote:
I have a function

def f(the_arg):
...

and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?
You can state that in your documentation.

You're very likely to get a reasonable runtime error
from this when you start using the_arg in your code.

The pythonic way of programming is not with overly
strict assumptions about typing, but rather by:
a) Assuming as little as possible about the data
you get from a caller or from a called function.
b) Use a comprehensive suite of automated tests to
make sure that you find programming errors.

From a hypothetical point of view, tests can only
find bugs, and never prove that programs are correct,
but in practice, automated tests is one of the best
ways to keep bugs out of your code. Compile time
type checks can only find a small fraction of the
bugs programmers make, and the tests that find the
harder bugs will also find all the type mismatches
that are problematic in any way.

There are those who speculate that we will eventually
have methods to formally prove correctness of programs
through some kind of analysis, but static type checks
and other compile time tests are very far from doing
that.

I think you will find that this approach of assuming
as little as possible about parameters and return
values will make your code both more robust and more
flexible than a traditional approach with static
typing as in C++, Java or ADA etc.
Jul 4 '06 #19

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

Similar topics

8
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window...
7
by: A. Saksena | last post by:
Hi all, Is it possible to write a function or a macro in C++, which is capable of accepting any number of arguments. To give an example, the following should be possible: - ...
6
by: Melkor Ainur | last post by:
Hello, I'm attempting to build an interpreter for a pascal-like language. Currently, I don't generate any assembly. Instead, I just build an abstract syntax tree representing what I've parsed...
9
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar...
11
by: Neo | last post by:
Why the following code is compilable? The function abc() doesn't take any arguments, still i can call the function with arbitraty number of arguments. Even compiler doesn't show any warning. What...
9
by: Csaba Gabor | last post by:
Inside a function, I'd like to know the call stack. By this I mean that I'd like to know the function that called this one, that one's caller and so on. So I thought to do: <script...
7
by: VK | last post by:
I was getting this effect N times but each time I was in rush to just make it work, and later I coudn't recall anymore what was the original state I was working around. This time I nailed the...
11
by: -Lost | last post by:
I have this generic function (JavaScript newbie here, so don't think I am going to impress you): function blah() { var container = ''; for(var i = 0; i < arguments.length; i++) { container...
2
ADezii
by: ADezii | last post by:
When a call is made to a Sub or Function Procedure, you can supply Arguments in the exact order they appear in the Procedure's definition, or you can supply them in any position by name. To...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.