[Tutor] Socket error in class

Mats Wichmann mats at wichmann.us
Mon Mar 6 16:36:09 EST 2017

On 03/06/2017 10:35 AM, leam hall wrote:
> What am I missing?
> ####
> class mysocket():
>   import socket
>   def __init__(self, sock=None);
>     if sock is None:
>       self.sock = socket.socket(socket.socket.AF_NET,
> socket.socket.SOCK_STREAM)
>     else:
>       self.sock = sock
> ####
> Error:
> NameError: global name "socket" is not defined.

The Python style guide, "PEP8", says this:

    Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.

an import statement creates a module object (if it hasn't been
previously imported, that is), and then executes it, leaving the name
you imported it as bound to the module object. That means when you do
what you did above, "socket" is a name inside the "mysocket" scope, and
it's no different than if you defined a class variable - you need to
qualify it to access it, it should be available as as self.socket inside
a method or as mysocket.socket.  But it seems better to do the import at
the top instead, then it really looks like a global and there won't be a

Note also in your code (I'm assuming you typed stuff, and did not paste
directly from the code you were trying):

- your __init__ definition ends with semicolon, not colon
- it's AF_INET, not AF_NET
- you've doubled "socket" in referring to constants AF_INET and SOCK_STREAM

More information about the Tutor mailing list