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 4027188
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T11:03:56+00:00 2026-05-20T11:03:56+00:00

I have a problem in Python, for which I cannot find any clean solution

  • 0

I have a problem in Python, for which I cannot find any clean solution …

When calling some methods, I want to execute some code before the method execution and after. In order (among many other things) to automatically set and clean a context variable.

In order to achieve this, I have declared the following metaclass :

class MyType(type):
    def __new__(cls, name, bases, attrs):
        #wraps the 'test' method to automate context management and other stuff
        attrs['test'] = cls.other_wrapper(attrs['test'])
        attrs['test'] = cls.context_wrapper(attrs['test'])
        return super(MyType, cls).__new__(cls, name, bases, attrs)

    @classmethod
    def context_wrapper(cls, operation):
        def _manage_context(self, *args, **kwargs):
            #Sets the context to 'blabla' before the execution
            self.context = 'blabla'
            returned = operation(self, *args, **kwargs)
            #Cleans the context after execution
            self.context = None
            return returned
        return _manage_context

    @classmethod
    def other_wrapper(cls, operation):
        def _wrapped(self, *args, **kwargs):
            #DO something with self and *args and **kwargs
            return operation(self, *args, **kwargs)
        return _wrapped

This works like a charm :

class Parent(object):

    __metaclass__ = MyType

    def test(self):
        #Here the context is set:
        print self.context #prints blabla

But as soon as I want to subclass Parent, problems appear, when I call the parent method with super :

class Child(Parent):
    def test(self):
        #Here the context is set too
        print self.context #prints blabla
        super(Child, self).test()
        #But now the context is unset, because Parent.test is also wrapped by _manage_context
        #so this prints 'None', which is not what was expected
        print self.context

I have thought of saving the context before setting it to a new value, but that only solves partially the problem…

Indeed, (hang on, this is hard to explain), the parent method is called, the wrappers are executed, but they receive *args and **kwargs addressed to Parent.test, while self is a Child instance, so self attributes have irrelevant values if I want to challenge them with *args and **kwargs (for example for automated validation purpose), example :

@classmethod
def validation_wrapper(cls, operation):
    def _wrapped(self, *args, **kwargs):
        #Validate the value of a kwarg
        #But if this is executed because we called super(Child, self).test(...
        #`self.some_minimum` will be `Child.some_minimum`, which is irrelevant
        #considering that we called `Parent.test`
        if not kwarg['some_arg'] > self.some_minimum:
            raise ValueError('Validation failed')
        return operation(self, *args, **kwargs)
    return _wrapped

So basically, to solve this problem I see two solutions :

  1. preventing the wrappers to be executed when the method was called with super(Child, self)

  2. having a self that is always of the “right” type

Both solutions seem impossible to me … Do somebody has an idea on how to solve this ? A suggestion ?

  • 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-20T11:03:57+00:00Added an answer on May 20, 2026 at 11:03 am

    Actually I have found out a way to prevent the wrappers to be executed when the method was called with super(Child, self) :

    class MyType(type):
        def __new__(cls, name, bases, attrs):
            #wraps the 'test' method to automate context management and other stuff
            new_class = super(MyType, cls).__new__(cls, name, bases, attrs)
            new_class.test = cls.other_wrapper(new_class.test, new_class)
    
        @classmethod
        def other_wrapper(cls, operation, new_class):
            def _wrapped(self, *args, **kwargs):
                #DO something with self and *args and **kwargs ...
                #ONLY if self is of type *new_class* !!!
                if type(self) == new_class:
                    pass #do things
                return operation(self, *args, **kwargs)
            return _wrapped
    

    That way, when calling :

    super(Child, self).a_wrapped_method
    

    The wrapping code is by-passed !!! That’s quite hackish, but it works …

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a little Java problem I want to translate to Python. Therefor I
I have 2 Python scripts which are main_menu.py and inputip.py. The problem occurs when
I am completely new to python and I have a serious problem which I
I have some problem, that look like some spaces in my understanding how python
I have problem in some JavaScript that I am writing where the Switch statement
I have problem with return statment >.< I want to store all magazine names
I have problem compilin this code..can anyone tell whats wrong with the syntax CREATE
I have problem when I try insert some data to Informix TEXT column via
I have a problem with a little .Net web application which uses the Amazon
Hallo! I want a blob object which I can pass around in python and

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.