problem with str()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • 7stud

    #1

    problem with str()

    I can't get the str() method to work in the following code(the last
    line produces an error):

    ============
    class test:
    """class test"""
    def __init__(self):
    """I am init func!"""
    self.num = 10
    self.num2 = 20
    def someFunc(self):
    """I am someFunc in test!"""
    print "hello"


    obj = test()
    obj.someFunc()
    names = dir(obj)
    print names

    methodList = [str for str in names if callable(getatt r(obj, str))]
    print methodList

    x = getattr(obj, methodList[0]).__doc__
    print x
    print type(x)
    print str(getattr(obj , methodList[0]).__doc__)
    ===========

    Here is the output:

    $ python test1.py
    hello
    ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
    ['__init__', 'someFunc']
    I am init func!
    <type 'str'>
    Traceback (most recent call last):
    File "test1.py", line 23, in ?
    print str(getattr(obj , methodList[0]).__doc__)
    TypeError: 'str' object is not callable

    This is part of some code in Diving Into Python,Chapter 4. In case a
    function doesn't have a __doc__ string, and therefore __doc__ returns
    None, the code needs to convert each __doc__ to a string so that the
    result is guaranteed to be a string.

  • Matimus

    #2
    Re: problem with str()

    Don't use built-ins as variable names. Your code will work if you
    change this:
    methodList = [str for str in names if callable(getatt r(obj, str))]
    to this:
    methodList = [s for s in names if callable(getatt r(obj, s))]

    Comment

    • Larry Bates

      #3
      Re: problem with str()

      7stud wrote:
      I can't get the str() method to work in the following code(the last
      line produces an error):
      >
      ============
      class test:
      """class test"""
      def __init__(self):
      """I am init func!"""
      self.num = 10
      self.num2 = 20
      def someFunc(self):
      """I am someFunc in test!"""
      print "hello"
      >
      >
      obj = test()
      obj.someFunc()
      names = dir(obj)
      print names
      >
      methodList = [str for str in names if callable(getatt r(obj, str))]
      print methodList
      >
      x = getattr(obj, methodList[0]).__doc__
      print x
      print type(x)
      print str(getattr(obj , methodList[0]).__doc__)
      ===========
      >
      Here is the output:
      >
      $ python test1.py
      hello
      ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
      ['__init__', 'someFunc']
      I am init func!
      <type 'str'>
      Traceback (most recent call last):
      File "test1.py", line 23, in ?
      print str(getattr(obj , methodList[0]).__doc__)
      TypeError: 'str' object is not callable
      >
      This is part of some code in Diving Into Python,Chapter 4. In case a
      function doesn't have a __doc__ string, and therefore __doc__ returns
      None, the code needs to convert each __doc__ to a string so that the
      result is guaranteed to be a string.
      >
      You masked the built-in str method in your list comprehension.

      Try changing to:

      methodList = [s for s in names if callable(getatt r(obj, str))]

      I'll bet it will work then.

      -Larry

      Comment

      • kyosohma@gmail.com

        #4
        Re: problem with str()

        On Mar 15, 2:49 pm, "7stud" <bbxx789_0...@y ahoo.comwrote:
        I can't get the str() method to work in the following code(the last
        line produces an error):
        >
        ============
        class test:
        """class test"""
        def __init__(self):
        """I am init func!"""
        self.num = 10
        self.num2 = 20
        def someFunc(self):
        """I am someFunc in test!"""
        print "hello"
        >
        obj = test()
        obj.someFunc()
        names = dir(obj)
        print names
        >
        methodList = [str for str in names if callable(getatt r(obj, str))]
        print methodList
        >
        x = getattr(obj, methodList[0]).__doc__
        print x
        print type(x)
        print str(getattr(obj , methodList[0]).__doc__)
        ===========
        >
        Here is the output:
        >
        $ python test1.py
        hello
        ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
        ['__init__', 'someFunc']
        I am init func!
        <type 'str'>
        Traceback (most recent call last):
        File "test1.py", line 23, in ?
        print str(getattr(obj , methodList[0]).__doc__)
        TypeError: 'str' object is not callable
        >
        This is part of some code in Diving Into Python,Chapter 4. In case a
        function doesn't have a __doc__ string, and therefore __doc__ returns
        None, the code needs to convert each __doc__ to a string so that the
        result is guaranteed to be a string.
        Your string comprehension over wrote the str built-in method, turning
        it into a variable. If you just type "str" (without the quotes) into
        the interpreter, it'll spit out 'someFunc'. Thus, you cannot use str
        as the iterator in your code:

        methodList = [str for str in names if callable(getatt r(obj, str))]

        instead, do something like this:

        methodList = [i for i in names if callable(getatt r(obj, i))]

        Have fun!

        Mike

        Comment

        • Terry Reedy

          #5
          Re: problem with str()


          "7stud" <bbxx789_05ss@y ahoo.comwrote in message
          news:1173988141 .493995.196780@ n76g2000hsh.goo glegroups.com.. .
          |I can't get the str() method to work in the following code(the last
          | line produces an error):

          If you 'print str' here

          | methodList = [str for str in names if callable(getatt r(obj, str))]

          and again here, you will see the problem; you have reassigned the name
          'str' to something else by using it in the list comp. Hence the advice to
          never reuse
          builtin names unless you mean to lose access to the builtin object.

          |print str(getattr(obj , methodList[0]).__doc__)

          Here I presume you want the builtin function. Too bad... ;-)

          Terry Jan Reedy



          Comment

          • 7stud

            #6
            Re: problem with str()

            Sheesh! You would think that after looking at every inch of the code
            for way too many hours, at some point that would have poked me in the
            eye.

            Thanks all.

            Comment

            • Steve Holden

              #7
              Re: problem with str()

              7stud wrote:
              Sheesh! You would think that after looking at every inch of the code
              for way too many hours, at some point that would have poked me in the
              eye.
              >
              Thanks all.
              >
              Get yourself a stuffed bear, and next time you have this kind of problem
              spend a few minutes explaining to the bear exactly how your program
              can't possibly be wrong. Works like a charm.

              regards
              Steve
              --
              Steve Holden +44 150 684 7255 +1 800 494 3119
              Holden Web LLC/Ltd http://www.holdenweb.com
              Skype: holdenweb http://del.icio.us/steve.holden
              Blog of Note: http://holdenweb.blogspot.com
              See you at PyCon? http://us.pycon.org/TX2007

              Comment

              • Gabriel Genellina

                #8
                Re: problem with str()

                En Thu, 15 Mar 2007 17:32:24 -0300, <kyosohma@gmail .comescribió:
                methodList = [str for str in names if callable(getatt r(obj, str))]
                >
                instead, do something like this:
                >
                methodList = [i for i in names if callable(getatt r(obj, i))]
                The fact that a list comprehension "leaks" its variables into the
                containing scope is a bit weird.
                A generator expression doesn't:

                pystr
                <type 'str'>
                pyw = (str for str in range(10))
                pyw
                <generator object at 0x00AD7C38>
                pystr
                <type 'str'>
                pyw.next()
                0
                pystr
                <type 'str'>

                --
                Gabriel Genellina

                Comment

                • Paul Rubin

                  #9
                  Re: problem with str()

                  kyosohma@gmail. com writes:
                  methodList = [str for str in names if callable(getatt r(obj, str))]
                  >
                  instead, do something like this:
                  >
                  methodList = [i for i in names if callable(getatt r(obj, i))]
                  or:

                  methodList = list(str for str in names if callable(getatt r(obj, str)))

                  genexps, unlike listcomps, make a new scope for their index variable.

                  Comment

                  • Alex Martelli

                    #10
                    Re: problem with str()

                    Steve Holden <steve@holdenwe b.comwrote:
                    7stud wrote:
                    Sheesh! You would think that after looking at every inch of the code
                    for way too many hours, at some point that would have poked me in the
                    eye.

                    Thanks all.
                    Get yourself a stuffed bear, and next time you have this kind of problem
                    spend a few minutes explaining to the bear exactly how your program
                    can't possibly be wrong. Works like a charm.
                    A rubber ducky works much better for that, btw -- more easily washable
                    than a stuffed bear, for example.


                    Alex

                    Comment

                    • Steve Holden

                      #11
                      Re: problem with str()

                      Alex Martelli wrote:
                      Steve Holden <steve@holdenwe b.comwrote:
                      >
                      >7stud wrote:
                      >>Sheesh! You would think that after looking at every inch of the code
                      >>for way too many hours, at some point that would have poked me in the
                      >>eye.
                      >>>
                      >>Thanks all.
                      >>>
                      >Get yourself a stuffed bear, and next time you have this kind of problem
                      >spend a few minutes explaining to the bear exactly how your program
                      >can't possibly be wrong. Works like a charm.
                      >
                      A rubber ducky works much better for that, btw -- more easily washable
                      than a stuffed bear, for example.
                      >
                      But stuffed bears are so much more knowledgeable about the minutiae of
                      software design.

                      regards
                      Steve
                      --
                      Steve Holden +44 150 684 7255 +1 800 494 3119
                      Holden Web LLC/Ltd http://www.holdenweb.com
                      Skype: holdenweb http://del.icio.us/steve.holden
                      Blog of Note: http://holdenweb.blogspot.com
                      See you at PyCon? http://us.pycon.org/TX2007

                      Comment

                      • 7stud

                        #12
                        Re: problem with str()

                        On Mar 15, 5:31 pm, "Gabriel Genellina" <gagsl-...@yahoo.com.a r>
                        wrote:
                        The fact that a list comprehension "leaks" its variables into the
                        containing scope is a bit weird.
                        A generator expression doesn't:
                        >
                        pystr
                        <type 'str'>
                        pyw = (str for str in range(10))
                        pyw
                        <generator object at 0x00AD7C38>
                        pystr
                        <type 'str'>
                        pyw.next()
                        0
                        pystr
                        <type 'str'>
                        On Mar 15, 5:34 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
                        or:
                        >
                        methodList = list(str for str in names if callable(getatt r(obj, str)))
                        >
                        genexps, unlike listcomps, make a new scope for their index variable.

                        Thanks.

                        Comment

                        • Alex Martelli

                          #13
                          Re: problem with str()

                          Steve Holden <steve@holdenwe b.comwrote:
                          ...
                          Get yourself a stuffed bear, and next time you have this kind of problem
                          spend a few minutes explaining to the bear exactly how your program
                          can't possibly be wrong. Works like a charm.
                          A rubber ducky works much better for that, btw -- more easily washable
                          than a stuffed bear, for example.
                          But stuffed bears are so much more knowledgeable about the minutiae of
                          software design.
                          And yet, the key to Python's strength is duck typing -- if you can teach
                          the duck to type, you've got it made.


                          Alex

                          Comment

                          • Steve Holden

                            #14
                            Re: problem with str()

                            Alex Martelli wrote:
                            Steve Holden <steve@holdenwe b.comwrote:
                            ...
                            >>>Get yourself a stuffed bear, and next time you have this kind of problem
                            >>>spend a few minutes explaining to the bear exactly how your program
                            >>>can't possibly be wrong. Works like a charm.
                            >>A rubber ducky works much better for that, btw -- more easily washable
                            >>than a stuffed bear, for example.
                            >>>
                            >But stuffed bears are so much more knowledgeable about the minutiae of
                            >software design.
                            >
                            And yet, the key to Python's strength is duck typing -- if you can teach
                            the duck to type, you've got it made.
                            >
                            >
                            That's bearly a joke at all :)

                            regards
                            Steve
                            --
                            Steve Holden +44 150 684 7255 +1 800 494 3119
                            Holden Web LLC/Ltd http://www.holdenweb.com
                            Skype: holdenweb http://del.icio.us/steve.holden
                            Blog of Note: http://holdenweb.blogspot.com
                            See you at PyCon? http://us.pycon.org/TX2007

                            Comment

                            Working...