Why I can’t import upper level modules or functions?

I have such a project structure:

scripts:
   apps:
      __init__.py
      app.py
   baike:
      __init__.py
      search.py

    __init__.py

I PyCharm, I marked ‘scripts’ as project source root, and in apps/app.py, I want to import:

from scripts.baike import Query

In baike.py, I have:

class Query(object):
     def __init__(self):
        pass

     def query(text):
        pass

What I want is to import the ‘query’ function from baike.Query class. However, when I type ‘scripts.’ in PyCharm, ‘scripts’ is not available for import. I didn’t create any setup.py, and just want to use the ‘scripts’ as the source root.

What’s the issue?

Answer

The only way to import modules that come from upper level dirs is to mark the dir scripts as Root. To do that in PyCharm, right click on the folder scripts and click on Mark Directory as > Sources Root. It should do the trick.

Leave a Reply

Your email address will not be published. Required fields are marked *