#๐Ÿ”’ vscode relative imports

10 messages ยท Page 1 of 1 (latest)

patent arrow
#

iam working with vscode alot and i dont know why but when i use relative iports vscode doesnt allow it

    from ..helpers.enums import Environment
ImportError: attempted relative import beyond top-level package

is there a way to fix it because it would be nice to be able to use relative imports for the code to be used in a multi repo

from game_core_client import Configuration
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict

from ..helpers.enums import Environment


class Settings(BaseSettings):
muted sorrelBOT
#

@patent arrow

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

untold geyser
#

This depends on how your script is being run, and howyour files are structured.

Python import can be divided into 2 types:

  • absolute imports, with no leading dots like your pydantic - these search for the name along sys.path
  • relative imports like your ..helpers.enums; these search in the current package, and only for names in the package
#

The import ..helpers.enums implies that:

  • your file is in a package (and was itself imported from that package)
  • that enums is where you expect relative to the file

If your file's path is eg /path/to/the/package/subfolder/foo.py
then ..helpers.enums refers to the file /path/to/the/package/helpers/enums.py

So your file must have been imported from package, and must be down a level (for the second . to go up a level)

#

@patent arrow ^^

patent arrow
untold geyser
#

If your file is in the package, you can run it directly but you need to do it as an import:

python -m package.subfolder.foo

instead of

python /path/to/the/package/subfolder/foo.py

The former means it's in the package, the latter is just some arbitrary script, not part of a package from Python's point of view.
@patent arrow

#

The -m means "run this module". The other thing means "run this script".

muted sorrelBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.