Re: [Tutor] Alan's responce frustrated beginner

2005-09-29 Thread Alan G

>I want to save this file, import it and make the changes, eggs = 
>toast, spam
> = jelly and change the values if needed.
>
> def firstpart():
>   for n in range(0, 55):
>  if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>  print 'eggs,',
>  else:
>  print 'spam,',

There are two approaches:

1) Use module level variales for the messages:

 module testval 

passMessage = 'eggs'
failMessage = 'spam'

def firstpart():
   for n in range(55):
 if n %3 . :
   print passMessage
 else: print failMessage

###

### clientcode 

import testval

testVal.passMessage = 'Milk'
testVal.failMessage = 'Honey'

testval.firstpart()



2) Use function parameters

def firstpart(iterations, condition, passMsg, failMsg):
   for n in range(iterations):
 if condition:
   print passMsg
 else: print failMsg

firstpart(55,(n % 3 or n % 7 or n % 11), 'eggs','spam')
firstpart(55,(n % 3 or n % 7 or n % 11), 'Milk','Honey')

###

The second approach is probably best IMHO (whether you
parametereise the iterations and condition is optional,
it just makes the function as geeric as possible...)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-29 Thread Alan G
> I have this list wich is made of tuples. I wish I could "flatten" 
> this list, that is, to extract each element in the tuples and 
> build a new flat list with it. 

Recursion is often used for this, there is an example 
function in my tutorial topic on recursion (using nested 
lists rather than tuples but it should work for either)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-29 Thread Pujo Aji
Hi,
 
Use this:def _flatten(seq,myhasil):
  for isi in seq:
if type(isi) != str:
  try:
_flatten(isi,myhasil)
  except:
myhasil.append(isi)
else:
  myhasil.append(isi)
  
def flatten(seq):
  '''code to flatten tupple'''
  hasil = []
  _flatten(seq,hasil)
  return hasil
http://www.uselesspython.com/showcontent.php?author=38
Cheers,
pujo 
On 9/29/05, Bernard Lebel <[EMAIL PROTECTED]> wrote:
Hello,I have this list wich is made of tuples. I wish I could "flatten" thislist, that is, to extract each element in the tuples and build a new
flat list with it. Is there any shortcut to do that or do I have to gothrough some list comprehension-like procedure?(I have looked at sets but I have to keep things ordered).ThanksBernard
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] New-style classes

2005-09-29 Thread Jan Eden
Hi,

after updating a program to use new-style classes, I am a bit confused. My 
setup looks like this (simplified):

#Show.py

import Data

class Base(object):
...

class Page(Data.Page, Base):
...

class Author(Data.Author, Base):
...

#Data.py

class Base:
...

class Page(Base):
...

class Author(Base):
...

The module Show.py provides methods, Data.py provides data attributes. I use 
the property method in Data.Base for a certain attribute - but why does this 
work?

Data.Base has no base classes, so it is not based on a built-in type: How can 
it be a new-style class?

Thanks for any hints,

Jan
-- 
There are 10 kinds of people:  those who understand binary, and those who don't
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-29 Thread Kent Johnson
Kent Johnson wrote:

> I'm curious about why you want to do this, it is kind of a strange
> requirement. But anyway, here is a class that subclasses dict and
> presents the interface you want to client code. It doesn't actually
> update all instances when you add or delete a key; it keeps a list of
> valid keys in a class attribute and updates this list when you add or
> delete. Then when you access a key it checks the list of valid keys.
> If the key you want is not in the list, you get a KeyError - the
> instance dict is never checked. If the key you want is in the list
> but not in the instance, you get the default value.

This class needs a little more work to correctly model a dictionary - its 
keys(), values(), items(), __contains__(), __iter__() and iteritems() methods 
at least need customization to work from the _keys attribute. One way to do 
this would be to inherit from UserDict.DictMixin; then only keys() would have 
to be defined.

Kent
 
> I don't see any need to actually add default values to all the dicts.
> Conceivably to save memory you might want to actually delete values
> from all the dicts; to do this you could keep a list of all the
> existing dicts as another class attribute. I'm not sure you will save
> much though as the dict itself probably doesn't resize downward. A
> side effect of not deleting keys is that if you delete and then
> restore a key, instances that had that key before will magically
> restore their old value. This could be a bug or a feature depending
> on your requirements.
> 
> Finally, the set of valid keys is shared by all instances, so if you
> want to use this for two different types of things you will have to
> make subclasses and give each subclass its own _key attribute.> 
> Requires Python 2.3 or greater
> 
> Kent
> 
> # CommonKeysDict.py
> # Make it work with Python 2.3
> try:
> set
> except NameError:
> from sets import Set as set
> 
> class CommonKeysDict(dict):
> """Dictionary where all instances must have the same set of keys
>and with a default value for unknown keys.
>
>>>> d = CommonKeysDict()
>>>> d[0]
>Traceback (most recent call last):
>  ...
>KeyError: 0
>
>>>> d[0] = 1
>>>> d[0]
>1
>
>A second instance will get the default value for keys that are in use:
>>>> d2 = CommonKeysDict()
>>>> d2[0]
>'default'
>
>The second instance can have its own values
>>>> d2[0] = 2
>>>> d2[0]
>2
>>>> d[0]
>1
>
>Deleting a key from any instance removes that key from the allowed set.
>Note that this doesn't actually delete the key from all instances, it 
> just
>makes it inaccessible.
>
>>>> del d[0]
>>>> d2[0]
>Traceback (most recent call last):
>  ...
>KeyError: 0
>
> """
> 
> _keys = set()
> 
> def __init__(self, **items):
> dict.__init__(self, **items)
> 
> def __getitem__(self, key):
> if key not in self._keys:
> raise KeyError, key
> try: 
> return dict.__getitem__(self, key)
> except KeyError:
> return 'default'
> 
> 
> def __setitem__(self, key, value):
> self._keys.add(key)
> dict.__setitem__(self, key, value)
> 
> 
> def __delitem__(self, key):
> self._keys.remove(key)
> dict.__delitem__(self, key)
> 
> 
> def _test():
> import doctest
> doctest.testmod()
> 
> if __name__ == "__main__":
> _test()
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-29 Thread Kent Johnson
Ron Phillips wrote:
> Maybe I should explain why I thought I wanted this object. I am trying
> to read, edit, and write shapefiles (actually, a shapefile is a
> collection of 3-6 files having the same filename, but different
> extensions. It's a legacy format that still gets a lot of use in
> geography.)
> 
> One of the constituent files in a shapefile is a variant of Xbase,
> which knows nothing  about NULL, so I have to provide some value in
> every column for every record when I write them. I thought that having a
> data structure that enforces a common set of "fields", the application
> would be more robust when it's being edited. (Prevent me from deleting
> an item for one record and not others, or adding a field to a record
> without adding at least some default value to all the others.)
> 
> I just thought about it, but a CSV file has kind of the same problem.

