Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file

Как я могу увидеть значения по умолчанию для правил серьезности диагностики Python в VS Code?

Как я могу увидеть (или извлечь в файле JSON) значения по умолчанию для правил серьезности диагностики для Python в VS Code, как описано здесь? https://github.com/microsoft/pylance-release/blob/main/DIAGNOSTIC_SEVERITY_RULES.md#diagnostic-severity-rules

Если вам просто нужно увидеть значение по умолчанию в VS Code, просто откройте файл settings.json (User или Workspace) и введите каждый из этих ключей один за другим. Всплывающее окно должно появляться для каждого возможного значения, а значение по умолчанию будет иметь подсказку « Значение по умолчанию » в описании.

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Вы также можете проверить каталог расширения Pylance, установленного на вашем компьютере. Сначала найдите каталог для всех ваших расширений VS Code :

Extensions are installed in a per user extensions folder. Depending on your platform, the location is in the following folder:

Перейдите в эту папку и найдите ms-python.vscode-pylance* папку.

Значение по умолчанию находится в default ключе. (Обратите внимание, что значение по умолчанию reportMissingImports совпадает с тем, что показано на скриншоте из всплывающего окна settings.json.

Это уже файл JSON, если вам нужно извлечь его в формат JSON.

when running Python test from withing VS Code using CTRL+F5 I’m getting error message

ImportError: attempted relative import with no known parent package

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

when running Python test from VS Code terminal by using command line

I’m getting error message

ValueError: attempted relative import beyong top-level package

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Here is the project structure

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

How to solve the subject issue(s) with minimal (code/project structure) change efforts?

[Update]

I have got the following solution using sys.path correction:

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

but I guess there still could be a more effective solution without source code corrections by using some (VS Code) settings or Python running context/environment settings (files)?

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

The other solution is to open your project in VS Code one directory higher (whatever directory that contains solutions and tests ). You will still need to change how you execute your code, though, so you are doing it from the top-level as I suggested above.

Do not use relative import. Simply change it to

Update

Now, the project directory will be in the PYTHONPATH for every tool that is launched via VS Code. Now Ctrl+F5 works fine.

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Setup a main module and its source packages paths

Solution found at:

Which also provide a neat in-depth video explanation

The solution to the attempted relative import with no known parent package issue, which is especially tricky in VScode (in opposite to Pycharm that provide GUI tools to flag folders as package), is to:

Add configuration files for the VScode debugger

Id Est add launch.json as a Module (this will always execute the file given in «module» key) and settings.json inside the MyProjectRoot/.vscode folder (manually add them if it’s not there yet, or be guided by VScode GUI for Run & Debug )

launch.json setup

Id Est add an «env» key to launch.json containing an object with «PYTHONPATH» as key, and «$/mysourcepackage» as value
final launch.json configuration

settings.json setup

Id Est add a «python.analysis.extraPaths» key to settings.json containing a list of paths for the debugger to be aware of, which in our case is one [«$/mysourcepackage»] as value (note that we put the string in a list only for the case in which we want to include other paths too, it is not needed for our specific example but it’s still a standard de facto as I know)
final settings.json configuration

This should be everything needed to both work by calling the script with python from the terminal and from the VScode debugger.

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

An Answer From 2022

Here’s a potential approach from 2022. The issue is identified correctly and if you’re using an IDE like VS Code, it doesn’t automatically extend the python path and discover modules.

Here are the drawbacks of the solution provided in the k0nze.dev solution:

In your example tests falls under it’s own directory and has it’s own init.py. In an IDE like VS Code, it’s not going to automatically discover this directory and module. You can see this by creating the below script anywhere in your project and running it:

_path.py

Windows

Mac / Linux / etc

Test It Out

Now re-run your _path.py script and you should see permanent additions to your path. This works for deeply nested modules as well if your company has a more stringent project structure.

VS Code

The solution is instead to use dot notation to prepend the path by using relative file path. This allows the user to append a file path relative to the project structure and not their own file structure.

For Other IDE’s

You can actually see the location that your version of VS Code is looking for by searching for the below setting in your preferences:

How can I see the default values for the Python Diagnostic Severity Rules in VS Code?

How can I see (or extract in a JSON file) the default values for the Diagnostic Severity Rules for Python in VS Code, as described here? https://github.com/microsoft/pylance-release/blob/main/DIAGNOSTIC_SEVERITY_RULES.md#diagnostic-severity-rules

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you just need to see the default value in VS Code, just open the settings.json file (User or Workspace), and enter each of those keys one by one. A popup should appear for each possible value, and the default value will have a «Default value» hint in the description.

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

You can also check the Pylance extension’s directory installed on your machine. First, find the directory for all your VS Code extensions:

Extensions are installed in a per user extensions folder. Depending on your platform, the location is in the following folder:

Go to that folder, and look for the ms-python.vscode-pylance* folder.

The default value is in the default key. (Notice the default for reportMissingImports matches the one in the screenshot from the settings.json popup.

That’s already a JSON file, if you need to extract it to JSON format.

Why pytest always says » ImportError: attempted relative import with no known parent package»

I’m new to pytest and python. My project structure is :

and test_a.py is:

Then run pytest under projroot :

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

By including a setup.py file in root directory and init.py in every folder worked for me and for importing a package inside any file just give that package location from parent directory

Adding __init__.py to project root actually messed up my pytest discovery and also pylint (causing Unable to import ‘angles’ pylint(import-error) ). I had to remove it from project root and only add it inside my tests folder, which solved both my pytest discovery and pylint warning.

With __init__.py in project root, i’ll have ModuleNotFoundError: No module named ‘angles’

Below is my folder structure with both pytest discovery and pylint (without warning) working :

Before I found out that the issue was having an unnecessary __init__.py in project root. I also tried

None of them worked.

Another hack I tried which fixed both pytest and test discovery was inserting sys.path.insert(0,’/Users/hanqi/Documents/Python/powerfulpython’) in the code but this is way too ugly. I didn’t want to add lines to code just for testing then have to delete them later.

After all these, I deleted __init__.py in root and all’s good. No need for any of the above list of 3 items.

Many solutions I went through deal with finding the tests folder, but that was not my problem. My tests were found correctly in their folders, just that the from angles import Angle was breaking which causes test discovery to fail.

Investigating how does __init__.py in project root break things:

I printed sys.path and realized with it,

/Documents/Python got prepended to sys.path and without it,

/Documents/Python/powerfulpython to be prepended and the __init__.py in project root cause

/Documents/Python to be prepended, but strangely i only saw the latter when I left both __init__.py inside.

I also tried deleting the __init__.py inside tests (but let __init__.py in root stay), and see

Documents/Python/powerfulpython/tests prepended to sys.path. This same line is also prepended if I delete both __init__.py in root and tests, not sure why.

Edit: The above behaviour is explained at https://docs.pytest.org/en/6.2.x/pythonpath.html

It will then search upwards until it can find the last folder which still contains an __init__.py file in order to find the package root

Both have the effect of editing sys.path, helping to make failing imports possible

So why does doing absolute import break with the extra __init__.py in

/Documents/Python to sys.path, but my absolute import needed to have

I have a trouble with imports in my project.

My directories structure is the following:

ImportError: attempted relative import with no known parent package

In folder2/__init__.py I did what I saw on a tutorial for making packages in Python:

So far, anything has worked. What should I do? I use Python 3.7.5

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть фото Diagnostics for imports that have no corresponding imported python file or type stub file. Смотреть картинку Diagnostics for imports that have no corresponding imported python file or type stub file. Картинка про Diagnostics for imports that have no corresponding imported python file or type stub file. Фото Diagnostics for imports that have no corresponding imported python file or type stub file

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In your example, folder_1 and folder_2 are two separate and unique packages. There are no relative imports between them. Put them in a single outer package to get it to work

Running test.py script

But there is a workaround where modules can be called using the «-m» option. But his only works if myproject is in the python path. It works here because I’m in the parent of myproject when I call it.

For those who don’t want to change their file system structure to make relative imports work I’ve created a new, experimental library: ultraimport

It allows file system based imports no matter how you run your code. ultraimports will always work.

In your file.py you would then write

This import does not depend on your current working directory and it does not care if it are modules, packages or scripts. It’s a Python file and you can import it.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *