Callable assertion?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Terry Reedy

    #16
    Re: Callable assertion?


    "Roy Smith" <roy@panix.co m> wrote in message
    news:roy-408A7D.18354005 102003@reader2. panix.com...[color=blue]
    > There's a big difference between verifying that a passed parameter[/color]
    has[color=blue]
    > the properties it's supposed to have and trying to figure out if you[/color]
    can[color=blue]
    > read a file or open a socket.[/color]

    Readability and connectability are also possible properties of passed
    parameters. For your purpose of init-time checking, the relevant
    property of properties is whether the property can be satifactorily
    checked at init time or not.
    [color=blue]
    > The former catches a programming error. If I meant to pass fred and[/color]
    I[color=blue]
    > pass fred() by mistake, the problem is going to be there every time[/color]
    I[color=blue]
    > run the program until I fix the code.[/color]

    And if you pass the name of an access prohibited file, that error will
    also continue until fixed.

    Alex Martelli has written several pages on 'look before you leap' (his
    phrase) versus 'try and respond to failure' (not his). Look them up
    for more discussion of this topic.

    Terry J. Reedy


    Comment

    • Peter Hansen

      #17
      Re: Callable assertion?

      Terry Reedy wrote:[color=blue]
      >
      > Alex Martelli has written several pages on 'look before you leap' (his
      > phrase) ...[/color]

      That just put an image in my mind, of someone carefully inspecting
      a chasm over which he intends to jump, measuring distance, making
      sure that it's within his abilities.

      He then backs up ten carefully measured paces, digs in his feet,
      and surges forward, sprinting at top speed.

      He flies towards the gap, his paces perfectly timed.

      At the last moment, just as he launches himself into the air, the
      ground under his foot crumbles away and he tumbles helplessly into
      the void.

      It might sound like a good idea, and even perhaps be a good idea,
      to check things out ahead of time, but it's essential to understand
      that, no matter what, you could overlook something or conditions
      could change at the last instant just as you "do it for real".

      Whether you use an assertion in __init__, or any other kind of
      "look before you leap", just make sure to remember that you might
      have overlooked some obscure way in which things could fail anyway.

      Always handle exceptions. There's no robust alternative.

      -Peter

      Comment

      • Gerrit Holl

        #18
        Re: Callable assertion?

        Gonçalo Rodrigues wrote:[color=blue]
        > On Sun, 05 Oct 2003 10:20:11 -0400, Roy Smith <roy@panix.co m> wrote:[color=green]
        > > "A.M. Kuchling" <amk@amk.ca> wrote:[color=darkred]
        > >> There's a callable(param) built-in function, dating back to Python 1..2.[/color][/color][/color]
        [color=blue][color=green]
        > >What does "appears callable" mean? Under what circumstances would
        > >callable(foo ) return True, yet foo() would fail?[/color]
        >
        > An extreme and artificial example:
        > [color=green][color=darkred]
        > >>> class FakeCallable(ob ject):[/color][/color]
        > ... def __call__(self, *args, **kwargs):
        > ... raise TypeError("My only purpose in life is to trick
        > the Python interpreter.")
        > ... [color=green][color=darkred]
        > >>> a = FakeCallable()
        > >>> callable(a)[/color][/color]
        > True[color=green][color=darkred]
        > >>> a()[/color][/color]
        > Traceback (most recent call last):
        > File "<interacti ve input>", line 1, in ?
        > File "<interacti ve input>", line 3, in __call__
        > TypeError: My only purpose in life is to trick the Python interpreter.[/color]

        Is there a difference between callable(a) and hasattr(a, '__call__')?

        Gerrit.

        --
        121. If any one store corn in another man's house he shall pay him
        storage at the rate of one gur for every five ka of corn per year.
        -- 1780 BC, Hammurabi, Code of Law
        --
        Asperger Syndroom - een persoonlijke benadering:

        Kom in verzet tegen dit kabinet:
        De website van de Socialistische Partij (SP) in Nederland: Informatie, nieuws, agenda en publicaties.


        Comment

        • Duncan Booth

          #19
          Re: Callable assertion?

          Gerrit Holl <gerrit@nl.linu x.org> wrote in
          news:mailman.10 65434008.19681. python-list@python.org :
          [color=blue]
          > Is there a difference between callable(a) and hasattr(a, '__call__')?
          >[/color]
          [color=blue][color=green][color=darkred]
          >>> class C: pass[/color][/color][/color]
          [color=blue][color=green][color=darkred]
          >>> callable(C), hasattr(C, '__call__')[/color][/color][/color]
          (True, False)

          A few other strange objects in the system show the same behaviour
          (socket.socket for one), but new style classes and most builtin objects are
          well behaved (i.e. they have the __call__ attribute if they are callable).

          --
          Duncan Booth duncan@rcp.co.u k
          int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
          "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

          Comment

          • Gonçalo Rodrigues

            #20
            Re: Callable assertion?

            On Mon, 6 Oct 2003 11:52:12 +0200, Gerrit Holl <gerrit@nl.linu x.org>
            wrote:
            [color=blue]
            >Gonçalo Rodrigues wrote:[color=green]
            >> On Sun, 05 Oct 2003 10:20:11 -0400, Roy Smith <roy@panix.co m> wrote:[color=darkred]
            >> > "A.M. Kuchling" <amk@amk.ca> wrote:
            >> >> There's a callable(param) built-in function, dating back to Python 1.2.[/color][/color]
            >[color=green][color=darkred]
            >> >What does "appears callable" mean? Under what circumstances would
            >> >callable(foo ) return True, yet foo() would fail?[/color]
            >>
            >> An extreme and artificial example:
            >>[color=darkred]
            >> >>> class FakeCallable(ob ject):[/color]
            >> ... def __call__(self, *args, **kwargs):
            >> ... raise TypeError("My only purpose in life is to trick
            >> the Python interpreter.")
            >> ...[color=darkred]
            >> >>> a = FakeCallable()
            >> >>> callable(a)[/color]
            >> True[color=darkred]
            >> >>> a()[/color]
            >> Traceback (most recent call last):
            >> File "<interacti ve input>", line 1, in ?
            >> File "<interacti ve input>", line 3, in __call__
            >> TypeError: My only purpose in life is to trick the Python interpreter.[/color]
            >
            >Is there a difference between callable(a) and hasattr(a, '__call__')?
            >[/color]

            Definitely yes. There are a few strange objects that are callable and
            do not have a __call__. And you can make up your own:
            [color=blue][color=green][color=darkred]
            >>> class Wrapper(object) :[/color][/color][/color]
            .... def __init__(self, obj):
            .... super(Wrapper, self).__init__( obj)
            .... self.__obj = obj
            .... def __getattr__(sel f, attrib):
            .... return getattr(self.__ obj, attrib)
            ....[color=blue][color=green][color=darkred]
            >>> a = Wrapper(lambda *args, **kwargs: None)
            >>> a[/color][/color][/color]
            <__main__.Wrapp er object at 0x010D4D50>[color=blue][color=green][color=darkred]
            >>> hasattr(a, "__call__")[/color][/color][/color]
            True[color=blue][color=green][color=darkred]
            >>> a()[/color][/color][/color]
            Traceback (most recent call last):
            File "<interacti ve input>", line 1, in ?
            TypeError: 'Wrapper' object is not callable[color=blue][color=green][color=darkred]
            >>>[/color][/color][/color]

            The gist is that the lookup for special methods does not use the usual
            getattr machinery but just crawls the class's mro in search of it.

            With my best regards,
            G. Rodrigues

            Comment

            • Greg Ewing (using news.cis.dfn.de)

              #21
              Re: Callable assertion?

              Erik Max Francis wrote:[color=blue]
              > "Gonçalo Rodrigues" wrote:
              >[color=green]
              >>Definitely yes. There are a few strange objects that are callable and
              >>do not have a __call__.[/color]
              >
              > I wouldn't call class objects all that strange :-).[/color]

              It is strange behaviour, though, considering
              [color=blue][color=green][color=darkred]
              >>> class C:[/color][/color][/color]
              .... pass
              ....[color=blue][color=green][color=darkred]
              >>> type(C).__dict_ _.keys()[/color][/color][/color]
              ['__delattr__', '__setattr__', '__repr__', '__call__', '__str__',
              '__getattribute __', '__new__']

              so according to C's type, it *should* have a __call__ method.
              I'm not sure exactly what's going on here.

              --
              Greg Ewing, Computer Science Dept,
              University of Canterbury,
              Christchurch, New Zealand


              Comment

              • Alex Martelli

                #22
                Re: Callable assertion?

                Greg Ewing (using news.cis.dfn.de ) wrote:
                [color=blue]
                > Erik Max Francis wrote:[color=green]
                >> "Gonçalo Rodrigues" wrote:
                >>[color=darkred]
                >>>Definitely yes. There are a few strange objects that are callable and
                >>>do not have a __call__.[/color]
                >>
                >> I wouldn't call class objects all that strange :-).[/color][/color]

                _CLASSIC_ classes are very strange indeed, for backwards compat.

                [color=blue]
                > It is strange behaviour, though, considering
                >[color=green][color=darkred]
                > >>> class C:[/color][/color]
                > ... pass
                > ...[color=green][color=darkred]
                > >>> type(C).__dict_ _.keys()[/color][/color]
                > ['__delattr__', '__setattr__', '__repr__', '__call__', '__str__',
                > '__getattribute __', '__new__']
                >
                > so according to C's type, it *should* have a __call__ method.
                > I'm not sure exactly what's going on here.[/color]

                BW compat -- type(C) (i.e <type 'classobj'>) is the weirdest
                little beast in Pythonland.

                Use newstyle classes only and keep your sanity...:
                [color=blue][color=green][color=darkred]
                >>> class C(object): pass[/color][/color][/color]
                ....[color=blue][color=green][color=darkred]
                >>>
                >>> C.__call__[/color][/color][/color]
                <method-wrapper object at 0x402ded8c>[color=blue][color=green][color=darkred]
                >>>[/color][/color][/color]


                Alex

                Comment

                Working...