I think I would try the same solution used by csv.DictWriter - use a writer 
object that has knowledge of the required fields and a default value. This 
assumes that at the time of writing you know what the required fields are, 
which seems reasonable but without knowing more about your app I can't be sure. 
Then the writer fills in the necessary default values as it writes the data.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Generalising system processes

2005-09-29 Thread Peter Jessop
Good day.

Is there a library in Python that generalises the display of processes
in the system.
I am looking for a consistent way of seeing processess, (a python
equivalent of ps(unix) or tasklist (windows).

I have googled but the only suggestion I have found was to install ps
on Windows.

Thanks

Peter Jessop
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New-style classes

2005-09-29 Thread Kent Johnson
Jan Eden wrote:
> Hi,
> 
> after updating a program to use new-style classes, I am a bit confused. My 
> setup looks like this (simplified):
> 
> #Show.py
> 
> import Data
> 
> class Base(object):
> ...
> 
> class Page(Data.Page, Base):
> ...
> 
> class Author(Data.Author, Base):
> ...
> 
> #Data.py
> 
> class Base:
> ...
> 
> class Page(Base):
> ...
> 
> class Author(Base):
> ...
> 
> The module Show.py provides methods, Data.py provides data
> attributes. I use the property method in Data.Base for a certain
> attribute - but why does this work?
> 
> Data.Base has no base classes, so it is not based on a built-in type:
> How can it be a new-style class?

Data.Base is not a new-style class, but the classes in Show are. And properties 
may appear to work in old-style classes. This document
http://www.python.org/2.2.3/descrintro.html#property
says,
Properties do not work for classic classes, but you don't get a clear error 
when you try this. Your get method will be called, so it appears to work, but 
upon attribute assignment, a classic class instance will simply set the value 
in its __dict__ without calling the property's set method, and after that, the 
property's get method won't be called either.

Here is an old-style class that defines a property:

 >>> class OldStyle:
 ... def getA(self):
 ... print "getA"
 ... return self.__a
 ... def setA(self, value):
 ... print "setA"
 ... self.__a = value
 ... a = property(getA, setA)
 ...
 >>> o=OldStyle()

OldStyle.getA() is called the first time I access o.a:
 >>> o.a
getA
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in getA
AttributeError: OldStyle instance has no attribute '_OldStyle__a'

Setting a value for a wipes out the property, now it behaves like a normal 
attribute:
 >>> o.a = 3
 >>> o.a
3

A class that inherits from object and OldStyle is a new-style class and the 
property works as expected:
 >>> class NewStyle(object, OldStyle):
 ...   pass
 ...
 >>> n=NewStyle()
 >>> n.a
getA
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in getA
AttributeError: 'NewStyle' object has no attribute '_OldStyle__a'
 >>> n.a=3
setA
 >>> n.a
getA
3

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with BeautifulSoup

2005-09-29 Thread Kent Johnson
(resending to the whole list)

Bernard Lebel wrote:
> Hi Kent,
> 
> Thanks a lot for that answer. I have had a look at the BS code, and I
> have to admit I'm a bit at a loss: how would you add several nestable
> tag names in that list?
> 
> I tried
> NESTABLE_TAGS = BeautifulSoup.buildTagMap( [], 'parameter', 'parameters' )
> for example, but I kept having these nesting issues. I fact I have a
> whole bunch of tags that I need to make nestable

I think that's right but I confess I don't understand that part of the code too 
well either. Maybe an email to the author? or maybe it's time to try 
ElementTree (and pdis XPath?) again.

Kent

> 
> 
> Thanks
> Bernard
> 
> 
> On 9/26/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Hi grouchy,
>>>
>>>I seem to have found the problem. Somehow, it seems BeautifulSoup
>>>doesn't like nested tags of the same name.
>>
>>This seems to be a feature of BS. It seems a bit of a misfeature when applied 
>>to XML but anyway...you can configure BS with a set of tags which can be 
>>nested, then it will properly parse your data. Here is a short program that 
>>shows how:
>>
>>xml = '''
>>
>>  1
>>
>>'''
>>
>>import BeautifulSoup
>>
>>class NestingParser(BeautifulSoup.BeautifulStoneSoup):
>>NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
>>
>>soup = NestingParser(xml)
>>print soup.prettify()
>>
>>
>>Kent
>>
>>___
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Installing ActiveState Python vs2003

2005-09-29 Thread Mohammad Moghimi
Hi
When I tried  to install activestate python(.net implementation of python) to my visual studio 2003.
It gives me this error message:

The Visual Python Installer found an installation of Python 2.4, 
but it also requires the win32 extensions.

what's  the problem? -- Mohammaddo you Python?!!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New-style classes

2005-09-29 Thread Jan Eden
Hi Kent,

Kent Johnson wrote on 29.09.2005:

>>Data.Base has no base classes, so it is not based on a built-in
>>type: How can it be a new-style class?
>
>Data.Base is not a new-style class, but the classes in Show are. And
>properties may appear to work in old-style classes. This document
>http://www.python.org/2.2.3/descrintro.html#property says,
>Properties do not work for classic classes, but you don't get a
>clear error when you try this. Your get method will be called, so it
>appears to work, but upon attribute assignment, a classic class
>instance will simply set the value in its __dict__ without calling
>the property's set method, and after that, the property's get method
>won't be called either.

Thanks for your quick reply. I read the document you mentioned before, that's 
why I was confused.

My actual code looks like this:

class Base:
def GetOwnType(self):
try: return self._own_type
except: return self.child_type

def SetOwnType(self, value):
self._own_type = value

own_type = property(GetOwnType, SetOwnType)

For some of the subclasses of Base, the attribute own_type is defined, the 
others should use child_type.

For both groups of subclasses, this works fine - if own_type has not been set 
somewhere else, self.child_type is returned when calling self.own_type.

When checking Data.Base.__mro__, I get an error, so it is not a new-style class 
by itself.

On the other hand, every time I use the own_type attribute, I do so via 
instances of new-style classes (Show.Page, Show.Author etc).

Could it be that the nature of these classes makes the code in Data.Base behave 
according to the new-style rules?

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generalising system processes

2005-09-29 Thread R. Alan Monroe
> Is there a library in Python that generalises the display of processes
> in the system.
> I am looking for a consistent way of seeing processess, (a python
> equivalent of ps(unix) or tasklist (windows).

> I have googled but the only suggestion I have found was to install ps
> on Windows.

On Windows, you can probably use ctypes module to call
CreateToolhelp32Snapshot()

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/perfmon/base/createtoolhelp32snapshot.asp

I have not tried this in Python, though.

Alan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-29 Thread Bernard Lebel
Thanks for the examples and references everyone.

I should clarify though that I was simply looking for a *built-in*
feature rather than a function or a list-comprehension. I know these
last two works and I currently use a list comprehension.

# Example:
>>> flatten( [ 1, 3, 4, ('allo', 'bonjour', 'salut' ), 34, False,
False, ( 3, ) ]
[ 1, 3, 4, 'allo', 'bonjour', 'salut' , 34, False, False, 3 ]


Cheers!
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New-style classes

2005-09-29 Thread Kent Johnson
Jan Eden wrote:
> My actual code looks like this:
> 
> class Base:
> def GetOwnType(self):
> try: return self._own_type
> except: return self.child_type
> 
> def SetOwnType(self, value):
> self._own_type = value
> 
> own_type = property(GetOwnType, SetOwnType)
> 
> For some of the subclasses of Base, the attribute own_type is
> defined, the others should use child_type.
> 
> For both groups of subclasses, this works fine - if own_type has not
> been set somewhere else, self.child_type is returned when calling
> self.own_type.
> 
> When checking Data.Base.__mro__, I get an error, so it is not a
> new-style class by itself.
> 
> On the other hand, every time I use the own_type attribute, I do so
> via instances of new-style classes (Show.Page, Show.Author etc).

That is the key

> 
> Could it be that the nature of these classes makes the code in
> Data.Base behave according to the new-style rules?> 

Yes, I tried to show that in my example. Any class that has a new-style class 
as one of its base classes will be a new-style class. The attribute lookup is 
implemented in the metaclass.

For an instance of Data.Base, the metaclass (the class of its class) is 
types.ClassType, which implements old-style attribute access. So if you create 
a Data.Base directly the property access will be broken.

On the other hand if you create an instance of Show.Page, the meta class is 
type, which implements new-style attribute access and the properties will 
behave correctly.

You have to keep in mind, this is Python, everything is dynamic. When you 
define Data.Base you don't define its behaviour irrevocably. Attribute lookup 
happens at runtime and is affected by the current state of the object.

Kent

> Thanks,
> 
> Jan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Jay Loden
I've not been able to find an answer to this conundrum anywhere: 

My current website is done in PHP with a setup something like this: 

::PHP TEMPLATE CODE::

include('file.htm')

::PHP TEMPLATE CODE::

This way, I can have PHP embedded in my htm files and it will be processed as 
part of the script. For example, I can have a form that's written in HTML and 
processed in PHP, then simply 'include("form.htm")' and I have a form with 
processing that's ALSO wrapped in my site template. 

I can't figure out how one would approach this in Python (i'm using 
mod_python). There's no equivalent to the "include" function from PHP. I 
can't use import because then Python would try to parse the HTML from the 
imported file. I've looked at stuff like cheetah and PSP, but neither of 
those actually answers the question, which is how can I include dynamic 
content including PHP code directly into an existing script. Even if I 
started using PSP, I still can't "include" a PSP page into the middle of 
another PSP page.

I'm definitely willing to consider any other solution for how I can make a 
form that processes its input but maintains my template code wrapped around 
it, so feel free to point out a "Pythonic" method. I just don't want to 
duplicate the template code, and I can't find a nice neat solution like what 
I've got in PHP.

-Jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Adam Cripps
On 9/29/05, Jay Loden <[EMAIL PROTECTED]> wrote:
> I've not been able to find an answer to this conundrum anywhere:
>
> My current website is done in PHP with a setup something like this:
>
> ::PHP TEMPLATE CODE::
>
> include('file.htm')
>
> ::PHP TEMPLATE CODE::
>
> This way, I can have PHP embedded in my htm files and it will be processed as
> part of the script. For example, I can have a form that's written in HTML and
> processed in PHP, then simply 'include("form.htm")' and I have a form with
> processing that's ALSO wrapped in my site template.
>
> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from PHP. I
> can't use import because then Python would try to parse the HTML from the
> imported file.

I thought PHP also parsed any html rendered through an included file?
Am I wrong here?
Adam
--
http://www.monkeez.org
PGP key: 0x7111B833
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread DS
bob wrote:

> At 04:29 PM 9/28/2005, DS wrote:
>
>> What I'm hoping to avoid is an
>> explicit reference to any of the called functions within the program.
>> By doing it that way, it would avoid a maintenance problem of having to
>> remember to put a reference for every new function in the calling
>> program.
>
>
> Try this - a class in which you define all the functions. The __init__
> method builds the dictionary.
>
> >>> class X:
> ... funcs = {}
> ... def y(self):
> ... pass
> ... def __init__(self):
> ... for itemname in dir(self):
> ... if not itemname.startswith('__'):
> ... item = getattr(self, itemname)
> ... if callable(item):
> ... self.funcs[itemname] = item
> ...
> >>> y = X()
> >>> y.funcs
> {'y': >}
>   


Thanks bob, that's an interesting approach.  That would be one huge class.

ds
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Christopher Arndt
Jay Loden schrieb:
> I can't figure out how one would approach this in Python (i'm using 
> mod_python). There's no equivalent to the "include" function from PHP. I 
> can't use import because then Python would try to parse the HTML from the 
> imported file. I've looked at stuff like cheetah and PSP, but neither of 
> those actually answers the question, which is how can I include dynamic 
> content including PHP code directly into an existing script. Even if I 
> started using PSP, I still can't "include" a PSP page into the middle of 
> another PSP page.

Python does not support mingling of Python code within HTML as PHP does out of
the box (because it is a general purpose programming language and wasn't
devised specifically for web development).  But there are several templating
modules that allow to embed Python code into other documents, like e.g. HTML.
You already mentioned Cheetah and PSP, another one I have used and found really
easy to work with, is EmPy.

With these, your script would basically be structured like the this: you have
your main CGI script, Servlet or whatever written in Python. There you import
the template module and use the functions it provides to load your HTML
template with embedded Python instructions and process it. Your main script
reads the output of the template processing and send it to standard out (which
is ultimately send to the browser).

For example (pseudo code)

-> mytemplate.tpl <-


@{htmlescpape(title)}


List of users:


@{for user in users}
  @{htmlescape(user)}
@{end for}


@{import time
now = time.asctime()
}
Generated at @{htmlescape(now)}


-> end mytemplate.tpl <-

-> myscript.cgi <-
import templatemodule

substitutions = dict(title="User list", users=('joe', 'bob', 'alice'))

output = template.process('mytemplate.tpl', substitutions)
print "Conten-type: text/html\n'
print output
-> myscript.cgi <-


Remember, this is pseudo code. There is no template module (to my knowledge)
that actually uses this exact syntax. But you should get the idea.

> I'm definitely willing to consider any other solution for how I can make a 
> form that processes its input but maintains my template code wrapped around 
> it, so feel free to point out a "Pythonic" method. I just don't want to 
> duplicate the template code, and I can't find a nice neat solution like what 
> I've got in PHP.

You just have to change your point of view. PHP *is* practically a template
language. The actual template processor is the Apache PHP module. In Python,
you can choose from several template modules available, each of which has it's
own syntax conventions and mechanisms.

Chris

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Frustrated Beginner

2005-09-29 Thread Daniel Watkins
Rosalee Dubberly wrote:
> ## Now I am trying to modify the function to replace eggs with toast
> and spam with jelly. I have spent days and nothing works. Can you send
> me in the right direction?? 

The obvious answer (that has already been mentioned) is to simply
replace the words in the actual program with their substitutes. However,
this is so obvious I sincerely hope that you don't mean this by the
question.

The right direction, as I understand it, would be to set the text to be
printed in a variable, which can then be passed to the function. This
will allow you to change the text to whatever you want easily, as well
as including the possibility for user input later.

An example is attached, so you can try to work it out yourself without
seeing it.

Dan
def firstpart(success,fail):
for n in range(0, 55):
if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
print n,"-",success
else:
print n,"-",fail

firstpart("yes","no")
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Alan G
>> can't use import because then Python would try to parse the HTML 
>> from the
>> imported file.
>
> I thought PHP also parsed any html rendered through an included 
> file?

It does but PHP 'understands' HTML - or more specifically ignores it!

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Alan G
> My current website is done in PHP with a setup something like this:
>
> ::PHP TEMPLATE CODE::
>
> include('file.htm')
>
> ::PHP TEMPLATE CODE::
>
> This way, I can have PHP embedded in my htm files and it will be 
> processed as
> part of the script.

OK, But PHP uses server side scripting like JSP or ASP
whereas mod Python uses standard CGI style programming.
You have to turn your thinking inside out.

You write the code and print the HTML.

So to include some html file output in your program use
something like:

print open('foo.htm').read()

Of course foo.html has to be pure html (or client side
scripting) that goes straight to the browser.

> ...I have a form with
> processing that's ALSO wrapped in my site template.

If you want to import processing put that in a python
module and import that, keep the code and function separate
(always good practice!).

If you really want ASP sytyle processing you need to look
at another web server technology such as Zope, PSP or
similar server scripting solutions for Python.

> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from 
> PHP.

Correct, the concept doesn't exist because you are working
with vanilla CGI rather than server scripting.

> can't use import because then Python would try to parse
> the HTML

But you can use import to pull in reusable python code.
Of course that's not quite the same since the python code
can't read values of the HTML fields etc. No problem for
the code in the current file but tricky if your form is
in the 'included' file...

> imported file. I've looked at stuff like cheetah and PSP,

> which is how can I include dynamic content including PHP code

Do you really mean you want a python script to include PHP code?
Thats something else again and I doubt if its possible.
I assumed your included file contained a mix of html and
python code?

> started using PSP, I still can't "include" a PSP page
> into the middle of another PSP page.

I thought you could do it using standard html SSI?

> I'm definitely willing to consider any other solution for how I can 
> make a
> form that processes its input but maintains my template code wrapped 
> around
> it, so feel free to point out a "Pythonic" method. I just don't want 
> to
> duplicate the template code, and I can't find a nice neat solution 
> like what
> I've got in PHP.

PHP comes from a very specific style of web programming.
Python tends to support vanilla CGI and to do PHP style coding you
need add-ins like PSP(the first suchj and therefore the most basic)
Either move up to a more powerful engine, like Zope, or adapt to CGI
style coding.

There are many web frameworks for Python but my needs are met
by CGI at one end and Zope at the other(once!) so I'm no expert.
CherryPy seems to be popular but I've no idea how it works...

HTH,

Alan g. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread bob
At 08:23 AM 9/29/2005, DS wrote:
>bob wrote:
>
> > At 04:29 PM 9/28/2005, DS wrote:
> >
> >> What I'm hoping to avoid is an
> >> explicit reference to any of the called functions within the program.
> >> By doing it that way, it would avoid a maintenance problem of having to
> >> remember to put a reference for every new function in the calling
> >> program.
> >
> >
> > Try this - a class in which you define all the functions. The __init__
> > method builds the dictionary.
> >
> > >>> class X:
> > ... funcs = {}
> > ... def y(self):
> > ... pass
> > ... def __init__(self):
> > ... for itemname in dir(self):
> > ... if not itemname.startswith('__'):
> > ... item = getattr(self, itemname)
> > ... if callable(item):
> > ... self.funcs[itemname] = item
> > ...
> > >>> y = X()
> > >>> y.funcs
> > {'y': >}
> >
>
>
>Thanks bob, that's an interesting approach.  That would be one huge class.

Well if you have lots of functions you will have one *huge* module. The 
additional class stuff is minor.

Also note that you can accomplish a similar thing by defining the functions 
outside any class and then finding them in globals(). Having said that I 
like the class approach in that it becomes a container for the functions 
you want to expose and other functions defined outside the class will be 
ignored. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping threads?

2005-09-29 Thread Michael Sparks
On Thursday 29 September 2005 07:27, Pierre Barbier de Reuille wrote:
> IMO, it is better to explicitely call the base class ... I think it is
> more readable. But I don't know if there is any drawback for any
> solution...

A drawback of NOT using super is that you're potetially setting yourself you 
for a fall.

Consider the following code
(Option 1)
from hypothetical import SomeBaseClass

class myClass(SomeBaseClass):
def __init__(self, ...):
super(myClass, self).__init__(...)

(Option 2)
from hypothetical import SomeBaseClass

class myClass(SomeBaseClass):
def __init__(self, ...):
SomeBaseClass.__init__(self)


In the case of option 1, this will work, and have reliable, predictable 
behaviour even if the implementation of SomeBaseClass in the "hypothetical" 
library changes from something like:

class SomeBaseClass(ActualBase):
   ...

To something like:

class SomeBaseClass(ActualBase,mixin1, mixin2):
   ...


In Option 2, you run the risk of methods higher up the tree being run more 
than once. Obviously in your *own* code you can avoid this if you like, but 
as soon as you start using and inheriting from classes in other people's 
libraries you can't guarantee that you're not running that risk.

I posted an example about this via gmane's email to news gateway last
week, but it doesn't appear to have hit the archive (or the list :) for some
reason, so I've included the reply I gave illustrating what can go wrong if
you don't use super at the end.

Regards,


Michael.
---
Original post regarding super:
Subject: Re: Using superclass __init__ method

paul brian wrote:

> class Base:
>def __init__(self):
>print "hello"
> 
> class Child(Base):
>def __init__(self):
>Base.__init__(self)
> 
>def foo(self):
>   print "foo"

I note this is using "old" style classes. However it's normal to recommend
that people use "new" style classes these days. (I only started using
python after they invented new style classes, hence the quotes around
new/old)

A more canonical example here is this:

class Base(object):
def __init__(self):
print "hello"

class Child(Base):
def __init__(self):
super(Child,self).__init__()
def foo(self):
print "foo"

Whilst this might an esoteric change, it's really to handle the fact that
python has multiple inheritance. Consider:

>>> class ChildOne(Base):
... def __init__(self):
... Base.__init__(self)
... print "Hello from ChildOne"
...
>>> class ChildTwo(Base):
... def __init__(self):
... Base.__init__(self)
... print "Hello from ChildTwo"
...
>>> class GrandChild(ChildOne,ChildTwo):
... def __init__(self):
... ChildOne.__init__(self)
... ChildTwo.__init__(self)
... print "Hello from GrandChild"
...
>>> GrandChild()
Hello from Base
Hello from ChildOne
Hello from Base
Hello from ChildTwo
Hello from GrandChild
<__main__.GrandChild instance at 0x40397f8c>


What you can see here is that the __init__ in Base was executed twice. This
may or may not be a problem with some things, but where people use classes
to "mixin" functionality it can be a real problem.

Consider the alternative using "super" instead: 

>>> class Base(object):
... def __init__(self):
... print "Hello from Base"
...
>>> class ChildOne(Base):
... def __init__(self):
... super(ChildOne,self).__init__()
... print "Hello from ChildOne"
...
>>> class ChildTwo(Base):
... def __init__(self):
... super(ChildTwo,self).__init__()
... print "Hello from ChildTwo"
...
>>> class GrandChild(ChildOne,ChildTwo):
... def __init__(self):
... super(GrandChild,self).__init__()
... print "Hello from GrandChild"
...
>>> GrandChild()
Hello from Base
Hello from ChildTwo
Hello from ChildOne
Hello from GrandChild
<__main__.GrandChild object at 0x4039ccac>


Regards,


Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread DS
bob wrote:

> At 08:23 AM 9/29/2005, DS wrote:
>
>> bob wrote:
>>
>> > At 04:29 PM 9/28/2005, DS wrote:
>> >
>> >> What I'm hoping to avoid is an
>> >> explicit reference to any of the called functions within the program.
>> >> By doing it that way, it would avoid a maintenance problem of
>> having to
>> >> remember to put a reference for every new function in the calling
>> >> program.
>> >
>> >
>> > Try this - a class in which you define all the functions. The __init__
>> > method builds the dictionary.
>> >
>> > >>> class X:
>> > ... funcs = {}
>> > ... def y(self):
>> > ... pass
>> > ... def __init__(self):
>> > ... for itemname in dir(self):
>> > ... if not itemname.startswith('__'):
>> > ... item = getattr(self, itemname)
>> > ... if callable(item):
>> > ... self.funcs[itemname] = item
>> > ...
>> > >>> y = X()
>> > >>> y.funcs
>> > {'y': >}
>> >
>>
>>
>> Thanks bob, that's an interesting approach.  That would be one huge
>> class.
>
>
> Well if you have lots of functions you will have one *huge* module.
> The additional class stuff is minor.
>
I agree.  My first thought when I saw that was that it would be a memory
issue, but then as I sat and thought about it, it I couldn't really tell
if it was any different than a huge module.  One thing I don't have
experience with yet is the amount of memory taken when an instance of
the object is created.  For example, does it use substantially more
memory if there are a bunch of if, elif clauses (representing the unused
functions within the class)?  I'll monkey around with it and see what I get.

> Also note that you can accomplish a similar thing by defining the
> functions outside any class and then finding them in globals(). Having
> said that I like the class approach in that it becomes a container for
> the functions you want to expose and other functions defined outside
> the class will be ignored.

>From what I've read so far, globals are actively discouraged.  A class
seems like the best approach. 

I'm actually pretty surprised that there isn't a built-in facility with
Python for referencing functions like this.  In reading Python in a
Nutshell, prior to asking my questions here, I had thought that there
probably was, but I just wasn't grasping it.

Thanks.

ds




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread Danny Yoo
> >From what I've read so far, globals are actively discouraged.  A class
> seems like the best approach.
>
> I'm actually pretty surprised that there isn't a built-in facility with
> Python for referencing functions like this.  In reading Python in a
> Nutshell, prior to asking my questions here, I had thought that there
> probably was, but I just wasn't grasping it.


Hi DS,


Modules can be thought of as containers for functions.  As a concrete
example, let's say we have a module named 'functions':

##
# in functions.py
def A(): print "A"

def B(): print "B"

def C(): print "C"
##


In other programs, this 'functions' module can be imported and dir()ed:

##
>>> import functions
>>> dir(functions)
['A', 'B', 'C', '__builtins__', '__doc__', '__file__', '__name__']
##


There are our attributes of the 'functions' module.  Those functions in
the module can also be called:

##
>>> getattr(functions, 'A')

>>>
>>> getattr(functions, 'A')()
A
##


I'm not exactly sure if this is what you want, but this shows a simple way
to highlight a selection of functions, by using a module as the container.


Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread DS
Danny Yoo wrote:

>>>From what I've read so far, globals are actively discouraged.  A class
>>seems like the best approach.
>>
>>I'm actually pretty surprised that there isn't a built-in facility with
>>Python for referencing functions like this.  In reading Python in a
>>Nutshell, prior to asking my questions here, I had thought that there
>>probably was, but I just wasn't grasping it.
>>
>>
>
>
>Hi DS,
>
>
>Modules can be thought of as containers for functions.  As a concrete
>example, let's say we have a module named 'functions':
>
>##
># in functions.py
>def A(): print "A"
>
>def B(): print "B"
>
>def C(): print "C"
>##
>
>
>In other programs, this 'functions' module can be imported and dir()ed:
>
>##
>  
>
import functions
dir(functions)


>['A', 'B', 'C', '__builtins__', '__doc__', '__file__', '__name__']
>##
>
>
>There are our attributes of the 'functions' module.  Those functions in
>the module can also be called:
>
>##
>  
>
getattr(functions, 'A')


>
>  
>
getattr(functions, 'A')()


>A
>##
>
>
>I'm not exactly sure if this is what you want, but this shows a simple way
>to highlight a selection of functions, by using a module as the container.
>
>
>Best of wishes!
>
>  
>
Ok!!!   This is exactly it.  Thanks so much.  This provides the link
between a string that represents a function to the actual calling of
that function with getattr().  I was just reading up on the getattr()
because it was in used in Bob's answer, when your email came through.

Thanks so much to all of you that have answered my questions, including 
Liam.Clarke-Hutchinson, whom I didn't acknowledge directly with an
email.  I hope I'm not asking too many questions.  This is kind of a
departure for me.  Usually, I just bang my head against the wall till I
break through.  At some point I hope to get to a point where I can
provide answers for others who are just learning as well.

ds


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Jay Loden
Alan, thanks for your responses, they're quite helpful. I suspect the real 
problem I'm having is simply trying to switch modes of thinking to CGI style 
or mod_python style instead of the PHP style embedded code. 

The whole point of this exercise for me was to decide which language I prefer 
for web development and evaluate Python for web work. So far, I've found PHP 
much easier to work with and less "clunky" in terms of what I'm trying to do 
- but I believe that's very much a function of my thinking being rooted in 
the PHP style. 

If Im understanding this right...the Pythonic/CGI method for something like 
this is to import a template module of some kind, then call methods from that 
template to display the template, with other Python code in the middle that 
takes care of form processing? 

The solution I have now feels smoother, since all I do is put content 
into .htm files, then pull them into a template that's basically an html 
sandwich. This gives me capability to stick a  section into the .htm 
file itself - for example a form with some dynamic content/variables - and 
then from a user perspective, all they see is a normal html page.  

>From a server side, it's seeing one big PHP script that includes both template 
code and form code, but without me needing to write any templating code into 
the form itself - instead I just call the form into the template.  With 
Python, it seems like this kind of approach is impossible, and it also means 
that my form would probably have to have some kind of special extension, like 
"form.py" (so the handler knows what to do with it) instead of just being 
located at "form.htm" - am I following this all correctly? 

Does anyone know of any soup-to-nuts CGI programming examples online for 
Python that might make this clearer so I can bug the list less and just read 
some example code?

-Jay

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread Alan G
> I'm actually pretty surprised that there isn't a built-in facility 
> with
> Python for referencing functions like this.

I'm not. In fact its pretty unusual in any language to try to map
from function name to function directly. Dictionaries are the
universal solution for this, I can only think of a handful(4?)
languages that I've used (Out of 20 plus) that can do
string -> function mapping directly.

Its not usually a very useful thing to do - how would the
typical user know what the function names were? Either the
user has access to the code or the code presents the names
to the user(as strings) in which case a mapping has to
exist somewhere already.

I'm curious as to how you are addressing those issues?
Is this something that only developers will be using?
How will the user know what names are possible?

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread DS
Alan G wrote:

>> I'm actually pretty surprised that there isn't a built-in facility with
>> Python for referencing functions like this.
>
>
> I'm not. In fact its pretty unusual in any language to try to map
> from function name to function directly. Dictionaries are the
> universal solution for this, I can only think of a handful(4?)
> languages that I've used (Out of 20 plus) that can do
> string -> function mapping directly.
>
> Its not usually a very useful thing to do - how would the
> typical user know what the function names were? Either the
> user has access to the code or the code presents the names
> to the user(as strings) in which case a mapping has to
> exist somewhere already.
>
> I'm curious as to how you are addressing those issues?
> Is this something that only developers will be using?
> How will the user know what names are possible?
>
> Alan G.


I am playing with building a facility that accepts equations or
expressions that are parsed and solved.  I hope to use this with genetic
algorithms that would create mostly useless expressions, but that over
time might become better.  If I was doing it for users building
expressions, I'd probably do a javascript kind of approach for
assembling expressions from lists.  Your point is well taken, because
I'm often awed at the amazing ly stupid errors that I make when I'm
typing. 

Rest assured, I don't know 20 languages, computer or otherwise.  I know
that I used some sort of thing like that in the 80's with Revelation, a
database/language derived from Pick.  (That one is probably a little
obscure, it may not be on your list of 20).  I also think you can do
that in Perl, but bear in mind I know less about Perl than I do Python.

ds
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread Michael Sparks
On Thursday 29 September 2005 22:26, Alan G wrote:
> string -> function mapping directly.
>
> Its not usually a very useful thing to do

This is precisely how shared libraries under linux and IIRC DLLs in windows 
work. cf dlopen, dysym in C. 

> how would the typical user know what the function names were?

Under linux one can examine the names of functions in a library using "nm".

eg:
# nm libpython2.4.so|head -20
 U abort@@GLIBC_2.0
000dfea0 d abs_doc
0001fcf0 t abstract_get_bases
0001fe20 t abstract_issubclass
 U access@@GLIBC_2.0
000e9ba0 d acquire_doc
0008f970 t addcleanup
0001be40 t addclosure
000d2040 d add_doc
0009d7c0 t add_flag
0001b8f0 t addnfaarc
0001b870 t addnfastate
00059680 t add_subclass
00049de0 t adjust_tp_compare
000ea680 d alarm_doc
 U alarm@@GLIBC_2.0
000e9760 d allocate_doc
000e6280 d api_version_warning
0003a6f0 t app1
000cfc40 d append_doc

Obviously, ctypes does much the same thing. 

Compare and contrast:

try: 
from ctypes import * 
libc = cdll.LoadLibrary("/lib/libc.so.6")
sched_yield = libc.sched_yield
 except ImportError: 
def sched_yield(): pass
 except AttributeError:
def sched_yield(): pass

with ...

try:
   import functions as libc
   sched_yield = getattr(libc, "sched_yield")
   # this is of course effectively equivalent to:
   #   sched_yield = libc.sched_yield
except ImportError:
def sched_yield(): pass
except AttributeError:
def sched_yield(): pass

It's pretty much the same thing. I could see that this may have uses in 
systems that allow plugins.

Devils-advocate-ly , ;-)


