Home > Software engineering >  Python import module with package name
Python import module with package name

Time:05-22

I've been reading a lot of questions about this issue and still have some questions.

First of all i want to explain a little what i want to do

I have this file system

 Project/
       └──main.py
       └──transformations/
                        └──__init__.py
                        └──translate.py
                        └──rotate.py
                        └──scale.py

And main.py being:

import transformations

if __name__ == "__main__":
    print("Main:")
    transformations.translate.test()
    transformations.rotate.test()
    transformations.scale.test()

each test() just prints "Hello" on console.

Searching i was able to somehow make it work giving __ init__.py the following command lines:

import transformations.translate
import transformations.rotate
import transformations.scale

So when i try to run the code from main.py the code is executed as intended but VSCode give me any autocomplete suggestion, so i dont know if im doing things correctly.

As you can see in this image.When i write "transformations." vscode wont give me any prompt to autocomplete "translate" "rotate" or "scale". And if i write the function call of the module anyways, it runs as intended but vscode does not recognize it as a module or function as it does with sqrt from math module as shown in the second image, where it puts "sqrt" in yellow.

So, basically, to summarize, the code is working as i want to, but im not sure if im doing things properly because the vscode autocompleter and color formatter is not detecting the scripts on the package folder.

Thanks in advance!

CodePudding user response:

Because you didn't import them as modules in your __init__.py file. You can use the form from ...import... to import in the __init__.py file. like below

from transformations import translate
from transformations import rotate
from transformations import scale

Hope this helps you.

  • Related