[Tutor] Tutor Digest, Vol 82, Issue 45, Topic 3, Globals

echowit at aol.com echowit at aol.com
Sat Dec 11 07:38:38 CET 2010

-----Original Message-----
From: tutor-request <tutor-request at python.org>
To: tutor <tutor at python.org>
Sent: Fri, Dec 10, 2010 6:33 pm
Subject: Tutor Digest, Vol 82, Issue 45

Send Tutor mailing list submissions to
tutor at python.org
To subscribe or unsubscribe via the World Wide Web, visit
r, via email, send a message with subject or body 'help' to
tutor-request at python.org
You can reach the person managing the list at
tutor-owner at python.org
When replying, please edit your Subject line so it is more specific
han "Re: Contents of Tutor digest..."

oday's Topics:
   1. Re: role playing game - help needed (ALAN GAULD)
  2. Re: Writing to the terminal? (Alan Gauld)
  3. Re: Globals as variables in a tkinter widget (Alan Gauld)
  4. Re: the "**" operator? (Alex Hall)
  5. Code evaluation inside of string fails with __get_item
     (Tim Johnson)

Message: 1
ate: Fri, 10 Dec 2010 23:21:22 +0000 (GMT)
rom: ALAN GAULD <alan.gauld at btinternet.com>
o: Al Stern <albstern at gmail.com>
c: "tutor at python.org" <tutor at python.org>
ubject: Re: [Tutor] role playing game - help needed
essage-ID: <448643.14907.qm at web86708.mail.ird.yahoo.com>
ontent-Type: text/plain; charset="utf-8"

Thanks again Alan.  Much clearer now.  One final part I don't understand.
>>> "%d is the result of %d + %d" % (6+7,6,7)
I understand (I think) the 6+7 part but why the ,6,7 after that.  I could 
see how either '6+7' or '6,7' would be the correct format but not both.
The format string has 3 percent markers - all numbers.
t is therefore expecting 3 values, so I have to give it them.
he first marker gets 6+7, ie 13. The second gets 6 
he third 7...
Look at the first example in the loops topic in my tutorial.
t uses variables in the same way rather than literal values, 
hat might make it more obvious. Maybe :-)
Alan G.
------------- next part --------------
n HTML attachment was scrubbed...
RL: <http://mail.python.org/pipermail/tutor/attachments/20101210/a7647551/attachment-0001.html>
Message: 2
ate: Fri, 10 Dec 2010 23:42:56 -0000
rom: "Alan Gauld" <alan.gauld at btinternet.com>
o: tutor at python.org
ubject: Re: [Tutor] Writing to the terminal?
essage-ID: <idudu0$n0d$1 at dough.gmane.org>
ontent-Type: text/plain; format=flowed; charset="iso-8859-1";

Modulok" <modulok at gmail.com> wrote
> Assume I'm working in a command shell on a terminal. Something like
 tcsh on xterm, for example. I have a program which does *something*.
 Let's say it counts down from 10. How do I print a value, and then
 erase that value, replacing it with another value?
