Home > Back-end >  How can I successfully use a decorator function for my problem?
How can I successfully use a decorator function for my problem?

Time:10-20

I'm trying to use the pie "@" syntax for decorators but I can't seem to get this to work for my particular example.

I can achieve my intended result with this..

import pandas as pd

def prepare_todays_campaigns(decorated):
  
  campaigns_outgoing = pd.DataFrame({"test":[1,2,3]})

  n_campaigns = len(campaigns_outgoing)

  if n_campaigns > 0:

      print(
          f"{n_campaigns} to process."
      )

      decorated(campaigns_outgoing)
      
def dec_test(campaigns_outgoing):
  for _, row in campaigns_outgoing.iterrows():
    print(row)
    

prepare_todays_campaigns(dec_test)

i.e.

enter image description here

But when I try and use the @ syntactic sugar, I can't seem to get my expected result...

def prepare_todays_campaigns(decorated):
  
  def wrapper(*args, **kwargs):
    # creatives x campaign
    campaigns_outgoing = pd.DataFrame({"test":[1,2,3]})

    n_campaigns = len(campaigns_outgoing)

    if n_campaigns > 0:

        print(
            f"{n_campaigns} to process."
        )

        decorated(*args, **kwargs)

    
  return wrapper

@prepare_todays_campaigns
def dec_test(campaigns_outgoing):
  for _, row in campaigns_outgoing.iterrows():
    print(row)
    
dec_test()

Result:

enter image description here

Does anyone have any recommendations as to how to solve this?

CodePudding user response:

Look at the method signature def dec_test(campaigns_outgoing):

And when you call the method:

dec_test()

You do not pass in the campaigns_outgoing argument.

  • Related