0

I have two scripts:
script1:

from test import script2

if __name__ == '__main__':
    foo()

script2:

def foo():
    print 'hello'

In the structure:

test:
│   A
│-----B:
│       script2.py
│script1.py

I am trying to call the function foo() from script2.py in script1.py.

I received the error:

This inspection detect names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level itesm are supported better than instance items.

enter image description here

I read number of similar cases but they didn't help me:
Call a function from another file in Python
How to import a function from parent folder in python?
Import Script from a Parent Directory

E235
  • 11,560
  • 24
  • 91
  • 141
  • You need to make it a package with `__init__.py` files. – Artyer Nov 03 '17 at 23:11
  • 1
    You need to import from `test.A.B`. Also you need `__init__.py` files in each folder – OneCricketeer Nov 03 '17 at 23:11
  • What they said above, **or**, you add B to your `PYTHONPATH` environment variable. – GPhilo Nov 03 '17 at 23:13
  • Check your _cwd_ (which by default is appended to _PYTHONPATH_), not to be inside the package. Also, *\_\_init\_\_.py* files in any folder you want to be a package. – CristiFati Nov 03 '17 at 23:13
  • @cricket_007 I put `__init__.py` in each folder and in `script2.py` I added `from A.B.script2 import *` now it works fine. Thanks. – E235 Nov 03 '17 at 23:26
  • `from test import script2` doesn't *ever* create a name other than `script2` in the local namespace. It certainly won't, under any circumstances whatsoever, provide something named `foo`. – Charles Duffy Nov 04 '17 at 00:54

1 Answers1

0

For Python packages to work, you need __init__.py files in the folders. These can be empty.

Then, you are importing from a subfolder, so you need import script2 from A.B

At that point, you may use script2.foo()

Also worth mentioning that Python3 should be targeted for any new projects .

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245