1

This is the content of test.py

def main(ccfg):
    print(ccfg.param)

This is the content of main.py:

import test
import cfg
ccfg = cfg.cfg()
test.main(ccfg)

cfg.py contains a config-class:

class cfg:
    def __init__(self):
        pass
    param = 5

When writing the code in test.py, Pycharm (or any other IDE) does not recognize that ccfg is an instance of cfg. How can I make the class known to the IDE so that I get the code suggestions?

Alon
  • 434
  • 4
  • 19

1 Answers1

0

Mark you folder as Sources Root in IDE. Right Click -> Mark Directory As -> Sources Root

grapes
  • 8,185
  • 1
  • 19
  • 31
  • How does test.py know then that ccfg is an instance of cfg ?! – Alon Dec 04 '18 at 09:59
  • `test.py` knows nothing. It is **PyCharm** who knows. PyCharm parses your files in folders, which are specified as `Sources Root` and remembers types/instances. – grapes Dec 04 '18 at 10:04
  • But the autocomplete/code suggestion is done via a static type checker which is based on an internal copy of [typeshed](https://github.com/python/typeshed). It does not require the folder to be marked as Sources Root. – shmee Dec 04 '18 at 11:21
  • Doesn't it build it's code database from sources? I guess, it gets to know what sources to parse based on information on project source tree, which it gets from PyCharm – grapes Dec 04 '18 at 11:26
  • Typeshed is used for builtins and well known 3rd party packages. Obviously, it cannot guess types for code written by the user. The module `test.py` doesn't know about `main.py` calling its `main` method with an instance of `cfg`. But if we know, that it always will be a instance of cfg, we can add a type hint by using [docstrings](https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code), [stubs](https://www.python.org/dev/peps/pep-0484/#stub-files) or [typing](https://docs.python.org/3.5/library/typing.html) in Python 3.5+. – shmee Dec 04 '18 at 11:54
  • Actually PyCharm can guess types in many cases. For example, if the class was called `Cfg` and the parameter was called `cfg`, it would offer completion of `Cfg` members in `test.py` even without type hints. – yole Dec 04 '18 at 13:06
  • @yole, You are right, it can do that, but only based on naming, afaik. You'll have to model your naming scheme around your desired autocompletion. I'd rather not :) Using typing is the only method I can think of, that does not impose restrictions on your names (and other stuff, like "protected/private" attributes in classes) and very likely also works in other IDEs. – shmee Dec 04 '18 at 13:38
  • Our intention was to model the completion heuristics around the naming scheme that people use anyway. – yole Dec 04 '18 at 13:41