[Python] VS Code not being able to recognize modules and constants imported from other scripts

Discussão em 'Python' iniciado por Stack, Outubro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have a general question when working on larger projects using Visual Studio Code, where I want to avoid writing the same imports and defining constants in every python file. Let us say I have a project structure as follows:

    project/
    helpers.py
    scripts/
    plot.py


    In helpers.py, I import modules and define constants for plotting, such as

    import matplotlib.pyplot as plt

    LINE_WIDTH = 2


    As I want to avoid defining the line width on figures and importing matplotlib.pyplot in every script, I add the project folder to my python path, export $PYTHONPATH=/folder/to/project/:$PYTHONPATH, such that I in plot.py simply can write

    from helpers import *

    plt.plot([1,2,3], [1,4,9], lw=LINE_WIDTH)
    plt.savefig('figure.png')


    In plot.py, VS Code believes that plt and LINE_WIDTH are not defined, but the scripts run fine, and I get the plot. Is there any way to make VS Code realize what have been imported from helpers.py, such that I do not have to remember all the specific variable namings when making new scripts?

    I have tried to search for similar problems, but the closest I get is to problems related to relative imports.


    I add a screenshot to visualize my problem:

    [​IMG]

    Continue reading...

Compartilhe esta Página