Pithikos
Pithikos

Reputation: 20300

How solve module name collision in Python?

I have a module named websocket. For this module I want some tests and for these tests I pip install the appropriate module. The problem is that the installed module has the exact same name as my own module.

Project structure:

websocket-server
       |
       |---- websocket.py
       |
       '---- tests
               |
               '---- test.py

test.py:

from websocket import WebSocketsServer  # my module
from websocket import create_connection # installed module

Is there a way to solve this:

Upvotes: 4

Views: 10610

Answers (5)

Mike Dog
Mike Dog

Reputation: 74

I have solved a similiar problem with a dirty hack, which works only in UNIX/Linux.

In your root folder, make a soft link to itself:

> ln -s . myroot

Then just import whatever you want with the simple prefix:

import myroot.websocket

Upvotes: 1

guidot
guidot

Reputation: 5333

You could choose a different capitalization like webSocket, since the Python resolution is case-sensitive.

Upvotes: 0

Pithikos
Pithikos

Reputation: 20300

I solved this in the end as I wanted. The solution is hackish but it doesn't matter since it's only for one specific type of tests.

import websocket as wsclient # importing the installed module

del sys.modules["websocket"]
sys.path.insert(0, '../..')
import websocket             # importing my own module

So I can now refer to my own module as websocket and the installed module as wsclient.

Upvotes: 1

volcano
volcano

Reputation: 3582

There's an imp module - although it's on the way to be deprecated in Python 3.4. It allows you to import modules dynamically

my_websource = imp.load_source('my_websource', <path to your module.py>')

Upvotes: 0

DaveS
DaveS

Reputation: 915

Can you nest your module in a package?

from mywebsocket.websocket import WebSocketsServer # my module
from websocket import create_connection # installed module

see https://docs.python.org/2/tutorial/modules.html#packages

Upvotes: 6

Related Questions