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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T12:52:49+00:00 2026-06-14T12:52:49+00:00

Suppose I have defined: def to_class(cls): returns a decorator aimed to force the result

  • 0

Suppose I have defined:

def to_class(cls):
  """ returns a decorator
  aimed to force the result to be of class cls. """
  def decorating_func(func):
    def wrapper(*args, **kwargs):
      return cls(func(*args, **kwargs))
    return wrapper
  return decorator(decorating_func)

I wish to use it to create decorators which turn function results to objects of a given class. However, this will not work:

class TestClass(object):
  def __init__(self, value):
    self._value = (value, value)

  def __str__(self):
    return str(self._value)

  @staticmethod
  @to_test_class
  def test_func(value):
    return value

to_test_class = to_class(TestClass)

as test_func will look for to_test_class and will not find it. On the other hand, putting the assignment to to_test_class before the class definition will fail as well, as TestClass will not be defined yet.

Trying to put @to_class(TestClass) above the definition of test_func will also fail, as the method is constructed before the class (if I am not wrong).

The only workaround I have found is to define to_test_class manually as a decorator, and not as one returned from the general “to_class” def.

It might be important to mention that this is only a basic example, but I wish to use to_class for many applications, such as modifying the returned value before ‘plugging’ it into the class’ constructor; and I wish to use it as a decorator for other class’ methods as well.

I am sure some think a “to_class” decorator is pointless; manipulations can be done within the decorated method, instead. Though, I find it convenient, and it helps me with readability.

Finally I wish to add that this interests me 20% for practical reasons and 80% for studying reasons, as I find this is something I do not fully understand about decorators in Python in general.

  • 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-06-14T12:52:50+00:00Added an answer on June 14, 2026 at 12:52 pm

    Indeed, at class construction time, the class object itself has not yet been constructed, thus you cannot use it as the basis of a decorator.

    One work-around I can think of, is to not use the staticmethod decorator. Instead, internally in your own decorator, re-use the classmethod decorator. That way you ensure that Python at the very least passes in the associated class for you:

    def to_class(func):
        """ returns a decorator
        aimed to force the result to be of class cls. """
        def wrapper(cls, *args, **kwargs):
            return cls(func(*args, **kwargs))
        return classmethod(wrapper)
    

    Then use it like this:

    class TestClass(object):
        def __init__(self, value):
            self._value = (value, value)
    
        def __str__(self):
            return str(self._value)
    
        @to_class
        def test_func(value):
            return value
    

    Demonstration:

    >>> def to_class(func):
    ...     """ returns a decorator
    ...     aimed to force the result to be of class cls. """
    ...     def wrapper(cls, *args, **kwargs):
    ...         return cls(func(*args, **kwargs))
    ...     return classmethod(wrapper)
    ... 
    >>> class TestClass(object):
    ...     def __init__(self, value):
    ...         self._value = (value, value)
    ...     def __str__(self):
    ...         return str(self._value)
    ...     @to_class
    ...     def test_func(value):
    ...         return value
    ... 
    >>> TestClass.test_func('foo')
    <__main__.TestClass object at 0x102a77210>
    >>> print TestClass.test_func('foo')
    ('foo', 'foo')
    

    A generic version of your decorator is not easy; the only other workaround to your conundrum is to use a metaclass hack; see another answer of mine where I describe the method in more detail.

    You basically need to reach into the class-under-construction namespace, set a temporary metaclass, and then rely on there being at least one instance of the class before your decorator will work; the temporary metaclass approach hooks into the class creation mechanisms to retrieve the constructed class at a later time.

    Seeing as you are using this decorator as an alternative class factory however, that is probably not going to be ideal; if someone used your decorated functions to create class instances exclusively the metaclass would be called too late.

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

Sidebar

Related Questions

Suppose we have following code defined in tester.py class Tester( object ): def method(
Suppose I have a function defined like this: class Foo() { public: void bar(MyClass*
Suppose I have an entity object defined as public partial class Article { public
Suppose I have the following defined in a header file: namespace MyNamespace { Class
Suppose I have, class example(object) def __init__(var1 = 10, var2 = 15, var3 =
Suppose I have defined a function: def hello(name:String, words:String) = println(Hello! + name +
Suppose I have a user defined type: CREATE OR REPLACE TYPE TEST_TYPE AS OBJECT
Suppose I have the following: A region defined by minimum and maximum latitude and
Suppose I have a war and jar projects defined in maven. The Jar project
Suppose I have got a model ArticleVersion in my project which is defined as:

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.