Q:

Python file and class match imported file and class

I'm trying to wrap the PySerial module with my own module and I can't get it to construct the PySerial object. No matter what I try, the constructor calls my class and not the PySerial one.
In file serial.py
import serial as pyserial
class Serial(Stream):
    """
    Class to represent a serial stream.
    """
    def __init__(self, **kwargs):
        super(Serial, self).__init__()
        if 'port' not in kwargs:
            raise Exception('Missing port parameter in serial constructor')
        self._conn = pyserial.Serial()

In main Python script:
try:
    conn = serial.Serial(port=PORT, baud=BAUD)

Error message:
C:\workspace> python test_serial_stream.py
F
======================================================================
FAIL: test_constructor (__main__.TestSerialStream)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_serial_stream.py", line 15, in test_constructor
    self.fail("Constructor crashed: "+ ex.message)
AssertionError: Constructor crashed: Missing port parameter in serial constructor

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

C:\workspace>

From the assertion message, we can see that it's crashing in the constructor. If I debug it, it jumps the if just fine, but then it calls the same constructor in the line after the exception. This time without args and it crashes.

A:

You is using a local file called serial.py that has the same name of the module of the serial library. When your script runs import serial as pyserial, actually, pyserial refers to your local file serial.py instead of the system library. The simpler solution is to rename your script from serial.py to myserial.py. In addition, be sure to remove any serial.pyc that may remain after the renaming operation.  

