[FAQTS] Python Knowledge Base Update -- June 20th, 2000

Fiona Czuczman fiona at sitegnome.com
Tue Jun 20 08:53:42 EDT 2000


Hi guys,

Below are the latest entries into http://python.faqts.com

cheers,

Fiona Czuczman


## New Entries #################################################


-------------------------------------------------------------
Is getstatusoutput() the prefered method to run os commands from within a python script or is there something more generic?
http://www.faqts.com/knowledge-base/view.phtml/aid/3850
-------------------------------------------------------------
Fiona Czuczman
Matthew Schinckel

Try using os.system(command)


-------------------------------------------------------------
How can I find out how much memory a remote computer has installed? The computers are on the same NT network and have the same login.
http://www.faqts.com/knowledge-base/view.phtml/aid/3866
-------------------------------------------------------------
Fiona Czuczman
Roger Upole

Try the win32pdh module from the win32 extensions.  The NT performance
monitor can access memory stats on another machine if you have 
sufficient privilege.  The hard part is getting the path string right, 
but there is a path browser to help with that.  I think it's 
win32/lib/win32pdhutil.py.


-------------------------------------------------------------
How do I create a fully stand alone programme to put on systems where python is not installed?
http://www.faqts.com/knowledge-base/view.phtml/aid/3868
-------------------------------------------------------------
Fiona Czuczman
Matthias Huening, Matthew Schinckel

You should try Gordon McMillan's "Installer". It's at:
http://starship.python.net/crew/gmcm/distribute.html

One option is to use mxCGIPython (can't remember the URL, find it on
Parnassus <http://www.vex.net/parnassus>, and just have a compiled
single-file binary and the program.


-------------------------------------------------------------
I'm trying to get a user's username and password but by using raw_input() the password is echoed to the screen.  How can I make it so that their password isn't shown?
http://www.faqts.com/knowledge-base/view.phtml/aid/3869
-------------------------------------------------------------
Fiona Czuczman
Janko Hauser, David Goodger

Look for the module getpass in the library reference. It also supports
windows according to the document string.

    import getpass
    password = getpass.getpass()

If you still see the password echoed to the screen, then you're missing 
some functionality, probably termios. Check out the getpass.py code for 
the decision tree that is followed.


-------------------------------------------------------------
Could someone give me a simple explanation of regular expressions?
http://www.faqts.com/knowledge-base/view.phtml/aid/3870
-------------------------------------------------------------
Fiona Czuczman
Andrew Kuchling

Regular expressions are a mini-language for defining a certain set 
of strings; the re module then takes a regular expression and tells you
if a given string matches the expression.  For example, [abc] means
'a', 'b', or 'c'; \bA.*?\b means a word beginning with 'A' (\b is a
special sequence meaning "match a word boundary").  As you can see,
regular expressions are concise but can easily be obscure.

Regular expressions will practically never be faster than a simple
string.find, so if you're searching for a fixed string, don't use
regular expressions; their extra expressive power costs you in
performance.  But they can do things that aren't possible with the
string module alone, and would require several lines of Python code 
to implement.

Consult the Library Reference, or the Regular Expression HOWTO for
more info.  (http://www.python.org/doc/current/lib/module-re.html,
http://www.python.org/doc/howto/regex/)


-------------------------------------------------------------
Can two threads get in each others' way if they simultaneously try to mutate a list?
Can two threads get in each others' way if they simultaneously try to mutate a list?
http://www.faqts.com/knowledge-base/view.phtml/aid/3831
-------------------------------------------------------------
Fiona Czuczman
Aahz Maruch

It depends how they mutate it.  I believe that single builtin functions
(e.g. [].append()) are thread-safe.  OTOH, [].sort() may not be
thread-safe, particularly if you've got user-defined classes on the list
with __cmp__() defined.


-------------------------------------------------------------
When and why should I use Intvar() etc?
When and how do I use the textvariable option?
http://www.faqts.com/knowledge-base/view.phtml/aid/3867
-------------------------------------------------------------
Fiona Czuczman
richard_chamberlain

from Tkinter import *
root=Tk()
myIntVar = IntVar()
myStringVar= StringVar()
Label(root,textvariable=myStringVar).pack(side=TOP)
def setLabel():
    myStringVar.set(myIntVar.get())
Radiobutton(root,text="First Radiobutton",variable=myIntVar,value=1,
                    command=setLabel).pack(side=LEFT)
Radiobutton(root,text="Second Radiobutton",variable=myIntVar,value=2,
                    command=setLabel).pack(side=LEFT)
root.mainloop()

I'm using both IntVar and textvariable in this example.

I create new instances of Intvar and StringVar. I then create a label 
and assign the textvariable option to the instance of StringVar. I can 
now set the text of this label by called myStringVar.set('Hello') or get 
the text by myStringVar.get().

Next I've created two Radiobuttons and assigned their variable options 
to the instance of IntVar. I give them two separate values. Any changes 
to the radiobuttons will now be reflected in myIntVar.

I created a function called setLabel which uses the set and get methods 
of the instances. I then assign it to the label by called 
myStringVar.set(myIntVar.get()) which changes the value of the 
textvariable and the change is immediately reflected on the label.


## Edited Entries ##############################################


-------------------------------------------------------------
How can I extract all the keys in a formatting string to a list?
How can I extract all the keys in a formatting string to a list?
http://www.faqts.com/knowledge-base/view.phtml/aid/1505
-------------------------------------------------------------
Nathan Wallace, Fiona Czuczman
Michael Ströder, Johannes Stezenbach

For example, go from:

  '%(language)s has %(count)03d quote types.' % vars()

to get:

  ['language','count']

Try something like this:

------------
class GrabKeys:
    def __init__(self):
        self.keys = []
    def __getitem__(self, name):
        self.keys.append(name)
        return 0 # 0 is apparently compatible with all % format
characters

gk = GrabKeys()

'%(language)s has %(count)03d quote types.' % gk

print gk.keys
------------


-------------------------------------------------------------
Are colons unnecessary in my Python code?
http://www.faqts.com/knowledge-base/view.phtml/aid/2910
-------------------------------------------------------------
Fiona Czuczman
Courageous, David Porter, François Pinard, Moshe Zadka, Dirck Blaskey

Lead in discussion:

Sometimes colons seem syntactically unnecessary. For example:

        if <condition>:
                statement
        else:
                statement

Really, else doesn't need a colon, as far as I can tell (I can see the 
need for the if, supposing you want to have the statement on the same 
line).

Answer(s):

- When using python-mode in Emacs (or jed), the colon facilitates
auto-indention. Also, if you forget the colon, the next line will not be
indented, so you will catch your mistake. 

- Granted, but it is always good for a language to have a bit of 
redundant information.  When properly thought, such redundancy prevents 
various mistakes from programmers (once they are used to it, of course 
:-), and often increase overall legibility.

- Theoretically, a colon is only necessary in things like

if yes: print "yes"

Since otherwise the parser can figure out when to stick a colon. 
However, usability studies show people are more comfortable when the 
beginning of a block is signaled, and I can see why:

if yes
        print "yes"

Seems....naked. Much less readable then 

if yes:
        print "yes"

Guido didn't want 10 ways (or even 2) to spell things, so the colon is
mandated for all.

- > if yes: print "yes"

Oddly enough, the parser doesn't really need the colon here either.
It can manage to figure out where the if expression ends without it.

The colon is almost entirely for readability purposes.
(there are a couple of places where ambiguity occurs without it).

If you're curious about the other thread,
or about Python without colons,
or to test my above assertion,
check out:

http://www.danbala.com/python/colopt


-------------------------------------------------------------
What is a tuple and why is it used (as opposed to an array, etc)?
http://www.faqts.com/knowledge-base/view.phtml/aid/3795
-------------------------------------------------------------
Fiona Czuczman
Stephen Hansen, Aahz Maruch, Warren Postma,Russell E Owen

A Tuple is of a fixed length, the length it was when it was created. A
list is of a dynamic length -- its actual size, I believe, from a 
memory-ish standpoint, that lists are actually larger then they appear 
to be in the Python environment. On the C level, my understanding from 
reading various posts is that the list allocates additinoal memory for 
elements which may be added in later, so that it doesn't have to 
allocate One Piece Of Memory every time an element is added. A Tuple is 
immutable. Once created, with its given values, it can not be changed. a 
= (1,2,3) can not have a[1] = 5 done. A list is mutable. You can change 
the individual elements at any time.

My unknowing guess? The overhead to create the truly 'dynamic' lists is 
completely wasted in enough circumstances that it warrented making an 
array which was fixed, in both size, and content.

----------

>From my POV, the primary purpose of tuples is for dictionaries: they
allow you to do things like

foo = {}
foo[(1,2)] = 3

This essentially permits the use of multi-column primary keys (to use
database terminology).  In addition, as Stephen Hansen pointed out,
tuples are a fair bit more efficient than lists.

---------

I first came across the term tuple in relation to Relational Algebra and 
in particular, in the realm of SQL and Databases.

A row of data in a database is often called a tuple. Really, it's a way 
of creating a Structure like you would do in C, very efficiently, which 
once created, is immutable. This means you can create a hash on it, and 
then use the hash to get the piece of data out of a database table. This 
is exactly how Tuples work, and they are hashed and then placed into an 
associative array (Python calls associative arrays Dictionaries).

So whereas there is one native Array type in C, the List type in Python 
is a mutable dynamically sized array, and a Tuple is a fixed immutable 
grouping of items, and a Dictionary is like an array where the key 
doesn't have to be a number.  So, three kinds of things which have 
something in common with a C array is better than just having a return 
to the Bad Old Days where C arrays were fixed in size, mutable to the 
point that you could easily crash your system, and totally 
non-polymorphic.

-----------

Tuples are immutable only at the highest level (the level of a shallow 
copy). The entries in a tuple cannot be added or removed, but if an 
entry is a mutable object, that object is still mutable and hence the 
tuple is mutable.

I suspect the main reason for the existence of tuples is for use as 
dictionary keys. In this situation it is important to use a truly 
immutable tuple (one containing only immutable entries). I'm not sure 
how much protection Python offers, but if you do succeed in using a 
mutable tuple as a dictionary key, and the tuple changes, the key will 
no longer point to the entry.

tuples appear to be basically a "const" form of lists. If Python had 
"const" (from C++) then it probably would not need tuples.


-------------------------------------------------------------
Is the match() function any different to having search() with a ^ at the beginning of the string?
http://www.faqts.com/knowledge-base/view.phtml/aid/3348
-------------------------------------------------------------
Fiona Czuczman
Tim Peters

Yes, although the difference doesn't become clear until you exploit the
optional slicing arguments of compiled regexps:

>>> import re
>>> p = re.compile("^a")
>>> p.search("cba", 2)
>>> p = re.compile("a")
>>> p.match("cba", 2)
<re.MatchObject instance at ead590>
>>>

That is, while there is an "a" at index 2 of "cba", and "match" finds 
it, a caret does *not* match starting at index 2 (caret means 
start-of-string, and may or may not mean more than that depending on 
"multiline" mode -- using "match" instead cuts all that magical crap out 
of the equation).


-------------------------------------------------------------
How can I choose an element from a list at random?
How can I choose an element from a list at random?
http://www.faqts.com/knowledge-base/view.phtml/aid/1361
-------------------------------------------------------------
Nathan Wallace, Fiona Czuczman
Bruce Wolk

import random
random.choice(list)


-------------------------------------------------------------
Is there a function returning the intersection of two lists?
http://www.faqts.com/knowledge-base/view.phtml/aid/3283
-------------------------------------------------------------
Fiona Czuczman
Penfold

Example:

l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]

l3 should be [4,5]

Solution:

You could try using the ever useful kjbuckets module (find it on
http://www.vex.net/parnassus).

This implements mathematical sets and graphs which mean your below 
becomes as easy as

kjSet([1,2,3,4,5]) & kjSet([4,5,6,7,8])


-------------------------------------------------------------
I'd like to create a subclass of list that loads its contents from a file when you instantiate it. What do I subclass to do this?
http://www.faqts.com/knowledge-base/view.phtml/aid/3424
-------------------------------------------------------------
Fiona Czuczman
Remco Gerlich

You can't directly subclass types, like lists and integers. This is 
commonly viewed as a flaw in Python, maybe this will be changed once.

However, you can subclass UserList.UserList, a Python wrapper around a 
list (see Lib/UserList.py for its source).


-------------------------------------------------------------
I'm searching information regarding the use of pointers for linked and double linked lists.
http://www.faqts.com/knowledge-base/view.phtml/aid/3770
-------------------------------------------------------------
Fiona Czuczman
Martijn Faassen

Linked lists aren't hard:

class Node:
    def __init__(self, next):
        self.next = next

linked_list = Node(Node(Node()))

Every name in Python's a reference, so no pointers are needed. Just 
think of every name in Python as a pointer (to an object), if you like.

Doubly linked lists are along the same pattern, but have the trouble 
that they introduce circular references, which is bad for Python's 
reference counting based garbage collection scheme. You have to break 
one of the references yourself for it to work:

class Node:
    def __init__(self, prev, next):
        self.prev = prev
        self.next = next

node1 = Node(None, None)
node2 = Node(None, None)
node1.next = node2
node2.prev = node1

# and now to clean up so that refcounting works:
node2.prev = None







More information about the Python-list mailing list