1
def func(bar):

    my_dict = {  
        'query1': 'select * from table1',  
        'query2': 'select * from table2'  
    }
    my_dict[bar]

func('query1')    

My question is does my_dict executes both query and save it or it only executes query according to bar variable

1
  • What do you mean by "executed"? With your code, the only thing that could happen is that you could be referencing a value of my_dict if bar is one of the keys of the same dictionary... Commented Aug 19, 2016 at 21:56

2 Answers 2

2

In this specific case, no query are executed at all. It is only str objects which means that they actually don't do anything.

Let's try to detail 2 other cases. Assuming you have a function execute_query that execute a query given as parameter:

def func(query):
    my_dict = {
        'query1': execute_query('select * from table1'),
        'query2': execute_query('select * from table2'),
    }
    return my_dict[query]

func('query1')

In this case, both query will be executed because Python interpreter will analyse the dictionary composition. On the other hand, if you have a reference to this function, it won't call the function. Example:

def do_query1():
    return execute_query('select * from table1')

def do_query2():
    return execute_query('select * from table2')

def func(query):
    my_dict = {
        'query1': do_query1,
        'query2': do_query2,
    }
    return my_dict[query]() # <-- appropriate function will be call here

func('query1')
Sign up to request clarification or add additional context in comments.

2 Comments

Good for you for figuring out what he's really asking about.
thanks man for the explanation. Actually i misunderstood the sql and string to same thing. I was using psycopg2 for database and there are different queries according to parameter passed. What i misunderstood is that when i write the sql string in python dict it will execute it but this is not the case and it will only execute when i pass it to psycopg2. The dict will be the string not the sql query.
0

That will create the dictionary with two elements in memory, find the value associated with key bar and destroy the whole thing when the function is competed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.