Michael.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-29 Thread Danny Yoo
> Thanks so much to all of you that have answered my questions, including
> Liam.Clarke-Hutchinson, whom I didn't acknowledge directly with an
> email.  I hope I'm not asking too many questions.

Hi ds,

You're doing perfectly fine.  *grin*  We got to see a lot of different
approaches to that class of problem, so I think it was very useful for
folks to see.


Best of wishes to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why won't it enter the quiz? (off topic)

2005-09-29 Thread Jacob S.
Wow! What an argument...
A couple of comments on the code

> {code}
>
> import random
>
> def add(a,b):
>answer = a+b
>guess = float(raw_input(a," + ",b," = "))

This is easier IMHO, but the same
guess = float(raw_input("%s+%s="%(a,b)))

>return answer, guess
>
> num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
> num2 = random.choice(range(1,10))

Oh my.  Read the documentation on the random module.
Specifically random.randrange or even random.randint
Note: the difference between the two -- a <= result < b  as opposed to a <= 
result <= b

> while 1:
>q = random.choice(range(15,31)) ### to choose the number of questions
>cq = 1 ### To find the current question
>correct = 0
>while cq >= q: ### To find whether or not to end the quiz.

Of course, this has been corrected to   while cq <= q:

>print cq
>answer, guess = add(num1,num2)
>if guess != answer:
>print "Incorrect! The correct answer is: ",answer
>cq += 1
>elif guess == answer:
>print "Correct!"
>correct += 1
>cq += 1
>else:
>print "Questions: ",q
>print "Correct: ",correct
>print "Percent Correct: ",(cq/q)*100

