ValueError: attempted relative import beyond top-level package

I’ve manually cloned the fastai project and tried to run fastai/vision/gan.py manually(just to see if the …torch_core import *) would throw and error and got the error ValueError: attempted relative import beyond top-level package because of from ..torch_core import * in that file.

Why does that throw an error? As far as I am concerned, that is valid python code that uses relative import. If this breaks, then how come when not using it directly from source, this works? For example, if I wrote a python file in a directory that uses the pip installed fastai, and run from fastai.vision.gan import *
in that file, then everything is loaded and fine even though I suspect the from fastai.vision.gan import* would fail because it’ll try to import from ..torch_core import * as well?

I think this SO would answer this well: https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import

It is more or less because of how python determines what is considered in/out of a package. In the first case of you running manually python doesn’t know vision is its own package, as python doesn’t look up the directory hierarchy to determine packages.

In the case where python is accessing from the top level, it knows where the packages are, as that is the context that python is keeping track of package structure…

That is my understanding anyway.

1 Like

Thanks marii~