Python: smart coding with locals() and global()
Coding can be hard! and one of the most common reasons for that is that we tend to solve a coding problem thinking complex ways which can…
Coding can be hard! and one of the most common reasons for that is that we tend to solve a coding problem thinking complex ways which can create more problems than solutions.
Lets try to break down the following coding problem:
- The first server in servers list is a proxy server, so it needs to use the connect_to_proxy function.
- All other server are just servers that we want to connect and get to the next server, so they need to use the hop_to_server function.def connect_servers():
'''
Connect servers
'''
for server in servers:
if not "server_conn" in locals():
server_conn = connect_to_proxy(server=server)
else:
server_conn = hop_to_server(server=server)
locals() returns the variables / objects declared in the scope a function. So in this case the code will do the following:
- The first time that will run it will check if the “server_conn” variable has been created or not. Since this is the first time running the connect_to_proxy function will be executed and will return its value to the server_conn variable.
- After the first run of the loop the hop_to_server function will be executed untill the end of the loop.
But what about the globals() function? well it does the same thing, checks if a variable exists but not only in the scope of a function but globaly.
So using the locals() and globals() functions allows writing smart shortcuts, which in turn means less things that can go wrong and makes the code more readable.
Doing the same without using the locals() function:def connect_servers():
'''
Connect servers
'''
first_run = True
for server in servers:
if first_run == True:
server_conn = connect_to_proxy(server=server)
first_run = False
else:
server_conn = hop_to_server(server=server)
It will work, but the code has more lines and is not as readable as the first example.