Okay, this is a problem -- Due to the integer division cq/q, Percent Correct 
will only display 0, ever

>break
>
> print "Goodbye."

They probably won't see the stats because the program will execute the four 
print statements and immediately exit.  I suggest changing the last 
statement to

raw_input("Goodbye. Press enter to exit. ")

>
> {/code}
>

I have one more comment.  The code in the add function doesn't really seem 
to be that well grouped together ~ IOW, it seems like you defined a function 
just because you felt like you needed practice typing def something(args):

It seems much easier (in this case) to just leave the add() code in the 
actual main block. Does this make sense?

Oops.  I have two comments.  In add() (which I suggest removing) you define 
guess with float(...) whereas your answer is an integer.   (a+b)  So you may 
run into trouble with floating point precision.
For example. ~~Okay, I stand corrected, in my test, none (out of 0-100) gave 
me any trouble.

Hope this helps,
Jacob Schmidt 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Kent Johnson
Jay Loden wrote:
> Alan, thanks for your responses, they're quite helpful. I suspect the real 
> problem I'm having is simply trying to switch modes of thinking to CGI style 
> or mod_python style instead of the PHP style embedded code. 

There are quite a few template engines for Python that allow embedding Python 
into the template. One of them is part of mod_python: 
http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html

Some others are Myghty and Spyce and the PSP component of WebWare:
http://www.myghty.org/
http://spyce.sourceforge.net/
http://www.webwareforpython.org/Webware/PSP/Docs/index.html

