derived class from socket

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
chastings
Posts: 1
Joined: Sun Apr 28, 2019 5:08 pm

derived class from socket

Post by chastings » Sun Apr 28, 2019 5:16 pm

It seems I can't derive from socket, and I can't figure out why.

First, a simple inheritance example with my own classes in micropython as a sanity check:

>>> class base:
... def foo(self):
... print( "foo" )
...
>>> class derived(base):
... pass
...
>>> d=derived()
>>> d
<derived object at 3fff1c90>
>>> d.foo()
foo

Now, the same example with socket...

>>> import socket
>>> class dsocket(socket.socket):
... pass
...
>>> d=dsocket()
>>> d
<socket state=0 timeout=-1 incoming=0 off=0>
>>> s=socket.socket()
>>> s
<socket state=0 timeout=-1 incoming=0 off=0>

The derived object seems to have the same type as an object of the base class, which is unexpected.

Anyone know what's going on here? Happens in both releases 1.9.4 and 1.10. Thanks!

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: derived class from socket

Post by kevinkk525 » Mon Apr 29, 2019 5:52 am

Subclassing built-ins can sometimes work - but it's best avoided as behaviour is not guaranteed.
Doesn't work for machine.Pin either.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: derived class from socket

Post by pythoncoder » Mon Apr 29, 2019 6:28 am

It's worth reading this doc which explains the differences between MicroPython and CPython.

The problem with subclassing buiiltins can usually be worked around by using composition rather than inheritance.
Peter Hinch
Index to my micropython libraries.

Post Reply