Python Forum
decorate an imported function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
decorate an imported function?
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.
from module import function

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

any_func = decorator(function)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
Using decorator notation, no. But you can wrap as the previous answer shows.
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
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'>
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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to acquire an imported file creation time thunderspeed 4 280 Sep-23-2021, 04:27 PM
Last Post: Larz60+
  [newbie] Why is a module imported twice? Winfried 3 2,062 Apr-02-2021, 04:48 AM
Last Post: deanhystad
Star NameError – function doesn't recognize imported modules Sir 4 1,148 Dec-01-2020, 06:36 AM
Last Post: Sir
  how to do setattr() from an imported module nutron 3 1,520 Sep-20-2019, 08:16 PM
Last Post: nutron
  argparse and imported modules spatialdawn 2 3,154 Dec-01-2018, 12:35 PM
Last Post: spatialdawn
  global namespace of an imported function (2 Qs) Skaperen 4 1,659 Oct-09-2018, 12:30 AM
Last Post: Skaperen
  passing a value to imported code Skaperen 0 1,034 Sep-28-2018, 03:59 AM
Last Post: Skaperen
  function NOT imported from a module Skaperen 10 3,046 Aug-31-2018, 07:30 AM
Last Post: Gribouillis
  [SYS + OS] Script not Imported, Error Found ! JamieVanCadsand 2 2,305 Sep-22-2017, 08:03 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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