You might find that these have a familiar style.

Kent

> 
> The whole point of this exercise for me was to decide which language I prefer 
> for web development and evaluate Python for web work. So far, I've found PHP 
> much easier to work with and less "clunky" in terms of what I'm trying to do 
> - but I believe that's very much a function of my thinking being rooted in 
> the PHP style. 
> 
> If Im understanding this right...the Pythonic/CGI method for something like 
> this is to import a template module of some kind, then call methods from that 
> template to display the template, with other Python code in the middle that 
> takes care of form processing? 
> 
> The solution I have now feels smoother, since all I do is put content 
> into .htm files, then pull them into a template that's basically an html 
> sandwich. This gives me capability to stick a  section into the .htm 
> file itself - for example a form with some dynamic content/variables - and 
> then from a user perspective, all they see is a normal html page.  
> 
>>From a server side, it's seeing one big PHP script that includes both 
>>template 
> code and form code, but without me needing to write any templating code into 
> the form itself - instead I just call the form into the template.  With 
> Python, it seems like this kind of approach is impossible, and it also means 
> that my form would probably have to have some kind of special extension, like 
> "form.py" (so the handler knows what to do with it) instead of just being 
> located at "form.htm" - am I following this all correctly? 
> 
> Does anyone know of any soup-to-nuts CGI programming examples online for 
> Python that might make this clearer so I can bug the list less and just read 
> some example code?
> 
> -Jay
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quick way to find the data type

