adding attributes to a function, from within the function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fernando Rodriguez

    adding attributes to a function, from within the function

    Hi,

    What's the syntax to add an attribute to a function form the function body?

    For example, instead of doing:
    def fn():
    return 1
    fn.error = "Error message"
    print fn.error


    I'd like to do something like this:

    def fn():
    error = "Error message"
    return 1

    print fn.error

    How can I do this? O:-)

    TIA
  • Sean Cody

    #2
    Re: adding attributes to a function, from within the function

    > What's the syntax to add an attribute to a function form the function
    body?[color=blue]
    >[/color]
    I don't think this is entirely possible as there is no way obvious way to
    introspect the members of a function based on the language (as I know it).

    Functions can be invoked many times so you would not know which version of
    the member variable you will get (assuming the python interpeter copies the
    text segment of the function instead of branching to it [which is probably
    the case and if so the text segment doesn't normally have 'user memory'
    allocated within it as local variables may be on the stack [unless in python
    even local statics are heap based]]). Once a function has finished its
    memory is free'd unless it is some sort of static function.

    What you could do is:

    class fn:
    __init__():
    self.error = -1
    function_stuff( )

    Then you could do it but it is more effort that it is worth...

    From an OO or even modular standpoint you shouldn't break scope unless there
    is a really good reason to.

    --
    Sean
    P.S. I'm probably totally wrong but if I didn't at least try I wouldn't
    learn anything. :P
    P.P.S. I've used way too many buzz words.... maybe I shouldn't post to
    groups shortly after management meetings. :)


    Comment

    • Werner Schiendl

      #3
      Re: adding attributes to a function, from within the function

      Hi,

      Fernando Rodriguez wrote:
      [color=blue]
      >
      > I'd like to do something like this:
      >
      > def fn():
      > error = "Error message"
      > return 1
      >
      > print fn.error
      >[/color]

      AFAIK, not at all.

      The reason is, that in Python the function definition is an executable
      statement and therefore the function does not exist until after it's
      end.

      So you can either stay with your first approach, which should be fine
      as long as you always assign a static string.

      However, your code makes me believe you want to provide error details to
      a caller in case something goes awry. The proper way to handle errors in
      Python, however, is to use exceptions - not return values.

      for example:
      [color=blue][color=green][color=darkred]
      >>> class MyException(Exc eption):[/color][/color][/color]
      .... def __init__(self, details):
      .... self.details = details
      ....[color=blue][color=green][color=darkred]
      >>> def f(x):[/color][/color][/color]
      .... if x < 0:
      .... raise MyException("x must not be negative")
      .... # do normal processing
      ....[color=blue][color=green][color=darkred]
      >>> try:[/color][/color][/color]
      .... f(-1)
      .... except MyException, e:
      .... print "Something went awry:", e.details
      ....
      Something went awry: x must not be negative


      hth

      Werner


      Comment

      • Alex Martelli

        #4
        Re: adding attributes to a function, from within the function

        Fernando Rodriguez wrote:
        [color=blue]
        > Hi,
        >
        > What's the syntax to add an attribute to a function form the function
        > body?
        >
        > For example, instead of doing:
        > def fn():
        > return 1
        > fn.error = "Error message"
        > print fn.error
        >
        >
        > I'd like to do something like this:
        >
        > def fn():
        > error = "Error message"[/color]

        nope, that would be a local variable of the function
        [color=blue]
        > return 1
        >
        > print fn.error
        >
        > How can I do this? O:-)[/color]

        by assigning to fn.error within the function body you can
        approximate this, BUT, the function body will of course not
        be executed until the function is CALLED, so, given that in
        your "like to do" you're not calling it, there is NO way it
        can ever get your desiderata (access something that WOULD
        be set if you called the function, WITHOUT calling it).


        Alex

        Comment

        • Shu-Hsien Sheu

          #5
          Re: adding attributes to a function, from within the function

          Hi,

          I think you would need to use a class rather than function.
          [color=blue][color=green][color=darkred]
          >>> class fn(object):[/color][/color][/color]
          def __init__(self):
          self.error = 'Error message'

          [color=blue][color=green][color=darkred]
          >>> kk = fn()
          >>> kk.error[/color][/color][/color]
          'Error message'

          -shuhsien
          [color=blue]
          >Hi,
          >
          >What's the syntax to add an attribute to a function form the function body?
          >
          >For example, instead of doing:
          >def fn():
          > return 1
          >fn.error = "Error message"
          >print fn.error
          >
          >
          >I'd like to do something like this:
          >
          >def fn():
          > error = "Error message"
          > return 1
          >
          >print fn.error
          >
          >How can I do this? O:-)
          >
          >TIA
          >
          >[/color]



          Comment

          • Hung Jung Lu

            #6
            Re: adding attributes to a function, from within the function

            Shu-Hsien Sheu <sheu@bu.edu> wrote in message news:<mailman.2 90.1067620017.7 02.python-list@python.org >...[color=blue]
            > I think you would need to use a class rather than function.
            >[color=green][color=darkred]
            > >>> class fn(object):[/color][/color]
            > def __init__(self):
            > self.error = 'Error message'
            >
            >[color=green][color=darkred]
            > >>> kk = fn()
            > >>> kk.error[/color][/color]
            > 'Error message'[/color]

            Yes, in Python it's more natural to use a class object for storing
            attributes. What the original poster wanted was some sort of
            "closure-like" function, that is, a function object that can carry
            some data member as well. Also, in C++, you have static variables
            inside functions. In Python, if you use a function object, you can't
            insert attributes during the definition of the function.

            In Python, an class instance can be made callable by implementing the
            __call__() method. If the function is supposed to be singleton, then
            you can use:

            class fn(object):
            error = 'Error message'
            def __call__(self, x=None):
            if x is None:
            return 1
            else:
            return 2*x
            fn = fn() # gets rid of the class, this makes fn singleton
            print fn() # prints 1
            print fn(3) # prints 3
            print fn.error # prints 'Error message'

            regards,

            Hung Jung

            Comment

            • Michele Simionato

              #7
              Re: adding attributes to a function, from within the function

              Fernando Rodriguez <frr@easyjob.ne t> wrote in message news:<as15qvs0n na5mvio4agd5su9 9fmrcgui4e@4ax. com>...[color=blue]
              > Hi,
              > I'd like to do something like this:
              >
              > def fn():
              > error = "Error message"
              > return 1
              >
              > print fn.error[/color]

              You can always use a closure:

              def function_with_e rror_message(er ror):
              def _(): return 1
              _.error=error
              return _

              fn=function_wit h_error_message ("Error message")
              print fn.error

              However, IMHO using a class is better since automatic
              documentation tools and inspection features work better for classes
              than for closures.

              Michele

              Comment

              Working...