Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6862123
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T02:37:22+00:00 2026-05-27T02:37:22+00:00

I wanted to demonstrate the usefulness of decorators in python to some people and

  • 0

I wanted to demonstrate the usefulness of decorators in python to some people and failed at a simple example: Consider two functions (for sake of simplicity without arguments) f and g.
One can define their sum f+g as the function that returns f() + g(). Of course adding, subtracting etc. of functions is not defined in general. But it is easy to write a decorator that transforms every function into an addable function.

Now I would like to have a decorator that transforms any function into an “operable” function, that is, a function that behaves in the described way for any operator in the standard module operator. My implementation looks as follows:

import operator

class function(object):
    def __init__(self, f):
        self.f = f
    def __call__(self):
        return self.f()

def op_to_function_op(op):
    def function_op(self, operand):
        def f():
            return op(self(), operand())
        return function(f)
    return function_op
binary_op_names = ['__add__', '__and__', '__div__', '__eq__', '__floordiv__', '__ge__', '__gt__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__or__', '__pow__', '__sub__', '__truediv__', '__xor__']
for name in binary_op_names:
    type.__setattr__(function, name, op_to_function_op(getattr(operator, name)))

Let’s perform a little test to see if it works:

@function
def a():
    return 4

def b():
    return 7

c = a + b
print c()
print c() == operator.__add__(4, 7)

Output:

11
True

This is the final version I got after some experimenting.
Now let’s do two small, irrelevant modifications to have a look what I tried before:

First: In the definition of binary_op_names, change the square brackets to round brackets. Suddenly, a (for me) completely unrelated error message comes out:

Traceback (most recent call last):
  File "example.py", line 30, in <module>
    c = a + b
TypeError: unsupported operand type(s) for +: 'function' and 'function'

Where does this come from??

Second: Write op_to_function_op as a lambda expression:

op = getattr(operator, name)
type.__setattr__(function, name, lambda self, other: function(lambda: op(self(), other())))

Perform a slightly more involved test case:

@function
def a():
    return 4

def b():
    return 7

c = a + b
print c()
print c() == operator.__add__(4, 7)
print c() == operator.__xor__(4, 7)

Output:

3
False
True

This looks to me like scope leakage, but again I don’t understand why this happens.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T02:37:22+00:00Added an answer on May 27, 2026 at 2:37 am

    For the first issue, I didn’t see any problems when changing binary_op_names from a list to a tuple, not sure why you were seeing that.

    As for the second issue, all operations will perform an XOR because __xor__ was the last item that op was set to. Because op is not passed into the lambda when it is created, each time the lambda is called it will look for op in a global scope and always see __xor__.

    You can prevent this by creating a lambda that acts as a closure, similar to your current op_tofunction_op, it might end up looking something like this:

    op_to_function_op = lambda f: lambda self, other: function(lambda: f(self(), other()))
    for name in binary_op_names:
        op = getattr(operator, name)
        type.__setattr__(function, name, op_to_function_op(op))
    
    >>> (function(lambda: 4) + (lambda: 7))()
    11
    >>> (function(lambda: 4) - (lambda: 7))()
    -3
    >>> (function(lambda: 4) ^ (lambda: 7))()
    3
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using pyDes to encrypt some data. I wanted to demonstrate that if you
I just wanted to demonstrate why we should not be using JSTL tags to
Wanted some help with a problem with mapkit I am facing. Should be a
Wanted to get some consensus around a UI feature I'm working on right now.
Wanted a simple but efficient method to get value from Nullable when T is
Suppose I want to override some class which is already defined somewhere, for example,
Reading this question , I wanted to test if I could demonstrate the non-atomicity
The canonical function to demonstrate recursion is the factorial() function. I tried a simple
wanted to see if somebody can provide some suggestions/pointers on how to address this
Wanted to know if there was a way one could query shelveset details from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.