0

I have a list of functions that do the same tasks in different ways. Let's call them scrapper_german, scrapper_english, scrapper_spanish. I want to make my program know things about this functions, like how effective they are in some tasks. I can use a dictionary.

function_info = { 'scrapper_english': ('English', 'FullyTested'),
...
}

But is there a way to insert those properties, those attributes, into the function? Like a class can have

my_dog.favourite_foods = ('Cow', 'Pork')
Mert Mint
  • 29
  • 4
  • 2
    You probably need to use a class here, here's one that's literally an example on dogs - https://realpython.com/python3-object-oriented-programming/ – Peter Sep 24 '21 at 10:26
  • 3
    Check [Best way to add attributes to a Python function](https://stackoverflow.com/q/47056059/4046632) – buran Sep 24 '21 at 10:30
  • `def function_x(): pass` - `function_x.SomeAttribute = "whatever"` ... – Patrick Artner Sep 24 '21 at 10:42

2 Answers2

1

Propably the best way is to use class __call__ function to imitate your function with class possibilities

something like this:

class EnglishScraper:
    info_1=None
    info_2=None
    info_3=None
    info_4=None
    performance=None

    def __init__(self):
        """
        do you want to set some info in the constructor?
        """


    def __call__(self,*args,**kwargs): # or instead of args/kwargs you can use something specific
        """
        the function
        you can use any attributes -> self.info....
        """
        print('hello from function')
        


scrapper_english = EnglishScraper()

# __call__ is called like this
scrapper_english()

import time

# measure and save performance attribute
start = time.time()
scrapper_english()
performance = time.time()-start
scrapper_english.performance = performance
Martin
  • 3,333
  • 2
  • 18
  • 39
  • and what hinders you to do the same to a function? `def f(): pass; f.whatever = "should work"` – Patrick Artner Sep 24 '21 at 10:43
  • @PatrickArtner interesting, didnt know about this feature... But to be honest, never seen this being used. And with this new knowledge, I wouldnt use it anyway. I see that function is after all just another instance of class just like in my example... But without definition – Martin Sep 24 '21 at 10:46
1

Python functions are objects and as such you might set and get attributes, consider that

def somefunc(x):
    return x
print(isinstance(somefunc,object))
somefunc.effect = "123"
print(somefunc.effect)

output

True
123

That being said as you want to make my program know things about this functions, like how effective they are in some tasks storing that information in structure independent from your functions seem to provide greater flexibility and you might easily to provide such data for someone to analyse it without exposing functions themselves.

Daweo
  • 31,313
  • 3
  • 12
  • 25