Reputation: 73
I have been following along the "black hat python" book and when I typed in this particular code I got the error "global name server_loop() is not defined". Here is the statement BEFORE the main() function having the error:
if listen:
server_loop()
and here is the server_loop() function IN the main() function:
def server_loop():
global target
# if no target is defined, we listen on all interfaces
if (not len(target)):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
Thanks
Upvotes: 0
Views: 985
Reputation: 11
I also read this book, please arrange the function server_loop
before the call of main()
function.
Upvotes: 1
Reputation: 140286
I hope I understand the question correctly.
I can reproduce your case easily:
something()
def something():
pass
I get
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "<module1>", line 1, in <module>
NameError: name 'something' is not defined
If I call something
after having defined it it works.
You have to define functions before using them.
I suppose that your book just gave the information in the inverted order (top => down, from global/main to implementation/function) expecting that you knew that as a lot of languages, python requires function definition before function call. Personally I prefer single-block examples that you can type (or copy/paste) without thinking and it works right away.
Upvotes: 1