4

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:

  • Without having to rename my module (websocket.py)
  • Without polluting my project with ugly __init__()
  • Needs to work both on Python3 and 2
JasonMArcher
  • 13,296
  • 21
  • 55
  • 51
Pithikos
  • 16,954
  • 15
  • 107
  • 126

5 Answers5

4

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

DaveS
  • 855
  • 1
  • 8
  • 20
1

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
Mike Dog
  • 74
  • 6
0

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>')
volcano
  • 3,490
  • 20
  • 27
  • A Python 3.3+ solution here as well: http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – Wes Feb 18 '15 at 18:26
0

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.

Pithikos
  • 16,954
  • 15
  • 107
  • 126
0

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

guidot
  • 4,709
  • 2
  • 23
  • 36