Home > front end >  How to import from other scripts in VSCode?
How to import from other scripts in VSCode?

Time:09-29

I created the following two scripts in a brand new empty folder called F:\python\hello_world, using Visual Studio Code:

The first is my_function.py:

def hello() -> str:
    return "Hello, World"

The second is my_app.py:

from my_function import hello

print(hello())

When I run this from Visual Studio Code, I get an error saying I can't import:

Traceback (most recent call last):
  File "f:/python/hello_world/my_app.py", line 1, in <module>
    from my_function import hello
ImportError: cannot import name 'hello' from 'my_function' (f:\python\hello_world\my_function.py)

Any clue? I've recently switched from using PyCharm to using VSCode, and I can't quite seem to get started...

New Development

It turns out that, unlike my toy example (which works fine as soon as I add __init__.py to the project's folder), I was trying to run code from within a subfolder of the project. That's a VSCode no-no.

CodePudding user response:

From Python Modules, it said

The __init__.py files are required to make Python treat directories containing the file as packages.

But without it, your code still works well in my VS Code. You may try resetting VS Code by deleting folders %APPDATA%\Code and %USERPROFILE%\.vscode then see if the error goes away.

CodePudding user response:

You can import your function like this:

import my_function

print(my_function.hello())
  • Related