@func call syntax

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • teekaysoh@gmail.com

    #1

    @func call syntax

    Hi,

    I am new to Python, here I'd like to have a question: I noticed a
    special way to call a function in a program:

    @function_name

    No argv is passed, even though the function_name asks for one. Any idea
    what this @something syntax is trying to achieve. I haven't been able
    to find any answer of on the google web and groups.

    TIA.

  • casevh@comcast.net

    #2
    Re: @func call syntax


    teekaysoh@gmail .com wrote:[color=blue]
    > Hi,
    >
    > I am new to Python, here I'd like to have a question: I noticed a
    > special way to call a function in a program:
    >
    > @function_name
    >
    > No argv is passed, even though the function_name asks for one. Any idea
    > what this @something syntax is trying to achieve. I haven't been able
    > to find any answer of on the google web and groups.
    >
    > TIA.[/color]

    @function_name is called a decorator.

    The current method for transforming functions and methods (for instance, declaring them as a class or static method) is awkward and can lead to code that is difficult to understand. Ideally, these transformations should be made at the same point in the...




    casevh

    Comment

    • Schüle Daniel

      #3
      Re: @func call syntax

      this is decorator, this is how it's may be implented
      [color=blue][color=green][color=darkred]
      >>> def returns(t):[/color][/color][/color]
      .... def dec(f):
      .... def wrapped(*args, **kwargs):
      .... ret = f(*args, **kwargs)
      .... assert type(ret) is t
      .... return ret
      .... return wrapped
      .... return dec
      ....[color=blue][color=green][color=darkred]
      >>>
      >>> @returns(int)[/color][/color][/color]
      .... def f1():
      .... return 1
      ....[color=blue][color=green][color=darkred]
      >>> @returns(float)[/color][/color][/color]
      .... def f2():
      .... return 2.0
      ....[color=blue][color=green][color=darkred]
      >>> @returns(str)[/color][/color][/color]
      .... def f3():
      .... return 1
      ....[color=blue][color=green][color=darkred]
      >>> f1()[/color][/color][/color]
      1[color=blue][color=green][color=darkred]
      >>> f2()[/color][/color][/color]
      2.0[color=blue][color=green][color=darkred]
      >>> f3()[/color][/color][/color]
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 5, in wrapped
      AssertionError[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]


      I can imagine that stuff like this may be extremely usefull
      when testing you program
      later one could parse and remove all such assertations
      easy and cut them all at once

      Regards, Daniel

      Comment

      Working...