2005-09-29 Thread Jacob S.
I don't believe that eval() *would* work quite as intended either.

For example:

eval('a random string')
SyntaxError

and McGuire's method

othermethod('a random string')
'a random string'

Another example

eval('file')


othermethod('file')
'file'


That is, of course, if I understood the McGuire's method clearly. I didn't 
look very close. It might be that McGuire's method doesn't account for the 
second case either.

HTH,
Jacob


> Fair enough Danny,
> I made the changes. Thanks for the input.
>
>
> Still, regarding this comment.
>
> On 9/27/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>> The assumptions you make, about controlling the input, and being the only
>> source of the xml output, sound fine.  But you're assuming that the
>> environment that your program will work in will be static.  Software 
>> often
>> ends up being applied in places that are ridiculous and unplanned-for,
>> like a network application.  It's best practice to avoid unneccessary
>> risk, and not to court it.  *grin*
>
> Well, the fact is I'm in charge of these things here, fortunately. My
> job is to make sure nothing gets used the wrong way. :-)
>
> Still, your points are valid and I have taken note of them :-)
>
> Bernard
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-09-29 Thread Jacob S.



Why are you importing string?
 
1) You don't seem to use it anywhere
2) Use string methods instead
 
Jacob

  - Original Message - 
  From: 
  Chris Hallman 
  
  To: tutor@python.org 
  Sent: Wednesday, September 28, 2005 7:35 
  AM
  Subject: Re: [Tutor] script 
