I have a task that globs for files given a file pa...
# ask-community
c
I have a task that globs for files given a file path, in my flow I call that task with something like
f"{os.path.dirname(os.path.realpath(__file__))}/layouts"
, however this causes the following (when executing from Prefect cloud):
Copy code
Failed to load and execute Flow's environment: NameError("name '__file__' is not defined")
how come that global isn't available?
c
the
__file__
global is only available when either executed as main (i.e., if
__name__ == "main":
) or if it's a file located within an installed package; agents submit flow runs using the Prefect CLI so essentially this runs the flow in an interpreter, where this attribute isn't available / set by Python
c
sadness
is there another way to get the path of the currently executing task?
a file located within an installed package
the file is contained in the PYTHONPATH, is that relevant?
c
unfortunately no; I'm not sure how robust this is, but I believe this will work:
Copy code
@task
def my_task():
    ...

my_task.__code__.co_filename # <-- prints the correct location where the task is defined
c
how can I access that from within
my_task
?
should I define the task using the
class
structure and get at from
self
?
c
Yea I think that would be the simplest approach if you're comfortable with defining tasks as classes
c
cool, thanks!
c
👍 anytime!
c
I'm not seeing the attribute
___code___
, here's the full `dir(self)`:
Copy code
['__add__', '__and__', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__mifflin__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__or__', '__pow__', '__radd__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__signature__', '__sizeof__', '__slotnames__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_cached_reserved_attributes', 'auto_generated', 'bind', 'cache_for', 'cache_key', 'cache_validator', 'checkpoint', 'copy', 'inputs', 'is_equal', 'is_not_equal', 'log_stdout', 'logger', 'map', 'max_retries', 'name', 'not_', 'nout', 'or_', 'outputs', 'result', 'retry_delay', 'run', 'serialize', 'set_dependencies', 'set_downstream', 'set_upstream', 'skip_on_upstream_skip', 'slug', 'state_handlers', 'tags', 'target', 'task_run_name', 'timeout', 'trigger']
c
ah that attribute is only available on methods / functions that you implement -- try
self.run.__<http://code__.co|code__.co>_filename