Any tips on how to further investigate root cause ...
# ask-community
j
Any tips on how to further investigate root cause for:
Copy code
Unexpected error: ValueError('Could not infer an active Flow context.')
z
Hey @Jay Sundaram -- you'll have to provide more information than this. Generally this means you did
Copy code
@task
def foo():
   pass

with Flow() as flow:
    pass

foo()
z
Hi Jay - any chance you could post a minimum example of your flow code? Typically this error happens when tasks are called outside flow context block. For example
Copy code
from prefect import task

@task
def my_task():
        print ('hi')

my_task_ = my_task()
z
😄
👋 1
(note that it's called not initialized)
👍 1
Hey @Jay Sundaram -- let's continue this conversation in the main thread so other people can benefit and help as well.
I've tried to improve that error message to help narrow down your problem, can you install my patch with
pip install git+<https://github.com/PrefectHQ/prefect.git@improve-flow-context-err>
then try again?
j
sure. thanks. pip install failed. too much STDERR to post here.
z
Ah do you have
git
installed?
🙂 1
pip install <https://github.com/PrefectHQ/prefect/archive/improve-flow-context-err.zip>
should work too
j
something to do with my pip trying to pull from our CodeArtifact pypi
z
(that second install failed for me actually 😞 looks like that's not an easy option)
j
there's nothing wrong with calling a task from within a task, correct?
z
If you do that you need to call
task.run()
not
task()
Otherwise there wouldn't be a flow context (as this error says 😄 )
Hopefully adding the task name will help clarify things.. perhaps I should add even more information?
j
Copy code
@task()
def mytask2():
    print("task 2")

@task()
def mytask1():
    print("task 1")
    mytask2()

with Flow('myflow') as flow:
    mytask1()
reasonable?
z
That will break -- you'll need to call
mytask2.run()
🤔 1
When you call a task with
task()
you are creating an edge while defining a flow, not running it immediately.
j
Copy code
@task()
def mytask2():
    print("task 2")
    return {'status': 'good'}

@task()
def mytask1():
    print("task 1")
    t2_results = mytask2.run()
    print(f"task 2 returned status '{t2_results['status']}'")

with Flow('myflow') as flow:
    mytask1()
ok, so like this.
z
Yep!
When you do it this way though, the Prefect API will not know about
mytask2
so you won't get to see it in the UI and such.
j
Because of the returning of some result or because of running a task from within a task?
z
The second one
👍 1
It's no longer a part of the 'flow' that we track -- it's just code you're executing in a task
j
so then why decorate it with @task? should i make just make it a regular function?
z
You definitely could. Decorating it with
@task
might be misleading in this case. The only reason to do so is if you intend to add it to the flow later.
👍 1