Re: Specifing arguments type for a function

2006-07-04 Thread Magnus Lycka
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.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread George Sakkis
Dennis Lee Bieber wrote:
 On 22 Jun 2006 16:48:47 -0700, George Sakkis [EMAIL PROTECTED]
 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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread George Sakkis
Dennis Lee Bieber wrote:
 On 22 Jun 2006 22:55:00 -0700, George Sakkis [EMAIL PROTECTED]
 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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread Bruno Desthuilliers
George Sakkis wrote:
 Dennis Lee Bieber wrote:
 
On 22 Jun 2006 16:48:47 -0700, George Sakkis [EMAIL PROTECTED]
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 '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread Bruno Desthuilliers
George Sakkis wrote:
 Dennis Lee Bieber wrote:
 
On 22 Jun 2006 22:55:00 -0700, George Sakkis [EMAIL PROTECTED]
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 '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-22 Thread Bruno Desthuilliers
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.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-22 Thread bearophileHUGS
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-22 Thread George Sakkis
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 ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-21 Thread Mike Duffy
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/PythonDecoratorLibrary#head-308f2b3507ca91800def19d813348f78db34303e


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.

-- 
http://mail.python.org/mailman/listinfo/python-list


Specifing arguments type for a function

2006-06-20 Thread Paolo Pantaleo
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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread Diez B. Roggisch
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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread Rony Steelandt
 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


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread Diez B. Roggisch
 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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread bruno at modulix
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 '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread Maric Michaud
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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread K.S.Sreeram
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



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Specifing arguments type for a function

2006-06-20 Thread Maric Michaud
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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread George Sakkis
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread bruno at modulix
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 '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list