473,573 Members | 2,869 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 17585
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************ **********@g4g2 000hsf.googlegr oups.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.bi n","wb")
pyf.write(struc t.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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3681
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can...
3
5238
by: Dave | last post by:
Hello all, Quoting from page 24 of "The Boost Graph Library; User Guide and Reference Manual": "It turns out that by the contravariance subtyping rule, the parameter type in the derived classes member function must be either the same type or a base class of the type as the parameter in the base class." Now please consider this code:
3
2979
by: joe bruin | last post by:
hello all. i am trying to get rid of some warnings and do "the right thing". although in this particular case, i am not sure what the right thing is. the code: typedef struct {
20
10732
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
5
5606
by: leaf | last post by:
consider these functions: void foo() { cout << "foo() called; } void sayhello( std::string& msg ){ msg = "something"; } int add( int x, int y) {
16
3145
by: hzmonte | last post by:
Correct me if I am wrong, declaring formal parameters of functions as const, if they should not be/is not changed, has 2 benefits; 1. It tells the program that calls this function that the parameter will not be changed - so don't worry. 2. It tells the implementor and the maintainer of this function that the parameter should not be changed...
6
11586
by: Jack White | last post by:
Does anyone know if an analogue to the "swap()" function found in C++ exists in C#. For those not familiar, let's say you have a function that loads some collection passed in by reference. If an error occurs while loading then the collection will be in an indeterminate state. The work-around in C++ is to load a temporary collection first and...
13
3944
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help is much appreciated. JD
32
5634
by: copx | last post by:
Why doesn't the C standard include generic function pointers? I use function pointers a lot and the lack of generic ones is not so cool. There is a common compiler extension (supported by GCC and lccwin32 for example) which I consider to be perfectly reasonable: you can cast every kind of function pointer to a void pointer and void...
0
7784
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...
0
7705
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...
0
8032
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. ...
0
8205
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8074
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...
0
3734
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...
1
2223
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
1
1310
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1044
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...

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.