EzDevInfo.com

decorator

Decorator HTML, CSS, and JavaScript Front-End Framework Decorator Front End Documentation front end framework

python decorators with parameters

I have a problem with the transfer of variable 'insurance_mode' by the decorator. I would do it by the following decorator statement:

 @execute_complete_reservation(True)
 def test_booking_gta_object(self):
     self.test_select_gta_object()

but unfortunately, this statement does not work. Perhaps maybe there is better way to solve this problem.

def execute_complete_reservation(test_case,insurance_mode):
    def inner_function(self,*args,**kwargs):
        self.test_create_qsf_query()
        test_case(self,*args,**kwargs)
        self.test_select_room_option()
        if insurance_mode:
            self.test_accept_insurance_crosseling()
        else:
            self.test_decline_insurance_crosseling()
        self.test_configure_pax_details()
        self.test_configure_payer_details

    return inner_function

Source: (StackOverflow)

Is there a decorator to simply cache function return values?

Consider the following:

@property
def name(self):

    if not hasattr(self, '_name'):

    	# expensive calculation
    	self._name = 1 + 1

    return self._name

I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)

PS the real calculation doesn't depend on mutable values


Source: (StackOverflow)

Advertisements

What does functools.wraps do?

In a comment on the answer to another question, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?


Source: (StackOverflow)

Creating a singleton in python

This question is not for the discussion of whether or not the Singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in python in such a way that is most pythonic. In this instance I define 'most pythonic' to mean that it follows the 'principle of least astonishment'

