[Q] Type checking...go further...

Thomas Wouters thomas at xs4all.nl
Mon Jul 19 10:12:26 EDT 1999


On Mon, Jul 19, 1999 at 03:35:35PM +0200, Olivier Deckmyn wrote:

> Thank you all for your answers !
> I finally use isinstance in the methods of my classes...

> But to go further, is there a way in python to have typed methods parameters ?
> aka :

> class MyClass:
>     def myMethod(string myString):
>         print myString

Nope, there isn't. Python is fully dynamically typed. That means you have to
expect everything anytime anywhere, but it also means you wont have to worry
about what you send to where when. If you want to be sure an argument is of
a specific type (say, a string) either make sure by hand all calls are
strings and add a typecheck in the call, or convert the argument to a
string.

Or, if you want a function to do something very different depending on what
was passed, use a dispatch table:

class Eggs:
	def __init__(self, value):
		self.value = value

class MyClass:
	def spam_string(self, egg):
		print egg

	def spam_eggs(self, egg):
		print egg.value

	def spam_other(self, egg):
		if isinstance(egg, Eggs):
			self.spam_eggs(egg)
		else:
			self.spam_string(egg)

	def spam_list(self, spamlist):
		for egg in spamlist:
			self.spam(egg)

	dispatch = { type(""): spam_string,
		     type([]): spam_list }

	def spam(self, egg):
		if self.dispatch.has_key(type(egg)):
			self.dispatch[type(egg)](self, egg)
		else:
			self.spam_other(egg)

(this is a very simple example. Most of this can be done with a simple
wrapper classes with __repr__ or __str__ functions. But it's just for
basics, anyway.)

>>> a=MyClass()
>>> b=Eggs("sausages")
>>> c="Ham"
>>> a.spam(b)     
sausages
>>> a.spam(c)
Ham
>>> a.spam([["spam"]*5, b, b, c*10, [c]*10])
spam
spam
spam
spam
spam
sausages
sausages
HamHamHamHamHamHamHamHamHamHam
Ham
Ham
Ham
Ham
Ham
Ham
Ham
Ham
Ham
Ham

damned-if-i-know-why-i-dont-work-with-python-dai'ly yours,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list