Forum Archive

160032 import from same directory still broken

userista

Is it still possible to do an import from the same directory?

E.g.

foo
...bar.py
...init.py
baz.py

And in baz.py: from foo import bar

This used to work, though I'm not sure if it was supposed to.

Also, @omz should probably start a new thread for every beta. Instead of having multiple per beta.

dgelessus

Yes, that is completely normal Python import behavior. If a folder contains an __init__.py, it is treated as a package and you can import submodules from it. (This of course only works for locations that can be imported from, like the main Script Library or site-packages.)

ywangd

It seems that @omz took the dot out from default sys.path. That is why you code does not import. Add following code befor the import and it will work again.

import sys
if '.' not in sys.path:
    sys.path.insert(0, '.')
omz

Yes, I accidentally removed "." from the default sys.path, will be back in the next build.

Tizzy

I originally posted the below in 1.6 thread. The workaround from ywangd worked for me.

Build 160025 bug report.

I have a folder structure /AAAdriver/ inside of which I have DriverInfo.py and TripDataA.py.

previously, from within DriverInfo.py,

"import TripDataA"

worked just fine. With the latest beta, I'm getting "ImportError: No module named TripDataA"

Webmaster4o

This also seems to break the requests module, fix soon please!

userista

In 160032 '.' is still not in sys.path

Webmaster4o

Yeah, that's a shame. Just noticed that myself.

polymerchm

Agreed. module in same folder is not findable. Any temp fix, short of moving it to site-packages?

Webmaster4o

Yeah, I can use

import sys
if '.' not in sys.path: sys.path.append('.')

At the beginning of a script to fix this. This has to be above your import statement

JonB

just bumping this... seems to have missed the latest beta

omz

Hmm, works for me in the latest beta.

Phuket2

Mine is also working. I also doubled checked to make sure I didn't have a statement in the pythonista_startup.py that was correcting it

JonB

oh i see...

>>> '.' in sys.path
False

but the "played" path does get put on top, both for Play button and editor actions.
execfile does not do this, though i guess we were already responsible for setting path using execfile, at least indirectly through chdir.

Editor actions are a little surprising, in that they change sys.path globally. I have not tried this yet, but might that cause unintended consequences for running programs? I.e if there is some dynamic import, running a wrench item would cause that import to break.

I guess the point is, scripts should add their own import folder to sys.path, if they want to be guaranteed to be able to import from that folder later.