Python Forum
How to use a returned value?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use a returned value?
#1
Hi everybody,
I'm working on a program that involves querying a database with pyodbc and working with the results. below you will see my program, and the function I'm working with here. The end goal is to be able to work with the returned variables to be able to import/pass them along to another python program.

As you can see, the function works to connect to a database, run a query, and stores the query results in a dictionary. After that, I assign the specific dictionary keys to variables and "return" them at the end of the function. As noted above, I need to be able to import these variables (msg, destPhone, caseNum, timeStamp, sender) from another program... however when I try to print one of them (to test), I don't get any result.

Forgive me for the noobish question, but I'm new to python.. and new around here.
Thank you for your time!

def pullData():
    cnxn = pyodbc.connect('UID='+dbUser+';PWD='+dbPassword+';DSN='+dbHost)
    cursor = cnxn.cursor()

    outbound = cursor.execute("SELECT * FROM WKM_SMS_outbound ORDER BY id DESC")
    results = cursor.fetchone()
    collection = {}
    for index, outbound in enumerate(results):
        key_name = "col{0}".format(index)
        collection[key_name] = outbound

    msg = collection['col1']
    destPhone = collection['col2']
    caseNum = collection['col4']
    timeStamp = collection['col8']
    sender = collection['col10']

    cnxn.close()

    return (msg, destPhone, caseNum, timeStamp, sender)

pullData()
print(msg)
Reply
#2
try this:
msg, destPhone, caseNum, timeStamp, sender= pullData()
print(msg)
Reply
#3
Think about what you're doing: on line 22, you call the function and don't do anything with its return value, so it's just thrown away. Either assign it to a variable and then use that variable (which you already know how to do, e.g. lines 2 or 3) or use the value directly in an expression as shown above (though you already seem to know how to do that too: it's exactly what you're doing with the call to enumerate on line 8).

On line 23, you try to print the value of msg, but the variable doesn't exist outside of the scope of the pullData function. Perhaps you need to revise the concept of scope?
Reply
#4
Very easy trick, but in the most cases it's True.

def foo():
    name = 'Foo'
    return name
Everything, which is indented, is not accessible from outside.
This is True for functions, which don't use global variables.
Returning something from a function, requires that the caller assign the result.
But the caller can't see from outside, whats happening inside the function.
It's a kind of black box for the caller. You call it with something and then you get something back.

# I'm the caller
my_result = foo()
First the interpreter searches for the name foo (it could be everything).
Then the interpreter calls the object, which is referenced by foo. The function foo is executed and return the result.
On the caller side, the return value is assigned to the name result.
A = sign means always assignment to a name. (I don't like to use the term variable for it).


Edit:

If you see something like this:
a, b, c, d = some_function()
Then there is a step before assignment.
In this case the programmer expect 4 return values (objects).
If there is one name to less or too much, it won't work.
This technique is called Iterable Unpacking.
In addition, there is a Extended Iterable Unpacking.
I can't find the old pep.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(Jan-15-2020, 09:22 AM)DeaD_EyE Wrote: A = sign means always assignment to a name. (I don't like to use the term variable for it).

I have the same sentiment.

Python documentation Assignment statement calls it "name is bound to the object":

Output:
Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
thank you everybody for your input and thoughts.

Would somebody be kind enough to explain why this works?

msg, destPhone, caseNum, timeStamp, sender = pullData()
print(msg)
print(destPhone)
print(caseNum)
print(timeStamp)
print(sender)
I don't understand what's going on here... what's happening when declaring the returned values back to the funtion itself? Huh

I'm a sys admin rather than a software guy by trade, I've mostly just fallen into a programming role to meet the needs that my employer decides they want... so a lot of these things don't inherently make sense to me... still learning.
Thanks again!
Reply
#7
(Jan-15-2020, 02:14 PM)t4keheart Wrote: when declaring the returned values back to the funtion itself
not sure what you mean by this

on the RHS is the function call and the function returns tuple with 5 values
on the LHS are 5 names and you unpack the tuple into these (i.e. assign each element from tuple returned by the function to individual name)

probably confusion comes because the names used within the function scope (i.e. the local scope) are same as the names in global scope. However these are names with different scopes
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
(Jan-15-2020, 02:14 PM)t4keheart Wrote: Would somebody be kind enough to explain why this works?
I don't understand what's going on here...

This is called sequence unpacking (look for explanation at the end of chapter Tuples and Sequences

>>> first, second, third = ('spam', 'ham', 'eggs')                                                                                         
>>> first                                                                                                                                  
'spam'
>>> second                                                                                                                                 
'ham'
>>> third                                                                                                                                  
'eggs'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
I appreciate the input and clarification.

Believe it or not, I'm working on a program to integrate our case management system (law firm) and web sms messaging platform api, and allow for lawyers to text clients via posting messages in the CMS... and thanks to you guys I have just about half of that working (the sending side).

Never in a million years did I think I would be able to pull this one off lol. Wall

Thanks again. Cool
Reply
#10
In python you can declare objects on the fly, I used the same assignment names as you did to make a point, but it could be anything that's clear to you or someone else reading your code example:
a,b,c,d,e= pullData()
print(a)#printing your message
or
message, destPhoneNumber, caseNumber, time_Stamp, client= pullData()
print(message)
the others do a great job of showing you examples re read and run their code in an interactive prompt, play with it.
clear as mud?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to access values returned from inquirer cspower 6 695 Dec-26-2023, 09:34 PM
Last Post: cspower
  SQLAlchemy Object Missing when Null is returned Personne 1 1,676 Feb-19-2022, 02:50 AM
Last Post: Larz60+
  Getting "name 'get_weather' is not defined error and no json_data returned? trthskr4 6 3,528 Sep-14-2021, 09:55 AM
Last Post: trthskr4
  Libraries installed with pipenv, but ModuleNotFoundError returned jpncsu 2 2,946 Sep-06-2021, 07:24 PM
Last Post: jpncsu
  Exception: Returned Type Mismatch Error devansing 1 5,088 Mar-06-2020, 07:26 PM
Last Post: ndc85430
  Strange Characters in JSON returned string fioranosnake 4 5,117 Dec-02-2019, 07:25 PM
Last Post: fioranosnake
  Not all data returned from sys.argv ecdhyne 2 2,723 Sep-05-2019, 08:27 PM
Last Post: buran
  I always get 'None' returned. Confused. What did I miss? jpezz 2 2,346 Apr-07-2019, 10:06 AM
Last Post: jpezz
  How to resolve 404 returned from web method when not running on localhost littleGreenDude 3 3,024 Feb-05-2019, 09:01 PM
Last Post: littleGreenDude
  TypeError: __str__ returned non-string error jolinchewjb 5 9,959 Jan-24-2019, 07:54 AM
Last Post: jolinchewjb

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020