Python Forum
decorate an imported function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
decorate an imported function?
#4
In case it still isn't quite clear, a decorator is just syntactic sugar around wrapping something with something else, aliasing the original function, if you will.  But there's no reason it has to be JUST for functions...

>>> def wrapper(cls):
...   class Eggs:
...     def __init__(self, other):
...       print("pretending to be {0}".format(other))
...       self.other = other()
...   def inner():
...     return Eggs(cls)
...   return inner
...
>>> @wrapper
... class Spam:
...   def __init__(self):
...     print("SPAM!")
...
>>> x = Spam()
pretending to be <class '__main__.Spam'>
SPAM!
I can't actually think of a use for that which wouldn't be better served by just using inheritance, but if such a situation arises, it is possible.
Reply


Messages In This Thread
decorate an imported function? - by Skaperen - May-14-2017, 09:46 AM
RE: decorate an imported function? - by wavic - May-14-2017, 11:49 AM
RE: decorate an imported function? - by micseydel - May-14-2017, 05:54 PM
RE: decorate an imported function? - by nilamo - May-22-2017, 08:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Can a module tell where it is being imported from? stevendaprano 3 1,167 Apr-12-2022, 12:46 AM
Last Post: stevendaprano
  module detecting if imported vs not Skaperen 1 1,668 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  [newbie] Why is a module imported twice? Winfried 3 4,072 Apr-02-2021, 04:48 AM
Last Post: deanhystad
Star NameError – function doesn't recognize imported modules Sir 4 3,484 Dec-01-2020, 06:36 AM
Last Post: Sir
  how to do setattr() from an imported module nutron 3 3,338 Sep-20-2019, 08:16 PM
Last Post: nutron
  argparse and imported modules spatialdawn 2 5,438 Dec-01-2018, 12:35 PM
Last Post: spatialdawn
  global namespace of an imported function (2 Qs) Skaperen 4 3,245 Oct-09-2018, 12:30 AM
Last Post: Skaperen
  passing a value to imported code Skaperen 0 1,979 Sep-28-2018, 03:59 AM
Last Post: Skaperen
  function NOT imported from a module Skaperen 10 6,040 Aug-31-2018, 07:30 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020