question
  Thanks for all the 
  input!!! I really appreciate it. I need to post a correction to my script. 
  What I sent was an early version. I made a few minor modifications:import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])I've 
  researched what you all have suggested and I may need to switch to reading the 
  ini file line by line or using a different file parser. The ini file is only 
  100 lines long now, but will likely grow to 500 line and maybe to 4000 lines. 
  To give you a better background of what I'm doing with this script, it's 
  running on a network management system that receives traps. After some 
  processing of the raw trap, messages get sent to this script for further 
  processing. These messages are for interface down traps from routers and 
  switches in our network. I use this script to mitigate the number of interface 
  down messages on our console. I need to do this because we do not need to know 
  when every port has gone down (i.e. user ports). This script searches the ini 
  file for a device name match. Once it has found a match and if the interface 
  matches as well, I need to message forwarded to the console (the Windows 
  command). If no matching device or interface is found, then the script can 
  just exit. 
  - Show quoted text 
  -
  On 9/26/05, Kent 
  Johnson <[EMAIL PROTECTED]> 
  wrote:
  Kent 
Johnson wrote:> *TEST FIRST* Don't optimize until you know it is too 
slow and you> have a test case that you can time to see if your 
'optimizations' are> making it faster.Pardon my shouting :-) 
Kent___Tutor 
maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor 

  
  

  ___Tutor maillist  
  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Book recommendations?