I have multiple classes which would become singletons (my use-case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate.

Best methods:


Method 1: A decorator

def singleton(class_):
  instances = {}
  def getinstance(*args, **kwargs):
    if class_ not in instances:
        instances[class_] = class_(*args, **kwargs)
    return instances[class_]
  return getinstance

@singleton
class MyClass(BaseClass):
  pass

Pros

  • Decorators are additive in a way that is often more intuitive than multiple inheritance.

Cons

  • While objects created using MyClass() would be true singleton objects, MyClass itself is a a function, not a class, so you cannot call class methods from it. Also for m = MyClass(); n = MyClass(); o = type(n)(); then m == n && m != o && n != o

Method 2: A base class

class Singleton(object):
  _instance = None
  def __new__(class_, *args, **kwargs):
    if not isinstance(class_._instance, class_):
        class_._instance = object.__new__(class_, *args, **kwargs)
    return class_._instance

class MyClass(Singleton, BaseClass):
  pass

Pros

  • It's a true class

Cons

  • Multiple inheritance - eugh! __new__ could be overwritten during inheritance from a second base class? Have to think more than is necessary.

Method 3: A metaclass

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

#Python2
class MyClass(BaseClass):
    __metaclass__ = Singleton

#Python3
class MyClass(BaseClass, metaclass=Singleton):
    pass

Pros

  • It's a true class
  • Auto-magically covers inheritance
  • Uses __metaclass__ for its proper purpose (And made me aware of it)

Cons

  • Are there any?

Method 4: decorator returning a class with the same name

def singleton(class_):
  class class_w(class_):
    _instance = None
    def __new__(class_, *args, **kwargs):
      if class_w._instance is None:
          class_w._instance = super(class_w, 
                                    class_).__new__(class_, 
                                                    *args, 
                                                    **kwargs)
          class_w._instance._sealed = False
      return class_w._instance
    def __init__(self, *args, **kwargs):
      if self._sealed:
        return
      super(class_w, self).__init__(*args, **kwargs)
      self._sealed = True
  class_w.__name__ = class_.__name__
  return class_w

@singleton
class MyClass(BaseClass):
    pass

Pros

  • It's a true class
  • Auto-magically covers inheritance

Cons

  • Is there not an overhead for creating each new class? Here we are creating two classes for each class we wish to make a singleton. While this is fine in my case I worry that this might not scale. Of course there is a matter of debate as to whether it aught to be too easy to scale this pattern...
  • What is the point of the _sealed attribute
  • Can't call methods of the same name on base classes using super() because they will recurse. This means you can't customize __new__ and can't subclass a class that needs you to call up to __init__.

Source: (StackOverflow)

Howto get all methods of a python class with given decorator

How to get all methods of a given class A that are decorated with the @decorator2?

class A():
    def method_a(self):
      pass

    @decorator1
    def method_b(self, b):
      pass

    @decorator2
    def method_c(self, t=5):
      pass

Source: (StackOverflow)

How to write a custom decorator in django?

The problem -

@is_premium_user
def sample_view:
          .......
          ......

I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project?


Source: (StackOverflow)

Preferred way of defining properties in Python: property decorator or lambda?

Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?

@property
def total(self):
    return self.field_1 + self.field_2

or

total = property(lambda self: self.field_1 + self.field_2)

Source: (StackOverflow)

ASP.NET MVC Routing Via Method Attributes [closed]

In the StackOverflow Podcast #54, Jeff mentions they register their URL routes in the StackOverflow codebase via an attribute above the method that handles the route. Sounds like a good concept (with the caveat that Phil Haack brought up regarding route priorities).

Could someone provide some sample to make this happen?

Also, any "best practices" for using this style of routing?


Source: (StackOverflow)

Please help me understand the "Decorator Pattern" with a real world example.

I was studying the Decorator Pattern as documented in GOF. It seems like a complicated design pattern to me.

So please, help me understand the Decorator Pattern. Could someone give a use-case example of where this is useful in the real world?


Source: (StackOverflow)

How to create a Python decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters:

@redirect_output("somewhere.log")
def foo():
    ....

or without them (for instance to redirect the output to stderr by default):

@redirect_output
def foo():
    ....

Is that at all possible?

Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve.


Source: (StackOverflow)

Python - is there a list of decorators somewhere?

I know of @staticmethod, @classmethod, and @property, but only through scattered documentation. Is there a complete list of function decorators that are built into Python?


Source: (StackOverflow)

Getting method parameter names in python

Given the python function:

def aMethod(arg1, arg2):
    pass

How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")

The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")


Source: (StackOverflow)

when do we need Decorator Pattern?

When do we need to go for Decorator pattern? If possible give me a real world example that suits that pattern.


Source: (StackOverflow)

Django: Staff Decorator

I'm trying to write a "staff only" decorator for Django, but I can't seem to get it to work:

def staff_only(error='Only staff may view this page.'):
    def _dec(view_func):
        def _view(request, *args, **kwargs):
            u = request.user
            if u.is_authenticated() and u.is_staff:
                return view_func(request, *args, **kwargs)
            messages.error(request, error)
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home')))
        _view.__name__ = view_func.__name__
        _view.__dict__ = view_func.__dict__
        _view.__doc__ = view_func.__doc__
        return _view
    return _dec

Trying to follow lead from here. I'm getting:

'WSGIRequest' object has no attribute '__name__'

But if I take those 3 lines out, I just get a useless "Internal Server Error". What am I doing wrong here?


Source: (StackOverflow)

Python decorator as a staticmethod

I'm trying to write a python class which uses a decorator function that needs information of the instance state. This is working as intended, but if I explicitly make the decorator a staticmetod, I get the following error:

Traceback (most recent call last):
  File "tford.py", line 1, in <module>
    class TFord(object):
  File "tford.py", line 14, in TFord
    @ensure_black
TypeError: 'staticmethod' object is not callable

Why?

Here is the code:

class TFord(object):
    def __init__(self, color):
        self.color = color

    @staticmethod
    def ensure_black(func):
        def _aux(self, *args, **kwargs):
            if self.color == 'black':
                return func(*args, **kwargs)
            else:
                return None
        return _aux

    @ensure_black
    def get():
        return 'Here is your shiny new T-Ford'

if __name__ == '__main__':
    ford_red = TFord('red')
    ford_black = TFord('black')

    print ford_red.get()
    print ford_black.get()

And if I just remove the line @staticmethod, everything works, but I do not understand why. Shouldn't it need self as a first argument?


Source: (StackOverflow)