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
  • 14,195
  • 22
  • 56
  • 52
Pithikos
  • 18,827
  • 15
  • 113
  • 136

5 Answers5

5

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
  • 895
  • 1
  • 8
  • 20
1

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
  • 18,827
  • 15
  • 113
  • 136
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
  • 1
  • 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,578
  • 21
  • 28
  • 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

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

guidot
  • 5,095
  • 2
  • 25
  • 37