2005-09-29 Thread Andrew P
I was just thinking about Jon Bentley's Programming Pearls,
and how much I really liked it.  Nothing has really changed since
1986, and all the pseudo code translated nicely into Python.  It
was by far the most fun I've had reading any book about
programming.  Especially solving problems he presented before
turning the page, or trying damned hard to!

Does anybody have any recommendations for other books on programming
practices in general?  Any fun or philosophical reads on software
architecture/design? 

I saw that Alan Gauld recommends Code Complete, and went ahead and ordered that second hand :) 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Installing ActiveState Python vs2003

2005-09-29 Thread Andrei
Mohammad Moghimi  gmail.com> writes:

> When I tried  to install activestate python(.net implementation of python) to
my visual studio 2003.
> It gives me this error message:
>
> The Visual Python Installer found an installation of Python 2.4, 
> but it also requires the win32 extensions.
>
> what's  the problem? -- Mohammaddo you Python?!!

It seems you need to install win32all
(http://starship.python.net/crew/mhammond/win32/). The ActiveState Python distro
(ActivePython) includes this as well. Note that ActivePython is not the same
thing as ActiveState Visual Python, which seems to be what you got - one is a
Python distro, the other is an extension of the VisualStudio IDE. Neither is a
.Net implementation of Python, IronPython is (http://www.ironpython.com/).

Yours,

Andrei

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor