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')
3

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

and what hinders you to do the same to a function? def f(): pass; f.whatever = "should work"
@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: Nope, in his example f is just a regular function, not a full-fledged regular class instance. It has no __init__(), method inheritance, siblings sharing class attributes, etc. It's only a function with an attribute. And in this case it's all it needs.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.