[FAQTS] Python Knowledge Base Update -- August 2nd, 2000

Fiona Czuczman fiona at sitegnome.com
Wed Aug 2 08:29:27 EDT 2000


Hello All,

<standard comment>Here is yet another instalment of entries into 
http://python.faqts.com </standard comment>

- Fiona 


## Unanswered Questions ########################################


-------------------------------------------------------------
How do I take an int, which represents an IP address, and convert it back to dotted quad format?  (in C, it's inet_ntoa)
http://www.faqts.com/knowledge-base/view.phtml/aid/5115
-------------------------------------------------------------
Jon Nelson, Fiona Czuczman



-------------------------------------------------------------
The Windows distribution is set up to work with Tcl/Tk version 8.0 dlls.  How do I reconfigure it to work with a later version of Tcl/Tk?
http://www.faqts.com/knowledge-base/view.phtml/aid/5149
-------------------------------------------------------------
Steve Beisner



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


-------------------------------------------------------------
Does Python distinguish between double and single quotes in any way?
http://www.faqts.com/knowledge-base/view.phtml/aid/5151
-------------------------------------------------------------
Fiona Czuczman
John Grayson, Aahz Maruch, Erik Max Francis

Single and double quotes may be freely interchanged (so long as
they are balanced %-) ). It is easy, therefore, to construct strings
containing either single or double quotes.

      "It's"       'quote "xxx"'

      lst = ['1', "2", '3']  is equivalent to lst = ["1", '2', "3"]

If you are constructing command strings to use in Unix, then it can
be very convenient. Note that you may still need to escape occasional
quotes...

   look4 = 'file'
   word_count = os.popen("grep 'open(%s \"rb\")' *.py | wc" % look4)

------

In addition to all the other comments, remember that if you have quoting
problems, use """ or ''' (the two triple-quotes) -- you can avoid almost
all quote-quoting that way.

------

They're both interchangeable.  They're used to help with quoting of the
quotes themselves, viz.:

    '"Buk," said the duck.'
    "There's a duck here."

Specifically, in Python the quotes are not used to determine whether
variables are embedded in strings, as they are in shell scripting or
Perl or some other languages; Python does not embed variables that way.


-------------------------------------------------------------
Specifying a proxy server to be used for httplib?
http://www.faqts.com/knowledge-base/view.phtml/aid/5152
-------------------------------------------------------------
Fiona Czuczman
Amit, David Currie

Problem:

The Internet in our office can only be accessed through a proxy server.
I wanted to write a utility in Python that uses the httplib module to
automate some routine searches. But I am stuck since there does not
seem to be a way to access the Internet thru' the proxy.

I am sure there is a very small thing which I am missing. Could someone
please advise on how to channel the request thru' proxy and automate
authentication?

Solution:

I figured it out by reading RFC 2617 on "HTTP Authentication: Basic and
Digest Access Authentication", and by a helpful post by David Currie
dated 12 July, 2000.

The solution - in this case - was as follows:

---------------------------------------------
import httplib
import base64

# 1. connect to the proxy
h1 = httplib.HTTP("154.112.170.19:80")

# 2. give the absolute URL in the request
h1.putrequest('GET', 'http://www.yahoo.com/')

h1.putheader('Accept', 'text/html')
h1.putheader('Accept', 'text/plain')

# 3. set the header with a base64 encoding of user-id:passwd
auth = "Basic " + base64.encodestring("john_doe:glug#123")
h1.putheader('Proxy-Authorization', auth)

h1.endheaders()

# 4. get the page
errcode, errmsg, headers = h1.getreply()

print errcode
print errmsg
print headers

f=h1.getfile()
for line in f.readlines():
    print line
---------------------------------------------


-------------------------------------------------------------
Is there a way to create variables on the fly, like in a loop?
http://www.faqts.com/knowledge-base/view.phtml/aid/5153
-------------------------------------------------------------
Fiona Czuczman
Michal Wallace

Problem:


Does anyone know of a way to create variables on the fly, like in a 
loop?  I want to be able to build a set of check buttons in a GUI I'm 
writing, and each check button needs a different variable, I think, to 
determine which ones are checked.  I want to use a for loop to iterate 
over a list to build the check buttons, but I don't know the contents or 
length of the list.

Solution:

The concept is called anonymous objects. In python, objects can have
more than one reference pointing to them. Some of those references
have names, or labels that you can see in the code. eg:

>>> x = SomeClass()

.. That creates a SomeClass instance and calls it "x". But
you can then say:

>>> y = [x]

.. And now y[0] references the same SomeClass instance. 
if you then say:

>>> x = None

.. y[0] is STILL REFERENCING the original SomeClass instance. 
It's just "anonymous" now because it doesn't have a specific
name. You could just as easily have said:

>>> y = [SomeClass()]

and if you want more than one:

>>> y = []
>>> for x in range(10):
...     y.append[SomeClass()]


Here's some psuedocode that might get you thinking:

>>> btnLst = []
>>> for x in range(whatever):
...    newBtn = SomeButton() # just create the widget
...    btnValue =  SomeValue() # read from a list, maybe?
...    newBtn.pack() # or whatever to get it on the screen
...    list.append((newBtn,btnValue)


and later on:

>>> for button in btnLst:
...     if button.isChecked:
...         DoWhatever()


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


-------------------------------------------------------------
How do I print out the current time?
How can I get the current date and time?
http://www.faqts.com/knowledge-base/view.phtml/aid/3600
-------------------------------------------------------------
Mike Hostetler, Fiona Czuczman
http://www.python.org/doc/current/lib/module-time.html,Jeff

I didn't think that the official documentation was very clear on this 
(but it is there), so I'm adding it here.

If you do

>> import time
>> print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

You'll see something like:

2000-06-08 15:05:09

To dissect this:

time.time() gets the time in seconds since the epoch

time.localtime(secs) creates a tuple

time.strftime(string,tuple) creates a string of the time, using the 
formatting in "string" (that is what the "%"'s are doing there).
To see the full table of formatting options, see 
http://www.python.org/doc/current/lib/module-time.html

Also, the system man page, ('man strftime')? documents a closer set of 
the formatting options actually supported by the libc, which is what the 
python interpreter actually calls into. this will come into play mostly 
on 'older' machines, but python runs on them too!


-------------------------------------------------------------
Is there a quick way to see if a string is a valid date?
http://www.faqts.com/knowledge-base/view.phtml/aid/3991
-------------------------------------------------------------
Fiona Czuczman
richard_chamberlain

Marc Lemburg's mxDateTime module (do a search at www.vex.net/parnassus)
returns a RangeError if you create a date that doesn't exist. I've 
created a checkDate method below which returns 0 or 1.

mxDateTime is an excellent module if you're going to be doing anything
complicated with dates or times.

import DateTime

def checkDate(y,m,d):
    "year,month,day"
    try:
        checkDate=DateTime.DateTime(y,m,d)
    except DateTime.RangeError:
        return 0
    else:
        return 1
def testDates(y,m,d):
    print '%d/%d/%d' %(y,m,d)
    if checkDate(y,m,d):
        print 'is ok'
    else:
        print 'is not valid'

def main():
    testDates(2000,3,10)
    testDates(2000,13,3)

if __name__=='__main__':
    main()


-------------------------------------------------------------
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.







More information about the Python-list mailing list