[Tutor] Global Variables

Luke Paireepinart rabidpoobear at gmail.com
Sat Nov 21 02:33:31 CET 2009


On Fri, Nov 20, 2009 at 4:44 PM, Joseph Fennell <josephfennellster at gmail.com
> wrote:

> My apologies yes these are in seperate files,
> --------------
> main.py
> ---------------
>  cHandler.execute("SELECT * FROM table")
>
> #sets results from above to nl
>
> nl = cHandler.fetchall()
>
> dn = raw_input("User input: ")
>
> nl2 = []
> ------------
> modules.py
> ----------
> dname()
> ########
> def dname():
>     global nl
>     for ndc in nl:
>         if ndc[1] == dn:
>             nl2.append(ndc,)
>         else:
>             continue
> #########
> ------------
> main.py
> ------------
> tuple(nl2) = nl2
>

Just FYI, this line does nothing.
In fact I think that it is invalid syntax.
What you probably mean to say is
nl2 = tuple(nl2)

I.E. turn nl2 into a tuple and assign it back to nl2.

>
> ----------------
> modules.py
> ----------------
> qtysrch()
> #########
> def qtysrch():
>     global nl2
>     for ndc in nl2:
>         if ndc[7] == 0:
>             continue
>         else:
>             print ndc
>
> and the major problem I'm having is in both modules when the code is ran,
> an error is returned when it attempts to pass 'dname()' that 'nl' is not
> defined.
>
>
Yes, that is because this is not how you are supposed to code in Python.

In general, using global variables should be avoided.  There are specific
cases where it's acceptable, but you should assume your case is not one of
them.

You should read through a tutorial such as Alan Gauld's tutorial, so you can
understand the 'functionality' of functions (pardon the pun.)

Essentially, what you're doing now is using functions to modify variables
DIRECTLY.  What you need to to is use functions  that take in a value or
values, and output a value or values, but do not modify variables in the
global scope.  Also, if a function prints anything or modifies any outside
sources, it should not have a return value.  For example, list.sort()
returns None because it sorts the list in-place.  However, list.split()
returns the splitted list, and does not modify the original.

You should try to come up with more descriptive variable names.  It should
be clear to me what your code does even though I have never seen it before.
What do 'nl' and 'ndc' and 'nl2' refer to?  I've changed your variable names
to more descriptive versions, but it may not be completely accurate as I'm
not sure of your code intent.

Here's a cheat sheet of how you should rewrite these functions (also take
note of the way I modified your 'if' statements.  Your 'continue' branches
are not necessary):

------------------
order.py
------------------
def display_qtys(order):
    for lineitem in order:
        if lineitem[7] != 0: #check for a nonzero quantity
            print lineitem

def search(order, query):
    results = []
    for lineitem in order:
        if lineitem [1] == query:
            results.append(lineitem)
    return results
------------------

Note that I personally would actually write the search function like this:
------------------
def search(order, query):
    return [lineitem for lineitem in order if lineitem[1] == query]
------------------

List comprehensions can be a bit scary when you're first starting out.  Once
you get used to them, you really start to like them though.

Then your main program will look like this:

-------------------
main.py
------------------
import order
# some import for the cHandler routine, wherever that comes from...

cHandler.execute("SELECT * FROM table")
results = cHandler.fetchall()

query = raw_input("Please enter item to search for: ")
filtered_results = order.search(results, query)

#display the results
order.display_qtys(filtered_results)
------------------


I strongly recommend reading more tutorials about proper function
definition, in the long run (and whenever you have a large scale project to
work on, or even a medium-scale one, at that) handling values between
functions in global variables is going to soon become a huge headache.

Hope that helps, and let me know if anything is unclear!
-Luke


P.S. please use the REPLY-ALL because when you use regular reply it does not
send to the list as well, it just sends it directly to me.

Sorry I can't be more specific with the exact error returned as I'm not near
> a machine that I have python on.
>
>
> Thanks.
>
>
>
> On Fri, Nov 20, 2009 at 3:52 PM, Luke Paireepinart <rabidpoobear at gmail.com
> > wrote:
>
>>
>>
>>  On Fri, Nov 20, 2009 at 2:51 PM, Joseph Fennell <
>> josephfennellster at gmail.com> wrote:
>>
>>> Quick introduction,  I'm Joseph Fennell, and I've been playing with
>>> python for the past 6 years (primarily in the interpreter) and have finally
>>> gotten started on a full project and I've run into a small problem.  I have
>>> defined some modules, and when I import them into the page I want to use
>>> them on after I run the program it tells me the variable I'm trying to pass
>>> through them is not defined.
>>>
>>> I assume that it's because the variable is considered local and the
>>> imported functions are not technically local to that document.
>>>
>>> The code is to pass the contents of a database through to filter by name
>>> and quantity and as follows
>>>
>>
>> The example code you provided is very confusing.
>>
>>>
>>> =================================================
>>>
>>> cHandler.execute("SELECT * FROM table")
>>>
>>> #sets results from above to nl
>>>
>>> nl = cHandler.fetchall()
>>>
>>> dn = raw_input("User input: ")
>>>
>>> nl2 = []
>>>
>>> dname()
>>> ########
>>> def dname():
>>>     global nl
>>>     for ndc in nl:
>>>         if ndc[1] == dn:
>>>             nl2.append(ndc,)
>>>         else:
>>>             continue
>>> #########
>>> tuple(nl2) = nl2
>>>
>>> qtysrch()
>>> #########
>>> def qtysrch():
>>>     global nl2
>>>     for ndc in nl2:
>>>         if ndc[7] == 0:
>>>             continue
>>>         else:
>>>             print ndc
>>>
>>
>> Are you saying these are in separate files?
>>
>> Please repost the code in a more logical fashion.  Eg.
>>
>> -------------------------------
>> ~~~ somemodule.py
>> -------------------------------
>> def foobar():
>>     print "foobar!"
>>
>> -------------------------------
>> ~~~ main.py
>> -------------------------------
>>
>> import somemodule
>> somemodule.foobar()
>> -------------------------------
>>
>>
>> This will make it much easier to understand your question, because I don't
>> see how the code sample you provided applies to your question whatsoever.
>> Also, if you have a lot of code post it on pastebin (I wouldn't consider
>> this a lot of code).  Just for future reference.
>> -Luke
>>
>
>
>
> --
> "I swear - by my life and my love of it - that I will not live my life for
> another man, nor ask another man to live for mine."
> - John Galt (Anti-hero from Ayn Rand's Atlas Shrugged)
> <br>
> <a href="http://playogg.org"><img src "
> http://www.fsf.org/resources/formats/playogg/ogg_data/play_ogg_medium
> "></a>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091120/ad49ca1a/attachment-0001.htm>


More information about the Tutor mailing list