Dictionary returns different values when accessed from different functions

MINIMAL EXAMPLE

Put a print inside the get_tuple_space function:

def get_tuple_space():
    global tuple_space
    print("VALUE INSIDE GETTER")
    print(tuple_space)
    return tuple_space

When I call this function inside the file server.py where the tuple_space is declared an it's defined I get the expected result, that is the tuple_space filled with some elements.

while True:
        # Get the list sockets which are ready to be read through select
        readable,writable,exceptional = select.select(connected_list,[],[])

        for sock in readable:
            #New connection
            if sock == server_socket:
                connect()

            #Some incoming message from a client
            else:
                handle_incoming_msg(sock)
                print("Trying to get tuple space inside server")
                print(get_tuple_space())

However, trying to call this function in my client.py as following gives me and empty dictionary:

import socket, select, string, sys
import server

#some code
#...
#...

while True:
        socket_list = [sys.stdin, client_socket]

        # Get the list of sockets which are readable
        rList, wList, error_list = select.select(socket_list , [], [])

        for sock in rList:
            #user entered a message
            msg=sys.stdin.readline()
            linda.blog_out(my_name, my_topic, msg, client_socket)

            #HERE
            print("trying to get tuple space inside client")
            print(server.get_tuple_space())

            #reads from topic
            messages = linda.blog_rd(my_topic)
            print messages

END OF MINIMAL EXAMPLE

UPDATE

Added "global tuple_space" in the functions that uses this dictionary. Also, I tried to call get_tuple_space inside my server code and it returned a correct value. Looks like the problem occurs when I call the function from another code.

END OF UPDATE

I'm having a probably very beginer problem with Python. I'm trying to do some code using sockets and dictionaries but strangely to me my dict returns filled in some functions and empty in another functions. I've made him global, so I was expecting it to returns filled in all my functions.

I believe I'm missing some information about python scope or something. It seems that everything related to the sockets are working fine.

Firstly, my dictionary is initialized in the server.py as following

tuple_space={}

After that, for example, the first function connects the client to the server socket and receives a message containing it's name, topic of interest and message written. Then, my program updates de tuple_space dictionary with some information. The second function does a very similar thing, updating the tuple_space dictionary with new messages from that client about that topic.

Both returns the most updated version of my dictionary and are running in my server code.

def connect():

    sockfd, addr = server_socket.accept()

    data =str(sockfd.recv(buffer))
    name, topic, msg = data.split("@")

    connected_list.append(sockfd)
    tuple_space[(name, topic)]=""

    #add name and address
    registered_names.append(name)

    tuple_space[(name,topic)] = msg


def handle_incoming_msg(sock):
    # Data from client
    data = sock.recv(buffer)

    name, topic, msg = data.split("@")

    tuple_space[(name, topic)] = msg

    print(tuple_space)

Both functions are used in my main inside server.py. The first one when a new client connects and sends his name, topic and message, the second one when a connect client sends something:

def main():
    server_socket.bind((host, port))
    server_socket.listen(10) #listen atmost 10 connection at one time

    # Add server socket to the list of readable connections
    connected_list.append(server_socket)
    print("Servidor inicializado\n")

    while True:
        # Get the list sockets which are ready to be read through select
        readable,writable,exceptional = select.select(connected_list,[],[])

        for sock in readable:
            #New connection
            if sock == server_socket:
                connect()

            #Some incoming message from a client
            else:
                handle_incoming_msg(sock)

    server_socket.close()

After that, I want to receive the last messages, stored in tuple_space, in my client.py code. Here is what I'm doing inside a loop in my client:

messages_list = linda.blog_rd(my_topic)
            if len(messages_list)>0:
                print(messages_list)

The blog_rd function is the following, defined in my class "Linda"

def blog_rd(self, topic):

        incoming_messages = []

        registered_names = get_registered_names()
        tuple_space = get_tuple_space()

        for i in range(len(registered_names)):
            name = registered_names[i]
            print(name)
            incoming_messages.append((name, tuple_space[(name,topic)]))

        return incoming_messages

It was suposed to get the registered names and get the messagens stored in tuple_space, that call the get_tuple_space function.

The problem starts here:

def get_tuple_space():
    print(tuple_space)
    return tuple_space

When I call this function, the tuple_space dictionary, that is global, returns empty. It also happens with the registered_names list. I'm created that post about the dictionary to simplify my explanation, as the error in registered_names is the same as in tuple_space.

In my project, this function is called on another code file, acessed via import of the server.py. But what is confusing me is that even in the print the tuple_space is empty.

I was expecting that it would print all the values stored, as It does in the previous two functions.

What am I doing wrong?

Upvotes: 1

Views: 96

Answers (2)

thanks for everyone who tried to help.

As I said, I was having some trouble giving a minimal example as in my minimal example without sockets it worked with your suggestions, but didn't worked in the real project.

What I did to solve was to change how I represent tuple_space. I made it a Class with the needed attributes, that before was into a dictionary. So the server.py uses the object and handles it depending on the messages sended from the server.

Not sure what was hapenning before, but I'm glad I solved the problem somehow.

Thanks!

Upvotes: 0

gaFF
gaFF

Reputation: 757

As far as I understand, tuple_space is declared in a file, and used in one or several others. But all variable in Python are enclosed in the namespace of their module (the file where it is created). So if tuple_space is declared in server.py, you have to import it in another file with from server import tuple_space.

Upvotes: 1

Related Questions