hey im trying to use classes with prefect but runn...
# prefect-community
a
hey im trying to use classes with prefect but running into the following... can someone point out the correct way of doing this?
from prefect import Flow, Task, Parameter
class PrintTheStatements(Task):
    
def task_1():
        
print(f"first name is {self.firstname} and last name is {self.lastname}")
    
def run(self, firstname, lastname):
        
self.firstname = firstname
        
self.lastname = lastname
        
task_1()
if __name__ == "__main__":
    
with Flow("ClassTask") as flow:
        
firstname = Parameter("firstname", default="anish")
        
lastname = Parameter("lastname", default="chhaparwal")
        
apt = PrintTheStatements()
        
result = apt(firstname=firstname, lastname=lastname)
    
flow.run()
a
It looks like you wrote
task_1()
rather than
self.task_1()
a
oh damn! my bad. thanks for the help
a
You're welcome. Btw, I have never directly defined classes for tasks myself, but looking at the docs: https://docs.prefect.io/core/concepts/tasks.html#overview It looks like the recommended approach is to define the constructor, then you would write:
result = PrintTheStatements(firstname, lastname)
in such a case the
run
method will replace the
task_1
method.
Oh, sorry, an amendment: you'll still the two-step approach of creating the task object and then using it. So your current approach is fine, except that it would be overkill to assign firstname and lastname to be member variables in
run
when
run
can replace
task_1
. Having a constructor instead means that you could customise the task before running it.
a
I used task_1 as a representation of multiple functions doing various task on class obj before returning it.