This is one of those things that sounds like it should be easy but is 
act deceptively difficult to get right!
It all  depends on your terminal, and there are dozens of different 
ypes and settings. Thats why Unix has a terminfo (or in some Unices
ermcap - even they can't agree! :-) library to define the different 
ypes and try to bring some sanity to proceedings.But you need to
earn the basic terminal control codes.
In this case you need the backspace code which is Ctrl-H or chr(8).
Try this
>>> print "spam" + "chr(8)*2+"ear"
If your terminal recognises chr(8) as backspace you should
ee "spear". If it doesn't you'll see someting like:
The only foolproof way to do this kind of thing is to use a library 
urses which allows you to positioon the cursor and overwrite whatever
as there. But curses is non-trivial to use - not ridiculously hard, 
on trivial.
You can get a basic intro to curses in the event-driven topic
f my tutorial.
BTW there is quite a good writeup on terminfo here:
nd, as usual, Wikipedia has a fair writeup.
lan Gauld
uthor of the Learn to Program web site

Message: 3
ate: Sat, 11 Dec 2010 00:06:19 -0000
rom: "Alan Gauld" <alan.gauld at btinternet.com>
o: tutor at python.org
ubject: Re: [Tutor] Globals as variables in a tkinter widget
essage-ID: <iduf9s$rt9$1 at dough.gmane.org>
ontent-Type: text/plain; format=flowed; charset="iso-8859-1";

echowit at aol.com> wrote
> This code produces a good run.
Not sure what you mean by that. What is "a good run"?
> from tkinter import *
 root = Tk()
 class Application(Frame):
     global sv, Ptype, PtypeI, sel_rate_label, label
This is bizarre.
lobals are generally considered evil and to be avoided if possible.
ne way to avoid globals is to use classes.
o why on earth are you trying to introduce globals ionto a class?
hat do you think you will achieve that using class variables can't?
>     label = Label(root)
     Ptype = 999
    PtypeI = IntVar()
    W = 5
     Y = 4
And in fact most of these should probably be instance
ariables defined within your init() method...

   def sel(self):
       global W
       global Y
       Ptype = PtypeI.get()
       if Ptype <= 333: print('\nResulting Values:', 
       else: print('Ptype Failure:',PtypeI.get())
       print('Ptype Completed',Ptype,'\n')
       V = 2
       X = 3
       Z = X * 2
       W = X + 6
       Y = V ** 2
       U = W * Y
       print("V: ",V," X: ",X," Z: ",Z," W: ",W," Y: ",Y," U: 
Mixing print statements and GUIS is valid for debugging,
ut these don't look like debnug statements... Are you sure
ou want these appearing in the console rather than the GUI?
    def __init__(self,master=None):
You might want to pass the master in to Frame too...
       sel_rate_label = Label(self)
       sel_rate_label.config(text = '\nSelect Goats Personality 
       MODES = [
           ("1 Below Average", 000), ("2 Average", 111),
           ("3 Above Average", 222), ("4 Super Star", 333),
       for text, mode in MODES:
           b = Radiobutton(self, text=text,
                       variable=PtypeI, value=mode, command = 
Why use the global label here when you use the instance
evel labels elsewhere? Especially as you don't appear to use it?
> Resulting Values: 333 333
 Ptype Completed 333
 Exception in Tkinter callback
 Traceback (most recent call last):
   File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
     return self.func(*args)
   File "C:\Larry\FCGCF\GPDB\Dev\EX_OK.py", line 18, in sel
     U = W * Y
 TypeError: can't multiply sequence by non-int of type 'str'
It seems to think that Y is a string.
our code suggests Y is V**2 or 4.
an you insertt a print statement just before the offending
ine to find out what W and Y are at that exact point?
> My goal is to I learnto use a global variable as an argument inside 
 a widget function,
Why do you think that will be useful?
hat do you think you can do with globals that you can't do with
lass or instance variables?
> My Question is: Anybody know of some good on-line documentation
 about using GUIs to do more than say 'Hello World'?
There are a lot of GUI tutorials, some even use Tkinter.
ven my tutorial includes the GUI in the case study and the event 
rogramming topics as well as the GUI topic itself. They don;t go far
eyond hello world but they do take at least one step further.
lan Gauld
uthor of the Learn to Program web site

hanks for the speedy and thorough response.
I'm brand new to Python and was trying old, lazy C+ tricks, I guess.
Am going to take your advice, try to do it right and see what happens.
'preciate the code examples and the link, checked it out & like its style, anyway.
Thanks again,
Message: 4
ate: Fri, 10 Dec 2010 19:26:52 -0500
rom: Alex Hall <mehgcap at gmail.com>
o: Hugo Arts <hugo.yoshi at gmail.com>
c: tutor at python.org
ubject: Re: [Tutor] the "**" operator?
<AANLkTinSxhkmL+yCAVKwBHz8doPaYqb9gq57JQLUo0Wd at mail.gmail.com>
ontent-Type: text/plain; charset=ISO-8859-1
Thanks all! I thought update() would add an item even if it would be a
uplicate, but apparently not. I also now better understand why I am
lways passing around *args and **kwargs when calling super(). Very
On 12/10/10, Hugo Arts <hugo.yoshi at gmail.com> wrote:
 On Fri, Dec 10, 2010 at 8:14 PM, Alex Hall <mehgcap at gmail.com> wrote:
> Hi all,
> I was googling a way to do something like
> mydict=mydict.extend(additionaldict)


 see also:

> and someone on a forum recommends this:
> mydict=dict(mydict, **additionaldict)
> What is the ** doing here? I tried to look it up, but Google seems to
> ignore it since it is punctuation. The poster on the forum says it
> will put all elements of additionaldict in mydict that are not already
> in mydict, which is the behavior I am looking for, but I am not sure
> why this would be so. TIA.

 The * and **, when calling functions, are what's called extended
 calling syntax. It's a bit hard to explain, so I'm going to do a sort
 of clarify by example here:

>>> def f(a, b, c):
 ...     print a, b, c
>>> f(1, 2, 3)
 1 2 3
>>> a = [1, 2, 3]
>>> f(*a)
 1 2 3
>>> b = {'a': 2, 'b': 1, 'c': 3}
>>> f(*b)
 a c b
>>> f(**b)
 2 1 3

 In short, if a = [1, 2, 3], f(*a) is the same as f(1, 2, 3). if b =
 {'a': 2, 'b': 1, 'c': 3}, then f(**b) is the same as f(a=2, b=1, c=3).

 The * will iterate over its argument, and supply the resulting values
 as arguments to the function (iterating over a dict will return its
 keys, which is what you see with f(*b) here). ** requires a mapping
 type, and supplies the keys and values to the function as keyword

 * and ** are very flexible, and you can use them alongside with
 regular arguments:

>>> f(1, *[2, 3])
 1 2 3
>>> f(1, **{'b': 2, 'c': 3})
 1 2 3

 * and ** also have uses in function definition, where they sort of do
 the reverse. They can capture any number of regular or keyword
 arguments in a tuple or dictionary:

>>> def f(*args, **kwargs):
 ...     print args, kwargs
>>> f()
 () {}
>>> f(1, 2, 3)
 (1, 2, 3) {}
>>> f(1, 2, 3, a=4, b=5)
 (1, 2, 3) {'a': 4, 'b': 5}
>>> f(a=4, b=5)
 () {'a': 4, 'b': 5}

 Like with function calls, you can mix up regular arguments and */**
 arguments, as long as the resulting function is unambiguous:

>>> def f(a, *args, **kwargs):
 ...     print a, args, kwargs
>>> f()
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: f() takes at least 1 argument (0 given)
>>> f(1)
 1 () {}
>>> f(1, 2, 3)
 1 (2, 3) {}
>>> f(1, 2, 3, b=4, c=5)
 1 (2, 3) {'c': 5, 'b': 4}

ave a great day,
lex (msg sent from GMail website)
ehgcap at gmail.com; http://www.facebook.com/mehgcap

Message: 5
ate: Fri, 10 Dec 2010 15:24:52 -0900
rom: Tim Johnson <tim at johnsons-web.com>
o: tutor at python.org
ubject: [Tutor] Code evaluation inside of string fails with
essage-ID: <20101211002452.GB3380 at johnsons-web.com>
ontent-Type: text/plain; charset=us-ascii
I'm using Python 2.6.5.
he following problem is coming from inside of a complex code base
nd involves an implementation that I have used for years, and is
ow failing to execute in certain conditions.
his problem occurs with either of the follow two classes, which are
lifted' from 'Python Cookbook'. Class code follows:
lass Eval:
   def __init__(self, globals=None, locals=None):
       self.globals = globals or {}
       self.locals = locals or None
    def __getitem__(self, key):
       if self.locals is None:
           self.locals = sys._getframe(1).f_locals
       key = key % self
       return eval(key, self.globals, self.locals)
# and this one:
lass Evalx: 
def __init__(self, localvals = None, globalvals = None):
	if localvals is None : 
		self.locals = sys._getframe(1).f_locals
	else : 
		self.locals = locals
	if globalvals is None : 
		self.globals = sys._getframe(1).f_globals
	else : 
		self.globals = globals
def __getitem__(self,key):
	return eval(key,self.globals,self.locals)
# either are used the same way: To evaluate code inside of a string
# A larger description can be found at:
# http://code.activestate.com/recipes/66018-evaluating-code-inside-strings/
he execution looks like this:
elf.content = formatted_string % Evalx()
# where 'self' refers to an object of another class, that uses the
# Eval class 
nder certain circumstances, the embedded is code *not* executed. 
y inserting debugging stubs, I can see that the the Eval/Evalx instantiation
oes occur, but the overloaded function call to __get_item does
not* occur. I have also found that a seemingly unrelated event having
o do with file I/O must be causing a side effect. However, to keep
hings simple, I am first asking the following question:
hat would cause __get_item__ not to be called? I can confirm by
ther testing that the embedded codde is properly composed with
atching keywords.
This is probably the most difficult to resolve problem I've ever run
nto in python. My lack of understand of the underlying code in the
val classes is probably a contributing factor. 
im at johnsons-web.com or akwebsoft.com

utor maillist  -  Tutor at python.org

nd of Tutor Digest, Vol 82, Issue 45

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101211/65da9ea8/attachment-0001.html>

More information about the Tutor mailing list