[Tutor] Socket error in class

Steven D'Aprano steve at pearwood.info
Mon Mar 6 19:39:10 EST 2017

On Mon, Mar 06, 2017 at 12:35:27PM -0500, leam hall wrote:

> What am I missing?

Let us start by reading the exception that you get, below the class. 
That tells us *what* error occurred, but not how or why:

> 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.

It not a *socket* error at all, it is a regular NameError, the same sort 
of error that you get if you write:

x = 1
print(y)  # oops I meant x

You haven't shown the context for how you get that exception, so I have 
to guess. You should always show the entire traceback, not just the 
final line, and you should show the actual line of code that you ran 
that failed. My GUESS is that you tried to create a mysocket object:

mysock = mysocket()

and that's when you got the NameError. Or maybe you did something like 

mysock = socket.socket(socket.socket.AF_NET, socket.socket.SOCK_STREAM)

and the entire "mysocket" class is irrelevant. You don't give us enough 
information to tell what you actually did.

Either way, the solution is the same: read the exception. It is 
NameError, so the problem is that Python cannot see the global variable 
called "socket". Why not?

Well, consider this bit of code:

class Foo:
    x = 1

# outside of the class

What would you expect that code to do? Hopefully you expect a NameError: 
there's no global variable called "x". Setting x inside the class 
creates a "class variable" (or class attribute, the preferred term to 
use in Python). You would have to use Foo.x to reference it, not just x.

Imports are no different! In your class, you have:

class MySocket:
    import socket

but that doesn't create a global variable "socket", it creates a class 
attribute MySocket.socket. So the fix should be very simple: move the 
import out of the class and into the top-level, global part of your 

import socket

class MySocket:

That may or may not solve the problem, since I'm only guessing where you 
get the actual error. If this doesn't solve it, then please write back 
with the full traceback, not just the final line.


More information about the Tutor mailing list