Python Forum
decorate an imported function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
decorate an imported function?
#1
is it possible to decorate a function that came with an imported module?  if so ... how?  what can be done this way?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
from module import function

def decorator(func):
    def wrapper():
        # do some stuffs
        func()
        # do other stuffs
    
    return wrapper

any_func = decorator(function)
any_func()
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Using decorator notation, no. But you can wrap as the previous answer shows.
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can a module tell where it is being imported from? stevendaprano 3 1,140 Apr-12-2022, 12:46 AM
Last Post: stevendaprano
  module detecting if imported vs not Skaperen 1 1,637 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  [newbie] Why is a module imported twice? Winfried 3 4,037 Apr-02-2021, 04:48 AM
Last Post: deanhystad
Star NameError – function doesn't recognize imported modules Sir 4 3,417 Dec-01-2020, 06:36 AM
Last Post: Sir
  how to do setattr() from an imported module nutron 3 3,292 Sep-20-2019, 08:16 PM
Last Post: nutron
  argparse and imported modules spatialdawn 2 5,387 Dec-01-2018, 12:35 PM
Last Post: spatialdawn
  global namespace of an imported function (2 Qs) Skaperen 4 3,197 Oct-09-2018, 12:30 AM
Last Post: Skaperen
  passing a value to imported code Skaperen 0 1,960 Sep-28-2018, 03:59 AM
Last Post: Skaperen
  function NOT imported from a module Skaperen 10 5,957 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