Python supports LSP, does it?

bruno modulix onurb at xiludom.gro
Wed Aug 10 12:06:28 EDT 2005


Roy Smith wrote:
> Andy Leszczynski <leszczynscyATnospam.yahoo.com.nospam> writes:
> 
(snip)

>>It's not a true statement. Nothing in the language enforces LSP. In
>>fact, there's not even a [way?] when a function/method is invoked to make
>>sure the type passed in is a subtype of the type you expect
> 
> 
> Well, that's not entirely true. I could write:
> 
> def func (self, obj):
>    assert (isinstance (obj, baseClass))
> 
> It's sort of un-pythonic, but the language certainly lets you do it if you 
> really want to.

It doesn't inforce LSP anyway.

class baseClass(object):
  def f(self):
     print "in %s f" % self
     return 42

class derivedClass(baseClass):
  f = "gotcha"

class somethingElse(object)
  def f(self):
    return 42

def func1(obj):
  assert isinstance (obj, baseClass)
  obj.f()

def func2(obj):
  assert(callable(getAttr(obj, f))
  obj.f()

b = baseClass()
d = derivedClass()
s = somethingElse()

func1(b) # ok
func1(d) # TypeError
func1(s) # AssertionError

func2(b) # ok
func2(d) # AssertionError
func2(s) # ok

Clearly, somethingElse is a subtype of baseClass, when derivedClass is
not. Don't confuse suclassing with subtyping. issinstance() let you
check for subclassing, not for subtyping. The only language-level
mechanism I know of that more or less inforce LSP is Eiffel's contracts.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list