472,096 Members | 1,162 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,096 software developers and data experts.

Function parameter type safety?

Hi,

Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.

Jul 12 '07 #1
7 17477
Robert Dailey wrote:
Hi,

Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.
There is, but be careful. What about a string-like object, why would you want
to fail on that. It is better to attempt to do whatever you want to do with the
string and catch the exception.

Possible solution that I don't really like, but meets your explicit requirement:

def foo(arg1):
if isinstance(arg1, (basestring, unicode):

print "is string"
else:
print "is NOT string"

return
-Larry
Jul 12 '07 #2
Robert Dailey wrote:
Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.
In Python, you generally don't want to do this. If I have code like::

def foo(x):
if not isinstance(x, basestring):
raise ValueError('x must be a string')
return x.split()

then if someone creates a string-like object that doesn't subclass from
basestring, my code raises an exception even though the string-like
object had a .split() method and would have worked perfectly. If you
really feel like you need to give a specific error message, you could
write it instead like::

def foo(x):
try:
split = x.split
except AttributeError:
raise ValueError('x needs to have a split() method')
return split()

But generally there's no reason to do that because the AttributeError
itself would have said almost exactly the same thing.

Long story short: checking parameter types is un-Pythonic. Don't do it.

STeVe
Jul 12 '07 #3
In article <11**********************@g4g2000hsf.googlegroups. com>,
Robert Dailey <rc******@gmail.comwrote:
Hi,

Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.
At present, there isn't any built-in way to do this (see the recent
thread "PEP 3107 and stronger typing" for a long discussion).

However, you can use assert and isinstance() to check it manually:

def foo(a):
assert isinstance(a, str), "argument 'a' must be a string"
I wouldn't advocate getting carried away with this pattern since it
precludes your function from working with duck typing and defeats some
of the dynamic nature of Python. On the other hand, without such checks
the resulting exceptions from assuming an argument is one type when it
is another can be a bit misleading.

Dave
Jul 13 '07 #4
Good replies.

I'm in the process of learning Python. I'm a native C++ programmer, so
you can see how the question relates. There's a lot of cool things C++
allowed you to do with type-checking, such as function overloading.
With templates + type checking, I can create a STD version of ifstream/
ofstream in Python. However, I found it isn't possible since Python
mainly works with strings in file data instead of bytes. To write a
number 400000 to a file in python would take 6 bytes instead of 4, for
example. Anyway, I just wanted to explain why I was asking about type
checking. There's other measures I'm willing to take to get my job
done. Thanks guys.

Jul 13 '07 #5
On Jul 13, 4:53 pm, Robert Dailey <rcdai...@gmail.comwrote:
Good replies.

I'm in the process of learning Python. I'm a native C++ programmer, so
you can see how the question relates. There's a lot of cool things C++
allowed you to do with type-checking, such as function overloading.
This is an area of hot debate in Python and things are changing. You
may want
to have a look at http://www.python.org/dev/peps/pep-3119 about
interfaces,
and to http://www.python.org/dev/peps/pep-3124 about overloading and
generic functions. Both PEPs are for Python 3000, but their existence
should be an indication that people are not happy with the current
situation
in Python. You can something better than overloading already, with
P.J. Eby
modules simplegeneric and/or RuleDispatch, but I would say that they
are not
commonly used. So the right thing to do for now is to follow the good
advices you received, but keep in mind that there will be alternatives
in
the near future (such as interface checking/function overload).

Michele Simionato

Jul 13 '07 #6
On Jul 12, 5:52 pm, Robert Dailey <rcdai...@gmail.comwrote:
Hi,

Is there a way to force a specific parameter in a function to be a
specific type?
Yes; have a look at typecheck (http://oakwinter.com/code/typecheck/)
and FormEncode (http://formencode.org/Validator.html).

George

Jul 14 '07 #7
En Fri, 13 Jul 2007 11:53:41 -0300, Robert Dailey <rc******@gmail.com>
escribió:
However, I found it isn't possible since Python
mainly works with strings in file data instead of bytes. To write a
number 400000 to a file in python would take 6 bytes instead of 4, for
example.
pyimport struct
pyf = open("output.bin","wb")
pyf.write(struct.pack("l", 400000))
pyf.close()
py^Z
C:\TEMP>dir output.bin
El volumen de la unidad C no tiene etiqueta.
El número de serie del volumen es: 3828-F1AF

Directorio de C:\TEMP

14/07/2007 00:13 4 output.bin
1 archivos 4 bytes
0 dirs 18.806.763.520 bytes libres

"strings" are "strings of bytes" in Python. (If you are mostly concerned
with characters, use unicode objects).

--
Gabriel Genellina

Jul 14 '07 #8

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Derek Hart | last post: by
3 posts views Thread by Dave | last post: by
3 posts views Thread by joe bruin | last post: by
16 posts views Thread by hzmonte | last post: by
6 posts views Thread by Jack White | last post: by
32 posts views Thread by copx | last post: by
reply views Thread by leo001 | last post: by

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.