Dave
Dave

Reputation: 454

Python importing from incorrect module (which bears the same name), VSC

I have two modules, both named connection.py in two separate environments listed below. Both of the folders containing connection.py are in my PYTHONPATH system environment variable.

However, if that of spec is not placed above that of bvbot, spec's test_connection.py attempts to import from the connection.py of bvbot.

If in cmd, I can resolve this by moving the path of spec above that of bvbot. But, in Visual Studio Code, spec's test_connection.py still imports from bvbot's connection.py.

The two environments of interest are:

C:\Users\You_A\Desktop\2016Coding\VirtualEnviroments\spec\spec_trading
C:\Users\You_A\Desktop\2016Coding\VirtualEnviroments\bvbot\Legacy_bvbot

Structure of the spec path above:

src/
    spec_trading/
        __init__.py
        connection.py
tests/
    __init__.py
    connection.py

spec test_connection.py:

import pytest

from connection import Connection, OandaConnection


class TestConnection:
    def test_poll_timeout(self):
        connection = Connection()
        timeout = 10.0
        connection.set_poll_timeout(timeout)
        assert connection.poll_timeout == timeout

What I am doing wrong here? How can I resolve this without resorting to manually faffing with my systems environment variables and resolve the VSC issue?

Upvotes: 1

Views: 459

Answers (1)

Brett Cannon
Brett Cannon

Reputation: 16070

Easiest solution is to not use implicit relative imports (I assume this is Python 2.7). Basically use explicit relative imports and make sure the imports resolve within the package they are contained within instead of Python having to search sys.path for the module.

And if you are using Python 2.7, put from __future__ import absolute_import at the top of the file.

Upvotes: 1

Related Questions