Re: Striving for PEP-8 compliance

2010-04-10 Thread Lawrence D'Oliveiro
In message <18988a53-e88f-4abf-
a83a-314b16653...@x12g2000yqx.googlegroups.com>, Patrick Maupin wrote:

> I want nothing to do with any programmer who would mis-indent their
> code.

But what happens when you’re trying to reconcile two different indentation 
conventions? In Python, there can be problems doing that without introducing 
logic errors. That’s what this thread is about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Striving for PEP-8 compliance

2010-04-10 Thread Lawrence D'Oliveiro
In message , Grant Edwards wrote:

> On 2010-04-10, Lawrence D'Oliveiro 
> wrote:
>
>> In message , Grant Edwards wrote:
>>
>>> Anybody who invents another brace-delimited language should be beaten.
>>> You always end up with a big problem trying to make sure the braces
>>> are consistent with the program logic.
> 
>> Would you prefer ???begin??? and ???end??? word symbols, then?
> 
> Nope, I categorize those as nothing more than verbose "braces".

But since those symbols already, by definition, directly correspond to 
program logic, where exactly does the “big problem” arise trying to make 
sure they are “consistent with the program logic”? 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read file during module import?

2010-04-10 Thread Dave Angel

Jeremy wrote:

I have a module that, when loaded, reads and parses a supporting
file.  The supporting file contains all the data for the module and
the function that reads/parses the file sets up the data structure for
the module.

How can I locate the file during the import statement.  The supporting
file is located in the same directory as the module, but when I import
I get a No such file or directory error.  I could hard code the path
to the filename, but that would make it only work on my machine.

A related question: Can I parse the data once and keep it somewhere
instead of reading the supporting file every time?  I tried pickling
but that wouldn't work because I have custom classes.  (Either that or
I just don't know how to pickle—this is a highly probable event.)

Thanks,
Jeremy

  
By supporting file, presumably you mean a text or binary file, not a 
python module. That's why import won't work.


Now, if the data supports it, you could make that supporting file simply 
be an importable python program. I've seen code generators to create 
python code from a binary file such as a jpeg, so that you can just 
embed such code into your program.


But I'll guess that this isn't reasonable for your data, that the format 
is something you want to separately manipulate.


I think the secret you're looking for is the __file__ attribute of a 
module. That contains the full path to the module source file (.py or 
.pyc, usually). So you use dirname on that string, to get the directory 
name, and os.path.join to combine with your own filename. Now you have a 
string to pass to open().


DaveA

--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic list reordering

2010-04-10 Thread Kent Engström
Ben Racine  writes:
> I have a list...
>
> ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
> 'dir_330_error.dat']
>
> I want to sort it based upon the numerical value only.
>
> Does someone have an elegant solution to this? 

I use code like the hack below to sort miscellaneous strings that
consist of mixed numerical and non-numerical parts.

import re

nsk_re = re.compile("([0-9]+)|([^0-9]+)")
def numeric_sort_key(x):
return [handle_int_nonint(i_ni) for i_ni in nsk_re.findall(x)]

def handle_int_nonint(int_nonint_tuple):
if int_nonint_tuple[0]:
return int(int_nonint_tuple[0])
else:
return int_nonint_tuple[1]

def numerically_sorted(l):
return sorted(l, key=numeric_sort_key)

-- 
http://mail.python.org/mailman/listinfo/python-list


"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON htt

2010-04-10 Thread Naeem
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/"GREECE TV CHANNELS" "BELGIUM
TV CHANNELS" "SWEDEN TV CHANNELS" "RUSSIAN TV CHANNELS" "CHINA TV
CHANNELS" "ROMANTIC TV CHANNELS"   tv channels online" "tv channels
online" "tv channels free" "tv channels live" "usa tv live" "usa tv
channels list" "usa tv online" "alaska tv stations" "california tv
stations" "lebanon tv live" "kuwait tv channels" "kuwait tv channels
jobs" " "tv channels all over the world" "USA TV CHANNELS"
"PAKISTANI TV CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL
TV CHANNELS" "CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ
TV" ON http://all-time-tv.blogspot.com/   "tv channels
all over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN
TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV
CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON 
http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS"
"CANADA TV CHANNELS" "DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON
http://all-time-tv.blogspot.com/   "tv channels all
over the world" "USA TV CHANNELS" "PAKISTANI TV CHANNELS" "INDIAN TV
CHANNELS" "UK TV CHANNELS" "BRAZIL TV CHANNELS" "CANADA TV CHANNELS"
"DANW TV" "GEO TV" "SAMA TV" "AAJ TV" ON http://all-time-tv.blogspot.com/
"tv channels all over the world" "USA TV CHANNELS" "PAKISTANI TV
CHANNELS" "INDIAN TV CHANNELS" "U

Re: Performance of list vs. set equality operations

2010-04-10 Thread Stefan Behnel

Steven D'Aprano, 08.04.2010 03:41:

On Wed, 07 Apr 2010 10:55:10 -0700, Raymond Hettinger wrote:


[Gustavo Nare]

In other words: The more different elements two collections have, the
faster it is to compare them as sets. And as a consequence, the more
equivalent elements two collections have, the faster it is to compare
them as lists.

Is this correct?


If two collections are equal, then comparing them as a set is always
slower than comparing them as a list.  Both have to call __eq__ for
every element, but sets have to search for each element while lists can
just iterate over consecutive pointers.

If the two collections have unequal sizes, then both ways immediately
return unequal.



Perhaps I'm misinterpreting what you are saying, but I can't confirm that
behaviour, at least not for subclasses of list:

>>> class MyList(list):
... def __len__(self):
... return self.n
...
>>> L1 = MyList(range(10))
>>> L2 = MyList(range(10))
>>> L1.n = 9
>>> L2.n = 10
>>> L1 == L2
True
>>> len(L1) == len(L2)
False


This code incorrectly assumes that overriding __len__ has an impact on the 
equality of two lists. If you want to influence the equality, you need to 
override __eq__. If you don't, the original implementation is free to do 
whatever it likes to determine if it is equal to another value or not. If 
it uses __len__ for that or not is only an implementation detail that can't 
be relied upon.


Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Striving for PEP-8 compliance

2010-04-10 Thread Ben Finney
I'm interested that you are holding what appear to be contradictory
arguments, and don't seem to apply each one to the other. Let me take
the latest expressions of these and show how they can apply equally in
either direction:

Lawrence D'Oliveiro  writes:

> But what happens when you’re trying to reconcile two different
> indentation conventions? In Python, there can be problems doing that
> without introducing logic errors.

What happens whe you're trying to reconcile two different
block-delimiter conventions?

Lawrence D'Oliveiro  writes:

> But since [braces] already, by definition, directly correspond to
> program logic, where exactly does the “big problem” arise trying to
> make sure they are “consistent with the program logic”?

Since indentation already, by definition, directly corresponds to
program logic in Python, where exactly is the problem that leads you to
want to eradicate indentation as syntax?


In other words: I don't see why the problems you're asserting are
problematic for one kind of block delimitation syntax but not the other.

-- 
 \   “[Freedom of speech] isn't something somebody else gives you. |
  `\  That's something you give to yourself.” —_Hocus Pocus_, Kurt |
_o__) Vonnegut |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Striving for PEP-8 compliance

2010-04-10 Thread Grant Edwards
On 2010-04-10, Lawrence D'Oliveiro  wrote:
> In message , Grant Edwards wrote:
>
>> On 2010-04-10, Lawrence D'Oliveiro 
>> wrote:
>>
>>> In message , Grant Edwards wrote:
>>>
 Anybody who invents another brace-delimited language should be beaten.
 You always end up with a big problem trying to make sure the braces
 are consistent with the program logic.
>> 
>>> Would you prefer ???begin??? and ???end??? word symbols, then?
>> 
>> Nope, I categorize those as nothing more than verbose "braces".
>
> But since those symbols already, by definition, directly correspond to 
> program logic, where exactly does the ?big problem? arise trying to make 
> sure they are ?consistent with the program logic?? 

The same goes for indentation.  In python it's not possible to write a
program to correctly indent code that isn't alaready correctly indented.

In a brace delimited language it's not possible to write a program to
correctly place braces in an "incorrectly braced" program.

In either: if it is already correct, it's trivial to transform it into
another correct program with a different "style".

-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-10 Thread Manuel Graune
Michael Torrie  writes:
>
> Did you look at the link to Owen Taylor's reinteract program?  I think
> it's closer to what you want than any other thing mentioned here, with
> the exception that it's a standalone GTK (graphical) app.

Yes, I did. And I think this program is a great lightweight alernative
to sage,  which was mentioned in another post and would probably be
my preferred environment if I had complete freedom to set up my working
environment and would not need to exchange  data with others or explain
how someone else is supposed to reuse my code/results in two years time.
 
Things being as they are, I am looking for a solution which works with 
as few additional components  as possible, so that a solution based on
 a simple copy-and-paste class or decorator is preferable. 

Regards,

Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: braceless and semicolonless

2010-04-10 Thread CHEN Guang
Hi Peter,
In PythoidC, I handled C header files (and other C files for INCLUDE) with 
Python regular expression (RE).
First, I use the following RE to break C header files or C files into pieces
sepRE=_re.compile(r'\; | \{ | \} | // | /\* | \*/ | \r?\n',_re.VERBOSE)
Then, I carefully designed a loop testing each of the seperaters between 
adjacent pieces
for sep in sepRE.finditer(f0c):
...
if sg==';':
cItems.append(f0c[span0:ss1].strip())
span0 = ss1
...
to reassemble several (may be one) consequent pieces into items (a function, a 
struct, a constant ...)
At last I classify the items with some REs like
structRE=_re.compile(r'^(struct\s+([0-9A-Za-z_]+)\s*\{.+\}.*\;)$',_re.IGNORECASE|_re.DOTALL)
and arranged the items into Python objects with setattr(...)
You can download and read the source code of PythoidC at http://pythoidc.sf.net 
or http://pythoidc.googlecode.com 
If you feel PHP not good enough, I'd like to suggest Python ( www.python.org ). 
Python is really an excellent language, with Python you can program softwares 
for almost any porpose (except for hardware drivers and some software with very 
high requirement of speed, now PythoidC is just the extension for Python in 
such areas ).
Welcome to join the Python mailing list 
http://mail.python.org/mailman/listinfo/python-list to discuss Python 
techniques, there are many warm-hearted friends willingly to answer almost any 
questions. 
By the way, I work in China Medical University, Shenyang, northeast China. Will 
you tell me something about youself?
Best Regards,
ChenGuang

2010-04-09 22:24:27,"Peter West"  :


Hi Chen, 


My project uses a tree structured linked list to break down PHP into chunks, It 
was necessary because PHP has a lot of syntaxes for strings. Some parts of the 
language like one line comments and heredocs were quite a lot of trouble. How 
have you handled the pre-processor? I briefly considered modifying my project 
for C but the pre-processor's features would be difficult to handle. I'll try 
to find you an example.


What other features would you like to add? In PHP I'm trying to add some useful 
syntaxes such as calling an index of an array without assigning the array to a 
variable e.g. $object->getArray()[0]. Another is instantiating an object and 
using it in the same statement e.g. ($object new Class)->method(). 
Unfortunately PHP is not a very good language and there are only a few things I 
can change about it.


Peter.




2010/4/9 CHEN Guang 

Dear Peter,
I am the developer of PythoidC (braceless and semicolonless C language). I am 
so glad to see your message, just like a message from Voyager 2 spacecraft, 
telling me that I am nolonger alone in the universe! 
My plan is to release new versions of PythoidC from time to time, adding new 
applications and more examples. 
My hope is that our ideal (braceless and semicolonless) will be shared by more 
people in the world, thus lead to the simplification of all computer languages 
(Java, Perl ...)
Let's talk often.
ChenGuang




-- 
http://mail.python.org/mailman/listinfo/python-list


On Class namespaces, calling methods

2010-04-10 Thread vsoler
Still learning python, especially OOP.

While testing classes, I sometimes think of them as "ordinary
containers" of values and functions (methods). That is, values and
functions can be grouped together inside "namespaces" calles classes.

class Uno:
a=1
def m():
print "mouse"

Say that I have this "silly" class.

While I can then write

  print Uno.a

I cannot write
  Uno.m()

I get the following error message:

 TypeError: m() takes no arguments (1 given)

Since I have not created any instances of Uno, there is no self
object, and I do not understand what object is supplied to the
function call.

Could anybody explain what argument is being supplied to the method?
Is ther any workaround to call the m function?

Thank you
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing memory (namespace) before running code

2010-04-10 Thread vsoler
On Mar 21, 5:18 pm, Jon Clements  wrote:
> On 21 Mar, 15:02, vsoler  wrote:
>
> > Hi,
>
> > Is there a way to erase/delete/clear memory before a piece of code is
> > run?
>
> > Otherwise, the objects of the previous run are re-usable, and may
> > bring confusion to the tester.
>
> > Thank you
>
> I'm guessing you're using some sort of IDE?
>
> For instance, in IDLE if the [Python Shell] window is not closed, the
> session is kept. However, there is a menu option 'Shell' which has
> 'Restart Shell'. If you don't see a 'Shell' menu option, then make
> sure IDLE isn't being started with the -n option.
>
> However I would have thought the 'tester' would be running from a
> terminal/command line/double click jobby, so that a single Python
> session is executed and just runs -- rather than want to use it
> interactively afterwards.
>
> hth
>
> Jon.

Hello Jon,

I'm using PythonWin and there is no Shell menu option. And yes, I am
using python interactively.

Perhaps it is simply impossible to delete all the attributes of a
namespace in a single shot?

-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: obfuscate 0.2.2

2010-04-10 Thread Steven D'Aprano
I am pleased to announce the first stable release of obfuscate, 
version 0.2.2.

http://pypi.python.org/pypi/obfuscate/

obfuscate is a pure-Python module providing classical encryption
algorithms suitable for obfuscating and unobfuscating text.

This is a maintenance release of back-end and API changes but no new 
ciphers. This should be considered the first stable API for obfuscate.

obfuscate includes the following ciphers:
- rot13, rot5, rot18, rot47
- atbash
- Caesar cipher
- Keyword
- Affine
- Playfair, Playfair6, Playfair16
- frob (xor)
- Vigenere
- RailFence
- plus others.

DISCLAIMER: obfuscate is not cryptographically strong, and should not be
used where high security is required.

obfuscate is released under the MIT licence.

Requires Python 2.5 or 2.6.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Duncan Booth
vsoler  wrote:

> I get the following error message:
> 
>  TypeError: m() takes no arguments (1 given)
> 
> Since I have not created any instances of Uno, there is no self
> object, and I do not understand what object is supplied to the
> function call.
> 
> Could anybody explain what argument is being supplied to the method?
> Is ther any workaround to call the m function?
> 

Which version of Python are you using? Python 2.6 gives:

TypeError: unbound method m() must be called with Uno instance as first 
argument (got nothing instead)

whereas Python 3.1 gives:

>>> Uno.m()
mouse

(assuming you change the print statement to work on Python 3.x)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Alex Hall
On 4/10/10, vsoler  wrote:
> Still learning python, especially OOP.
>
> While testing classes, I sometimes think of them as "ordinary
> containers" of values and functions (methods). That is, values and
> functions can be grouped together inside "namespaces" calles classes.
>
> class Uno:
> a=1
> def m():
def m(self):
> print "mouse"
  print "mouse" #I believe
>
> Say that I have this "silly" class.
>
> While I can then write
>
>   print Uno.a
>
> I cannot write
>   Uno.m()
>
> I get the following error message:
>
>  TypeError: m() takes no arguments (1 given)
>
> Since I have not created any instances of Uno, there is no self
> object, and I do not understand what object is supplied to the
> function call.
I believe that self is always passed, whether you have an instance of
the uno class or not. Since you did not tell m() to expect self to be
passed to it, and self is passed anyway, m() has this self and has no
idea what to do with it. Also, you must make an uno object (u=uno())
then call methods off that object (u.m()) since not doing so means the
uno class will not get initialized.
>
> Could anybody explain what argument is being supplied to the method?
> Is ther any workaround to call the m function?
>
> Thank you
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic list reordering

2010-04-10 Thread alex23
On Apr 9, 8:52 am, Ben Racine  wrote:
> I have a list...
> ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
> 'dir_330_error.dat']
> I want to sort it based upon the numerical value only.
> Does someone have an elegant solution to this?

This approach doesn't rely on knowing the format of the string:

>>> from string import maketrans, letters, punctuation
>>> a = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
>>> 'dir_330_error.dat']
>>> def only_numbers(s):
... nums = s.translate(None, letters+punctuation)
... return int(nums)
...
>>> a.sort(key=only_numbers)
>>> a
['dir_0_error.dat', 'dir_30_error.dat', 'dir_120_error.dat',
'dir_330_error.dat']

If you're using Python 3.x, the string module has been removed, so you
can find the maketrans function on str there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic list reordering

2010-04-10 Thread MRAB

alex23 wrote:

On Apr 9, 8:52 am, Ben Racine  wrote:

I have a list...
['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
'dir_330_error.dat']
I want to sort it based upon the numerical value only.
Does someone have an elegant solution to this?


This approach doesn't rely on knowing the format of the string:


from string import maketrans, letters, punctuation
a = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
'dir_330_error.dat']
def only_numbers(s):

... nums = s.translate(None, letters+punctuation)
... return int(nums)
...

a.sort(key=only_numbers)
a

['dir_0_error.dat', 'dir_30_error.dat', 'dir_120_error.dat',
'dir_330_error.dat']

If you're using Python 3.x, the string module has been removed, so you
can find the maketrans function on str there.


The string module still exists in Python 3.x, but the string functions
which have been superseded by string methods have been removed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread vsoler
On Apr 10, 4:46 pm, Duncan Booth  wrote:
> vsoler  wrote:
> > I get the following error message:
>
> >      TypeError: m() takes no arguments (1 given)
>
> > Since I have not created any instances of Uno, there is no self
> > object, and I do not understand what object is supplied to the
> > function call.
>
> > Could anybody explain what argument is being supplied to the method?
> > Is ther any workaround to call the m function?
>
> Which version of Python are you using? Python 2.6 gives:
>
> TypeError: unbound method m() must be called with Uno instance as first
> argument (got nothing instead)
>
> whereas Python 3.1 gives:
>
> >>> Uno.m()
>
> mouse
>
> (assuming you change the print statement to work on Python 3.x)

Hello Duncan,

I am using ver 2.6, under PythonWin

The feedback that I get from python is exactly this one:

>>> print Uno.a
1
>>> Uno.m()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: m() takes no arguments (1 given)
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread vsoler
On Apr 10, 4:46 pm, Duncan Booth  wrote:
> vsoler  wrote:
> > I get the following error message:
>
> >      TypeError: m() takes no arguments (1 given)
>
> > Since I have not created any instances of Uno, there is no self
> > object, and I do not understand what object is supplied to the
> > function call.
>
> > Could anybody explain what argument is being supplied to the method?
> > Is ther any workaround to call the m function?
>
> Which version of Python are you using? Python 2.6 gives:
>
> TypeError: unbound method m() must be called with Uno instance as first
> argument (got nothing instead)
>
> whereas Python 3.1 gives:
>
> >>> Uno.m()
>
> mouse
>
> (assuming you change the print statement to work on Python 3.x)

Hello Duncan,

Your error message is correct if you use class Uno(object):
However, the error message is different underclass Uno:

Regards
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic list reordering

2010-04-10 Thread alex23
MRAB  wrote:
> The string module still exists in Python 3.x, but the string functions
> which have been superseded by string methods have been removed.

Awesome, thanks for the heads up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Laszlo Nagy



class Uno:
a=1
def m():
print "mouse"

Say that I have this "silly" class.

While I can then write

  print Uno.a

I cannot write
  Uno.m()

I get the following error message:

 TypeError: m() takes no arguments (1 given)
  

As a workaround, use this pattern:

>>> class Uno(object):
... @classmethod
... def m(cls):
... print "mouse"
...
>>> Uno.m()
mouse


Since I have not created any instances of Uno, there is no self
object, and I do not understand what object is supplied to the
function call.
  
The method is not actually called, so nothing is supplied. The error is 
raised when it turns out that the number of actual parameters and the 
number of formal parameters are different.


This is how you call a method:

#1. you try to call Uno.m() - the 'm' method object is found and taken
#2. argument values are evaluated and taken (in your example, there are 
no arguments)
#3. an extra argument is inserted in front of the argument list. This 
parameter is the object you where calling the method on. In this case, 
it is the 'Uno' class.
#4. actual arguments are assigned to formal parameters. If this fails 
for some reason, an exception is raised. In your case - the number of 
actual parameters is one, the number of formal parameters is zero. This 
is why you get an exception.
#5. If actual and formal parameters are matched, then the implicit self 
parameter is checked. If you call a method, then it must be an instance 
of the class being called (or an instanc of its subclass). For 
classmethods, it must be the same class (or a subclass of it).

#6. Function body executed, value returned

The implicit parameter (the instance, or for classmethods, the class) is 
ALWAYS added. So if you change your code:


class Uno:
   def m(self):
   pass

Then you won't get an exception in #4. But you will in #5, because 
instance methods must be called on an instance, not on a class. You can 
create a classmethod (e.g. with the @classmethod decorator) as shown 
above, and it will work.



Could anybody explain what argument is being supplied to the method?
Is ther any workaround to call the m function?

Thank you
  


--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Neil Cerutti
On 2010-04-08, Richard Lamboj  wrote:
> If someone knows good links to this thema, or can explain how
> parsers should/could work, please post it, or explain it.
>
> Thanks for the Informations and the Help!

I liked Crenshaw's "Let's Build a Compiler!". It's pretty trivial
to convert his Pascal to Python, and you'll get to basic parsing
in no time. URL:http://compilers.iecc.com/crenshaw/

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Striving for PEP-8 compliance

2010-04-10 Thread Patrick Maupin
On Apr 10, 5:10 am, Lawrence D'Oliveiro  wrote:
> In message <18988a53-e88f-4abf-
>
> a83a-314b16653...@x12g2000yqx.googlegroups.com>, Patrick Maupin wrote:
> > I want nothing to do with any programmer who would mis-indent their
> > code.
>
> But what happens when you’re trying to reconcile two different indentation
> conventions? In Python, there can be problems doing that without introducing
> logic errors. That’s what this thread is about.

Well, I think Steven pointed out how this isn't usually, really, a
problem, and I tried to point out (in a section of my posting you
didn't quote) that you will have to deal with stupid little nits in
life no matter which way you go.

Personally, for me, this particular thing is a non-issue.  If I'm
getting a code snippet from somewhere, fixing it up is not a problem,
and if I'm using a module or more from somewhere, I am not obsessive
about changing it to PEP 8.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread vsoler
On Apr 10, 5:28 pm, Laszlo Nagy  wrote:
> > class Uno:
> >     a=1
> >     def m():
> >         print "mouse"
>
> > Say that I have this "silly" class.
>
> > While I can then write
>
> >       print Uno.a
>
> > I cannot write
> >       Uno.m()
>
> > I get the following error message:
>
> >      TypeError: m() takes no arguments (1 given)
>
> As a workaround, use this pattern:
>
>  >>> class Uno(object):
> ...     @classmethod
> ...     def m(cls):
> ...             print "mouse"
> ...
>  >>> Uno.m()
> mouse
>
> > Since I have not created any instances of Uno, there is no self
> > object, and I do not understand what object is supplied to the
> > function call.
>
> The method is not actually called, so nothing is supplied. The error is
> raised when it turns out that the number of actual parameters and the
> number of formal parameters are different.
>
> This is how you call a method:
>
> #1. you try to call Uno.m() - the 'm' method object is found and taken
> #2. argument values are evaluated and taken (in your example, there are
> no arguments)
> #3. an extra argument is inserted in front of the argument list. This
> parameter is the object you where calling the method on. In this case,
> it is the 'Uno' class.
> #4. actual arguments are assigned to formal parameters. If this fails
> for some reason, an exception is raised. In your case - the number of
> actual parameters is one, the number of formal parameters is zero. This
> is why you get an exception.
> #5. If actual and formal parameters are matched, then the implicit self
> parameter is checked. If you call a method, then it must be an instance
> of the class being called (or an instanc of its subclass). For
> classmethods, it must be the same class (or a subclass of it).
> #6. Function body executed, value returned
>
> The implicit parameter (the instance, or for classmethods, the class) is
> ALWAYS added. So if you change your code:
>
> class Uno:
>     def m(self):
>         pass
>
> Then you won't get an exception in #4. But you will in #5, because
> instance methods must be called on an instance, not on a class. You can
> create a classmethod (e.g. with the @classmethod decorator) as shown
> above, and it will work.
>
> > Could anybody explain what argument is being supplied to the method?
> > Is ther any workaround to call the m function?
>
> > Thank you
>
>

Hi Laszlo,

It's perfectly clear.

Thank you very much
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Patrick Maupin
On Apr 10, 9:26 am, vsoler  wrote:

> class Uno:
>     a=1
>     def m():
>         print "mouse"
>

...

> I cannot write
>       Uno.m()

By default (at least in Python 2.x), Python will pass any function
which is accessed through getattr on class or instance (usually called
a "method") an instance of the class as the first parameter.

You can avoid this by using the @staticmethod decorator in front:

class Uno:
a = 1
@staticmethod
def m():
print "mouse"

Then you can call Uno.m() directly.

This puts a "staticmethod" wrapper around m(), which explains to the
interpreter not to try to pass it the instance variable.

Also useful is @classmethod.

Interestingly, if you don't use staticmethod, the value in the class's
dictionary is an ordinary function, but if you do use staticmethod,
you no longer have a callable function in the class's dictionary:

>>> class fred:
... def m():
...print "foo"
...
>>> fred.__dict__['m']()
foo
>>> class fred:
... @staticmethod
... def m():
...print "foo"
...
>>> fred.__dict__['m']()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'staticmethod' object is not callable


HTH,
Pat



Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


finding objects in a piece of functional code ?

2010-04-10 Thread Stef Mientki
hello,

I would like to translate some functional description into some standard
class object,
so it can be used as a basic building brick into a larger piece of code.

Suppose the functional description is:

Name = 'Test_Function'
Out = 3 * In

That's all I would like to write.
So it should be translated into something :

class Test_Function ( basic_buidling_brick ) :
Orginal_Description = """
Name = 'Test_Function'
Out = 3 * In
"""
def Run ( self, Inputs ) :
Output = 3 * Input
return Output

One of the tasks is to find all "objects" in the functional code.,
so the translator can ask additional information for input/output/memory
variables.
The best I can think of is something like this:

>>> my={}
>>> my2=copy.copy(my)
>>> exec('A=3; B=4; C=A*B; print A,B,C',my)
3 4 12
>>> for item in my :
...   if item not in my2 :
... print item
...
__builtins__
A
C
B

But this doesn't work, if I use a not yet definied variable (like "In"
in the example above).

Are there better ways ?

Or even better are there programs or libraries that can perfom such a
translation ?

thanks,
Stef Mientki


-- 
http://mail.python.org/mailman/listinfo/python-list


Tempering Client Expectations (OT)

2010-04-10 Thread Victor Subervi
Hi;
I'm working with my first client where I've developed a custom script. I way
underbid the project and I ate that as part of my learning experience. We
outlined as precisely as I knew how what functionality was needed. Then he
went to input data and lo and behold he needed more functionality. I told
him that would require more investment. This went on a few times and now
he's hopping mad about being nickeled and dimed to death. I bet this sounds
familiar to you all, doesn't it? Good thing he's also a personal friend...we
will survive this. But this red flag has caught my attention. Any good
articles out there (or other advice) on how to deal with a situation like
this?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Patrick Maupin
On Apr 8, 5:13 am, Nobody  wrote:
> On Wed, 07 Apr 2010 18:25:36 -0700, Patrick Maupin wrote:
> >> Regular expressions != Parsers
>
> > True, but lots of parsers *use* regular expressions in their
> > tokenizers.  In fact, if you have a pure Python parser, you can often
> > get huge performance gains by rearranging your code slightly so that
> > you can use regular expressions in your tokenizer, because that
> > effectively gives you access to a fast, specialized C library that is
> > built into practically every Python interpreter on the planet.

> Unfortunately, a typical regexp library (including Python's) doesn't allow
> you to match against a set of regexps, returning the index of which one
> matched. Which is what you really want for a tokeniser.

Actually, there is some not very-well-documented code in the re module
that will let you do exactly that.  But even not using that code,
using a first cut of re.split() or re.finditer() to break the string
apart into tokens (without yet classifying them) is usually a huge
performance win over anything else in the standard library (or that
you could write in pure Python) for this task.

> >> Every time someone tries to parse nested structures using regular
> >> expressions, Jamie Zawinski kills a puppy.
>
> > And yet, if you are parsing stuff in Python, and your parser doesn't
> > use some specialized C code for tokenization (which will probably be
> > regular expressions unless you are using mxtexttools or some other
> > specialized C tokenizer code), your nested structure parser will be
> > dog slow.
>
> The point is that you *cannot* match arbitrarily-nested expressions using
> regexps. You could, in theory, write a regexp which will match any valid
> syntax up to N levels of nesting, for any finite N. But in practice, the
> regexp is going to look horrible (and is probably going to be quite
> inefficient if the regexp library uses backtracking rather than a DFA).

Trust me, I already knew that.  But what you just wrote is a much more
useful thing to tell the OP than "Every time someone tries to parse
nested structures using regular expressions, Jamie Zawinski kills a
puppy" which is what I was responding to.  And right after
regurgitating that inside joke, Chris Rebert then went on to say "Try
using an *actual* parser, such as Pyparsing".  Which is all well and
good, except then the OP will download pyparsing, take a look, realize
that it uses regexps under the hood, and possibly be very confused.

> Even tokenising with Python's regexp interface is inefficient if the
> number of token types is large, as you have to test against each regexp
> sequentially.

It's not that bad if you do it right.  You can first rip things apart,
then use a dict-based scheme to categorize them.

> Ultimately, if you want an efficient parser, you need something with a C
> component, e.g. Plex.

There is no doubt that you can get better performance with C than with
Python.  But, for a lot of tasks, the Python performance is
acceptable, and, as always, algorithm, algorithm, algorithm...

A case in point.  My pure Python RSON parser is faster on my computer
on a real-world dataset of JSON data than the json decoder that comes
with Python 2.6, *even with* the json decoder's C speedups enabled.

Having said that, the current subversion pure Python simplejson parser
is slightly faster than my RSON parser, and the C reimplementation of
the parser in current subversion simplejson completely blows the doors
off my RSON parser.

So, a naive translation to C, even by an experienced programmer, may
not do as much for you as an algorithm rework.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Duncan Booth
vsoler  wrote:

> On Apr 10, 4:46 pm, Duncan Booth  wrote:
>> vsoler  wrote:
>> > I get the following error message:
>>
>> >      TypeError: m() takes no arguments (1 given)
>>

>> Which version of Python are you using? Python 2.6 gives:
>>
>> TypeError: unbound method m() must be called with Uno instance as first
>> argument (got nothing instead)
>>

 
> Hello Duncan,
> 
> Your error message is correct if you use class Uno(object):
> However, the error message is different underclass Uno:
> 

Odd. That's not what I get:

Python 2.6.1 (r26:67517, Dec  4 2008, 16:59:09) [MSC v.1500 64 bit (AMD64)] on 
win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 2.6.1  
>>> class Uno:
a=1
def m():
print "mouse"


>>> Uno.m()

Traceback (most recent call last):
  File "", line 1, in 
Uno.m()
TypeError: unbound method m() must be called with Uno instance as first 
argument (got nothing instead)
>>> 

Anyway, the moral is never, ever to use old-style classes in Python 2.x. 
You will get weird and unexpected results.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Neil Cerutti
On 2010-04-10, Patrick Maupin  wrote:
> Trust me, I already knew that.  But what you just wrote is a
> much more useful thing to tell the OP than "Every time someone
> tries to parse nested structures using regular expressions,
> Jamie Zawinski kills a puppy" which is what I was responding
> to.  And right after regurgitating that inside joke, Chris
> Rebert then went on to say "Try using an *actual* parser, such
> as Pyparsing".  Which is all well and good, except then the OP
> will download pyparsing, take a look, realize that it uses
> regexps under the hood, and possibly be very confused.

I don't agree with that. If a person is trying to ski using
pieces of wood that they carved themselves, I don't expect them
to be surprised that the skis they buy are made out of similar
materials.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer Science Practical Examination 2009" "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON http

2010-04-10 Thread saima81
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON
http://interface-edu-pk.blogspot.com/  "KARACHI UNIVERSITY
Centers of BSc (Pass) 1st/2nd year Computer Science Practical
Examination 2009"  "KARACHI UNIVERSITY DATE SHEET B.COM" "BA / B.SC"
"MA / M.SC" "FA / F.SC." "METRIC" "BOARD" ON 
http://interface-edu-pk.blogspot.com/
"KARACHI UNIVERSITY Centers of BSc (Pass) 1st/2nd year Computer
Science Practical Examination 2009"  "KARACHI UNIVERSITY DATE SHEET
B.COM" "BA / B.SC" "MA / M.SC" "FA / F.SC." "ME

Re: Cleanup guarantees?

2010-04-10 Thread Alf P. Steinbach

* Gabriel Genellina:
En Fri, 09 Apr 2010 01:13:37 -0300, Alf P. Steinbach  
escribió:


 > 
 > import urllib.request   # urlopen
 > import codecs   # getreader
 > import sys  # stderr
 >
 > def text_stream_from( url, encoding ):
 >  text_reader = codecs.getreader( encoding )
 >  connection = urllib.request.urlopen( url )
 >  return text_reader( connection )
 >
 > def list_text( url, encoding ):
 >  lines = text_stream_from( url, encoding )
 >  for line in lines:
 >  print( line, end = "" )
 >  lines.close()   # Undocumented?
 >
 > url = "http://www.rfc-editor.org/rfc/rfc1149.txt";
 > list_text( url, "ascii" )
 > 
 >
 > First, I'm unable to find documentation that there /is/ a close 
method in the
 > text_reader object, and I'm unable to find documentation that there 
is a close

 > method in the file like connection object; is there such documentation?

codecs.getreader returns a StreamReader instance (see [1])
StreamReader is documented here [2] and it says "In addition to the 
above methods, the StreamReader must also inherit all other methods and 
attributes from the underlying stream." -- the stream being 
'connection', from urllib.request.urlopen.
The 3.x version of the documentation in [3] doesn't provide any details 
except being "a file-like object". The 2.x version [4] is much more 
clear: "a file-like object is returned. This supports the following 
methods: read(), readline(), readlines(), fileno(), close(), info(), 
getcode() and geturl(). It also has proper support for the iterator 
protocol."


[1] http://docs.python.org/py3k/library/codecs.html#codecs.getreader
[2] http://docs.python.org/py3k/library/codecs.html#codecs.StreamReader
[3] 
http://docs.python.org/py3k/library/urllib.request.html#urllib.request.urlopen 


[4] http://docs.python.org/library/urllib.html#urllib.urlopen


Thanks.


 > Second, I'm unable to find documentation of when they're called and 
what they

 > do. It seems that (A) when the connection object's st
 method is called automatically, and (B) that when the
 > text_reader object's close method is called it calls the close method 
of the
 > wrapped stream (i.e. on the connection object). But where is this 
documented?


Nowhere, AFAIK.
I bet documentation patches are welcome.


Well, I think I know too little about intentions to do any documentation 
patches.


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


file events using fsevents for mac

2010-04-10 Thread gmail
Hi Everyone,

I m using python3 for my application and i need to capture file events using 
fsevents.
Is ter anyone knows to access fsevents in python3.

thanks for help in advance
rgds
mathan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Patrick Maupin
On Apr 10, 11:35 am, Neil Cerutti  wrote:
> On 2010-04-10, Patrick Maupin  wrote:
> > as Pyparsing".  Which is all well and good, except then the OP
> > will download pyparsing, take a look, realize that it uses
> > regexps under the hood, and possibly be very confused.
>
> I don't agree with that. If a person is trying to ski using
> pieces of wood that they carved themselves, I don't expect them
> to be surprised that the skis they buy are made out of similar
> materials.

But, in this case, the guy ASKED how to make the skis in his
woodworking shop, and was told not to be silly -- you don't use wood
to make skis -- and then directed to go buy some skis that are, in
fact, made out of wood.

I think it would have been perfectly appropriate to point out that it
might take some additional woodworking equipment and a bit of
experience and/or study and/or extra work to make decent skis out of
wood (and, oh, by the way, here is where you can buy some ready-made
skis cheap), but the original response didn't explain it like this.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic import ?

2010-04-10 Thread Aahz
In article <4bac361d$0$8840$c3e8...@news.astraweb.com>,
Steven D'Aprano   wrote:
>On Thu, 25 Mar 2010 18:03:58 -0700, C. B. wrote:
>> 
>> from mymodule import AAA
>> from mymodule import BBB
>> 
>> a = AAA(BBB()))
>> 
>> But, as there is no case where AAA can be used without BBB, I would like
>> to avoid importing BBB in my Python scripts when I already import AAA.
>
>Since AAA must take an argument of BBB, then give it a default:
>
># in mymodule
>def AAA(arg=BBB()):
>...

That would frequently give wrong results unless BBB is explicitly
designed to create immutable instances.  I strongly suggest doing the
usual mutable dance:

def AAA(arg=None):
if arg is None:
arg = BBB()
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Classes as namespaces?

2010-04-10 Thread Aahz
In article , kj   wrote:
>
>What's the word on using "classes as namespaces"?  E.g.
>
>class _cfg(object):
>spam = 1
>jambon = 3 
>huevos = 2
>
>breakfast = (_cfg.spam, _cfg.jambon, _cfg.huevos)

There is one gotcha associated with using classes as namespaces: you have
to be careful to avoid instantiating them.  That goes triple if you
modify the class attributes, because modifying an attribute in an
instance does *not* propagate the change to the class.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Stefan Behnel

Patrick Maupin, 10.04.2010 19:11:

On Apr 10, 11:35 am, Neil Cerutti  wrote:

On 2010-04-10, Patrick Maupin  wrote:

as Pyparsing".  Which is all well and good, except then the OP
will download pyparsing, take a look, realize that it uses
regexps under the hood, and possibly be very confused.


I don't agree with that. If a person is trying to ski using
pieces of wood that they carved themselves, I don't expect them
to be surprised that the skis they buy are made out of similar
materials.


But, in this case, the guy ASKED how to make the skis in his
woodworking shop, and was told not to be silly -- you don't use wood
to make skis -- and then directed to go buy some skis that are, in
fact, made out of wood.


Running a Python program in CPython eventually boils down to a sequence of 
commands being executed by the CPU. That doesn't mean you should write 
those commands manually, even if you can. It's perfectly ok to write the 
program in Python instead.


Stefan

--
http://mail.python.org/mailman/listinfo/python-list


[RELEASED] 2.7 beta 1

2010-04-10 Thread Benjamin Peterson
On behalf of the Python development team, I'm merry to announce the first beta
release of Python 2.7.

Python 2.7 is scheduled (by Guido and Python-dev) to be the last major version
in the 2.x series.  Though more major releases have not been absolutely ruled
out, it's likely that the 2.7 release will an extended period of maintenance for
the 2.x series.

2.7 includes many features that were first released in Python 3.1.  The faster
io module, the new nested with statement syntax, improved float repr, set
literals, dictionary views, and the memoryview object have been backported from
3.1. Other features include an ordered dictionary implementation, unittests
improvements, a new sysconfig module, and support for ttk Tile in Tkinter.  For
a more extensive list of changes in 2.7, see
http://doc.python.org/dev/whatsnew/2.7.html or Misc/NEWS in the Python
distribution.

To download Python 2.7 visit:

 http://www.python.org/download/releases/2.7/

While this is a development release and is thus not suitable for production use,
we encourage Python application and library developers to test the release with
their code and report any bugs they encounter.

The 2.7 documentation can be found at:

 http://docs.python.org/2.7

Please consider trying Python 2.7 with your code and reporting any bugs you may
notice to:

 http://bugs.python.org


Enjoy!

--
Benjamin Peterson
2.7 Release Manager
benjamin at python.org
(on behalf of the entire python-dev team and 2.7's contributors)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tempering Client Expectations (OT)

2010-04-10 Thread Tim Chase

On 04/10/2010 11:10 AM, Victor Subervi wrote:

Hi; I'm working with my first client where I've developed a
custom script. I way underbid the project and I ate that as
part of my learning experience. We outlined as precisely as I
knew how what functionality was needed. Then he went to input
data and lo and behold he needed more functionality. I told
him that would require more investment. This went on a few
times and now he's hopping mad about being nickeled and dimed
to death.


hahahaha...shocked, I say, shocked!


okay...with that out of the way...


Any good articles out there (or other advice) on how to deal
with a situation like this?


Given your track record, I'm not sure that even if folks here 
offer advice, you'll heed it.  But here goes:


1) Preeminently, address second-order ignorance.  Learn about the 
involved technologies before you consider proposing a solution. 
Had you taken the time up-front to ask any competent web 
developer "I'd like to make a web-application from scratch, what 
do I need to know?" they'd tell you to learn HTTP, HTML, CSS, 
Javascript, a server-side scripting language such as 
Python/PHP/Perl/Ruby, database/SQL technologies, and security 
best-practices (or they might question why you don't reuse an 
existing framework that already does what you want).  There are 
plenty of books & websites to facilitate learning *all* of these 
topics.  GIYF.  That list alone might have given you pause enough 
to say "woah, that's a lot, and all I know is a little HTML. 
Maybe the task of being a web programmer isn't as easy as I 
thought."  But, in the face of the daunting mountain of requisite 
skills, you opt to proceed...


2) Next, address first-order ignorance:  learn the requisite 
technologies involved in such a project.  Learn HTML, CSS, 
Javascript, how an HTTP transaction works, how to program well in 
your chosen scripting language, how to write SQL, and how to 
identify common security issues (OWASP puts out a good list).


This doesn't preclude you from doing paid projects for friends as 
you learn, but keep the funding down in the "buy me lunch and 
I'll tinker with your idea" range, not in the "pay me real money 
for a real application" range.  Make sure that the friend knows 
your level of experience (or lack thereof) doing what they want. 
 And don't fudge it with "I wrote this other web application" 
eliding the fact that said-web-app blew up in your face.  Be 
honest.  All artists need to master their tools, whether words, 
pigments, clay, or technologies.


3) When multiple professional-programmers on comp.lang.python 
face-palm and suggest you're doing something wrong or you lack an 
understanding, try listening and spending time to wrap your head 
around what they're saying.  Instead of dismissing with "I'm an 
artist, I can't understand that", STOP.  Let you client know you 
just stepped off the deep end, and suspend the project.  Hire 
somebody who does understand or take a class (this may cost real 
money).  But don't try and proceed in the face as your own 
non-understanding without first coming to terms with the issue.


4) Don't be afraid to reuse existing technologies:  could 
installing osCommerce on a $3/month web-server and tweaking the 
PHP code have sufficed for what you need?  Could you have used 
Django+Satchmo to get yourself up and running with proven code, 
tweaking what you need?  I remember you dismissing the suggestion 
to use existing web-frameworks.


5) Regarding scope-creep, it's a problem most developers & 
analysts face, but there are several mitigating methods you can 
use.  Experience from past projects helps gauge time for future 
projects and only your own experience will suffice.  If you don't 
have any past projects (personal deployments or school projects) 
you're not yet remotely ready to give estimates.  Even after 
you've done multiple projects, estimation is still as much an art 
as a science.


Also, get the client to sign off on basic features in very small 
bite-sized increments, addressing highest-priority needs first. 
If at any time the client sees a failure to progress at the rate 
they expect, they can pull the plug losing far less of their 
investment keeping the most important features developed 
thus-far.  Part of a developer/analyst's job is to get a good 
idea of a project's scope.  Examining all edge cases, looking for 
infrequently-used processes, probing exceptions, building a 
mental-model that corresponds to the client's mental-model...


6) As for "Tempering Client Expectations" (the subject line of 
this OT post), it seems the biggest gap involved not 
communicating to your client/friend "I'm using your project as a 
learning experience for multiple complicated technologies and I 
have minimal idea what is involved so there's no possible way I 
could give you an accurate estimate of scope or cost"


-tkc





--
http://mail.python.org/mailman/listinfo/python-list


bps coordinate identification

2010-04-10 Thread Luis Quesada

Dear all,
Given a gps coordinate, I would like to find out the country the 
coordinate belongs to. I wonder whether there is a python library that 
offers this capability...

Thanks in advance for any pointer.
Cheers,
Luis
PS: I am already aware of basemap but it seems we cannot answer this 
type of query with it.

--
http://mail.python.org/mailman/listinfo/python-list


Re: The Regex Story

2010-04-10 Thread Dotan Cohen
> Unreasonable phobia to regex is just as much harmful as overuse of it.
>

Agreed. I did not mean to sound as if I am against the use of regular
expressions.

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread Paul Rubin
Steven D'Aprano  writes:
> DISCLAIMER: obfuscate is not cryptographically strong, and should not be
> used where high security is required.

Certainly no one should never use obfuscate's rot13 function for high
security.  Use at least double-rot13 instead, or maybe even quadruple
rot13 ;-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] 2.7 beta 1

2010-04-10 Thread average
> On behalf of the Python development team, I'm merry to announce the first beta
> release of Python 2.7.
>
> Python 2.7 is scheduled (by Guido and Python-dev) to be the last major version
> in the 2.x series.  Though more major releases have not been absolutely ruled
> out, it's likely that the 2.7 release will an extended period of maintenance 
> for
> the 2.x series.

May I propose that the developers consider keeping this release *beta*
until after the present Python moratorium?  That is, don't let it be
marked as *official* until after, say, Python 3.3.

There are so many features taken from 3.0 that I fear that it will
postpone its adoption interminably (it is, in practice, treated as
"beta" software itself).  By making it doctrine that it won't be
official until the next "major" Python release, it will encourage
those who are able, to just make the jump to 3.0, while those who
cannot will have the subtle pressure to make the shift, however
gradual.  Additionally, it will give the community further incentive
to make Python3 all that it was intended to be.  Personally, the
timing of v3 prevented me from fully participating in that effort,
and, not ignoring the work of those who did contribute, I think many
of us feel that it has not reached its potential.

Just a small suggestion... .. .

marcos
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] 2.7 beta 1

2010-04-10 Thread Melton Low
On Sat, Apr 10, 2010 at 4:13 PM, average  wrote:

> > On behalf of the Python development team, I'm merry to announce the first
> beta
> > release of Python 2.7.
> >
> > Python 2.7 is scheduled (by Guido and Python-dev) to be the last major
> version
> > in the 2.x series.  Though more major releases have not been absolutely
> ruled
> > out, it's likely that the 2.7 release will an extended period of
> maintenance for
> > the 2.x series.
>
> May I propose that the developers consider keeping this release *beta*
> until after the present Python moratorium?  That is, don't let it be
> marked as *official* until after, say, Python 3.3.
>
> There are so many features taken from 3.0 that I fear that it will
> postpone its adoption interminably (it is, in practice, treated as
> "beta" software itself).  By making it doctrine that it won't be
> official until the next "major" Python release, it will encourage
> those who are able, to just make the jump to 3.0, while those who
> cannot will have the subtle pressure to make the shift, however
> gradual.  Additionally, it will give the community further incentive
> to make Python3 all that it was intended to be.  Personally, the
> timing of v3 prevented me from fully participating in that effort,
> and, not ignoring the work of those who did contribute, I think many
> of us feel that it has not reached its potential.
>
> Just a small suggestion... .. .
>
> marcos
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I disagree.  2.7 should go GA as soon as the developers deemed it stable.

Those who don't need 3rd party packages will no doubt migrate to 3.x.  Those
that required 3rd party packages not yet ported to 3.x will want to use 2.7.
 Delaying 2.7 from GA doesn't change the reality.  I myself would want to
use back ported features from 2.7 as a way to prepare for migration as soon
as those 3rd party packages are ported to 3.x.

Mel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] 2.7 beta 1

2010-04-10 Thread Michael Ströder
average wrote:
>> On behalf of the Python development team, I'm merry to announce the first 
>> beta
>> release of Python 2.7.
>>
>> Python 2.7 is scheduled (by Guido and Python-dev) to be the last major 
>> version
>> in the 2.x series.  Though more major releases have not been absolutely ruled
>> out, it's likely that the 2.7 release will an extended period of maintenance 
>> for
>> the 2.x series.
> 
> May I propose that the developers consider keeping this release *beta*
> until after the present Python moratorium?  That is, don't let it be
> marked as *official* until after, say, Python 3.3.
> 
> There are so many features taken from 3.0 that I fear that it will
> postpone its adoption interminably

Whether 3.x is adopted by developers is IMO not influenced by the 2.7 release
schedule. At least the effect is highly speculative. So please simply release
2.7 when it's ready.

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [RELEASED] 2.7 beta 1

2010-04-10 Thread Mensanator
On Apr 10, 5:45 pm, Michael Ströder  wrote:
> average wrote:
> >> On behalf of the Python development team, I'm merry to announce the first 
> >> beta
> >> release of Python 2.7.
>
> >> Python 2.7 is scheduled (by Guido and Python-dev) to be the last major 
> >> version
> >> in the 2.x series.  Though more major releases have not been absolutely 
> >> ruled
> >> out, it's likely that the 2.7 release will an extended period of 
> >> maintenance for
> >> the 2.x series.
>
> > May I propose that the developers consider keeping this release *beta*
> > until after the present Python moratorium?  That is, don't let it be
> > marked as *official* until after, say, Python 3.3.
>
> > There are so many features taken from 3.0 that I fear that it will
> > postpone its adoption interminably
>
> Whether 3.x is adopted by developers is IMO not influenced by the 2.7 release
> schedule. At least the effect is highly speculative. So please simply release
> 2.7 when it's ready.

3.x won't be adopted by developers until it's fixed. As of now, it's
seriously broken and unsuitable for production.

>
> Ciao, Michael.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [RELEASED] 2.7 beta 1

2010-04-10 Thread Chris Rebert
On Sat, Apr 10, 2010 at 4:47 PM, Mensanator  wrote:
> On Apr 10, 5:45 pm, Michael Ströder  wrote:
>> average wrote:
>> >> On behalf of the Python development team, I'm merry to announce the first 
>> >> beta
>> >> release of Python 2.7.
>>
>> >> Python 2.7 is scheduled (by Guido and Python-dev) to be the last major 
>> >> version
>> >> in the 2.x series.  Though more major releases have not been absolutely 
>> >> ruled
>> >> out, it's likely that the 2.7 release will an extended period of 
>> >> maintenance for
>> >> the 2.x series.
>>
>> > May I propose that the developers consider keeping this release *beta*
>> > until after the present Python moratorium?  That is, don't let it be
>> > marked as *official* until after, say, Python 3.3.
>>
>> > There are so many features taken from 3.0 that I fear that it will
>> > postpone its adoption interminably
>>
>> Whether 3.x is adopted by developers is IMO not influenced by the 2.7 release
>> schedule. At least the effect is highly speculative. So please simply release
>> 2.7 when it's ready.
>
> 3.x won't be adopted by developers until it's fixed. As of now, it's
> seriously broken and unsuitable for production.

In what ways do you consider it broken?

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Ethan Furman

Stefan Behnel wrote:

Patrick Maupin, 10.04.2010 19:11:


On Apr 10, 11:35 am, Neil Cerutti  wrote:


On 2010-04-10, Patrick Maupin  wrote:


as Pyparsing".  Which is all well and good, except then the OP
will download pyparsing, take a look, realize that it uses
regexps under the hood, and possibly be very confused.



I don't agree with that. If a person is trying to ski using
pieces of wood that they carved themselves, I don't expect them
to be surprised that the skis they buy are made out of similar
materials.



But, in this case, the guy ASKED how to make the skis in his
woodworking shop, and was told not to be silly -- you don't use wood
to make skis -- and then directed to go buy some skis that are, in
fact, made out of wood.



Running a Python program in CPython eventually boils down to a sequence 
of commands being executed by the CPU. That doesn't mean you should 
write those commands manually, even if you can. It's perfectly ok to 
write the program in Python instead.


Stefan


And it's even more perfectly okay to use Python when it's the best tool 
for the job, and re when *it's* the best tool for the job.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: On Class namespaces, calling methods

2010-04-10 Thread Steven D'Aprano
On Sat, 10 Apr 2010 16:35:29 +, Duncan Booth wrote:

> Anyway, the moral is never, ever to use old-style classes in Python 2.x.
> You will get weird and unexpected results.

That's a bit strong. They're only weird and unexpected if you're not 
expecting them and don't understand them.

Why are we worrying about the exact error message? New style or old 
style, they both raise TypeError, and testing for the exact error message 
is a fragile, dangerous thing to do: error strings are not part of the 
Python API, and are subject to change without notice, for any reason. For 
all we know, Python runtimes compiled on a Tuesday could use different 
error messages from runtimes compiled on Wednesdays.

I can only think of two circumstances where old-style classes are 
*wrong*: if you use multiple inheritance with a diamond diagram ("...now 
you have THREE problems" *wink*), if you intend using descriptors such as 
properties, or if you need __slots__. That's three circumstances: 
multiple inheritance with a diamond diagram, descriptors, __slots__, and 
__getattribute__. Four circumstances.

Any other time, they're merely discouraged, and gone in Python 3.x.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread Steven D'Aprano
On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> DISCLAIMER: obfuscate is not cryptographically strong, and should not
>> be used where high security is required.
> 
> Certainly no one should never use obfuscate's rot13 function for high
> security.  Use at least double-rot13 instead, or maybe even quadruple
> rot13 ;-).

Ha ha, that's funny! I've never heard that one before! *wink*

I may add a quadruple-rot13 to the next release. Would you like credit?

obfuscate does include ciphers which, prior to the invention of the 
computer, were good enough for real world use. E.g. the Playfair cipher 
was still in use for field communications in World War 2, e.g:

http://practicalcryptography.com/ciphers/playfair-cipher/

and of course Vigenere is uncrackable if you provide it with a 
cryptographically random key as long as the message which you use only 
once. (In that case, it is a one-time-pad.)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Steven D'Aprano
On Sat, 10 Apr 2010 10:11:07 -0700, Patrick Maupin wrote:

> On Apr 10, 11:35 am, Neil Cerutti  wrote:
>> On 2010-04-10, Patrick Maupin  wrote:
>> > as Pyparsing".  Which is all well and good, except then the OP will
>> > download pyparsing, take a look, realize that it uses regexps under
>> > the hood, and possibly be very confused.
>>
>> I don't agree with that. If a person is trying to ski using pieces of
>> wood that they carved themselves, I don't expect them to be surprised
>> that the skis they buy are made out of similar materials.
> 
> But, in this case, the guy ASKED how to make the skis in his woodworking
> shop, and was told not to be silly -- you don't use wood to make skis --
> and then directed to go buy some skis that are, in fact, made out of
> wood.

As entertaining as this is, the analogy is rubbish. Skis are far too 
simple to use as an analogy for a parser (he says, having never seen skis 
up close in his life *wink*). Have you looked at PyParsing's source code? 
Regexes are only a small part of the parser, and not analogous to the 
wood of skis.

Perhaps a better analogy would be a tennis racket, with regexes being the 
strings. You have a whole lot of strings, not just one, and they are held 
together with a strong framework. Without the framework the strings are 
useless, and without the strings the racket doesn't do anything useful.

Using this analogy, I would say the OP was wanting to play tennis with a 
single piece of string, and asking for advise on beefing it up to make it 
work better. Perhaps a knot tied in one end will help?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-10 Thread Terry Reedy

On 4/10/2010 8:32 AM, Stefan Behnel wrote:

Steven D'Aprano, 08.04.2010 03:41:

On Wed, 07 Apr 2010 10:55:10 -0700, Raymond Hettinger wrote:



If the two collections have unequal sizes, then both ways immediately
return unequal.



Perhaps I'm misinterpreting what you are saying, but I can't confirm that
behaviour, at least not for subclasses of list:

>>> class MyList(list):
... def __len__(self):
... return self.n
...
>>> L1 = MyList(range(10))
>>> L2 = MyList(range(10))
>>> L1.n = 9
>>> L2.n = 10
>>> L1 == L2
True
>>> len(L1) == len(L2)
False


This code incorrectly assumes that overriding __len__ has an impact on
the equality of two lists. If you want to influence the equality, you
need to override __eq__. If you don't, the original implementation is
free to do whatever it likes to determine if it is equal to another
value or not. If it uses __len__ for that or not is only an
implementation detail that can't be relied upon.


After reading the responses of both you and Raymond, I realized that a) 
there is a real difference between 'checking lengths' and 'calling 
__len__', which I (and apparently the example) had seen as the same and 
b) that the example shows that assuming that they are the same is a 
mistake. Thank you both for the clarification.


Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Paul Rubin
Steven D'Aprano  writes:
> As entertaining as this is, the analogy is rubbish. Skis are far too 
> simple to use as an analogy for a parser (he says, having never seen skis 
> up close in his life *wink*). Have you looked at PyParsing's source code? 
> Regexes are only a small part of the parser, and not analogous to the 
> wood of skis.

The impression that I have (from a distance) is that Pyparsing is a good
interface abstraction with a kludgy and slow implementation.  That the
implementation uses regexps just goes to show how kludgy it is.  One
hopes that someday there will be a more serious implementation, perhaps
using llvm-py (I wonder whatever happened to that project, by the way)
so that your parser script will compile to executable machine code on
the fly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread geremy condra
On Sun, Apr 11, 2010 at 1:17 AM, Steven D'Aprano
 wrote:
> On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:
>
>> Steven D'Aprano  writes:
>>> DISCLAIMER: obfuscate is not cryptographically strong, and should not
>>> be used where high security is required.
>>
>> Certainly no one should never use obfuscate's rot13 function for high
>> security.  Use at least double-rot13 instead, or maybe even quadruple
>> rot13 ;-).
>
> Ha ha, that's funny! I've never heard that one before! *wink*

I think I lost a sarcasm detector to this line- are you being serious?

Geremy Condra
-- 
http://mail.python.org/mailman/listinfo/python-list


doctest.testfile fails on text files with Windows line endings

2010-04-10 Thread Steven D'Aprano
After converting a text file containing doctests to use Windows line 
endings, I'm getting spurious errors:

ValueError: line 19 of the docstring for examples.txt has inconsistent 
leading whitespace: '\r'


I don't believe that doctest.testfile is documented as requiring Unix 
line endings, and the line endings in the file are okay. I've checked in 
a hex editor, and they are valid \r\n line endings.

In doctest._load_testfile, I find this comment and code:

# get_data() opens files as 'rb', so one must do the equivalent
# conversion as universal newlines would do.
return file_contents.replace(os.linesep, '\n'), filename

which I read as an attempt to normalise line endings in the file to \n.

(But surely this will fail? If you're running, say, Linux or MacOS, 
linesep will already be '\n' not '\r\n', and consequently the replace 
does nothing, any Windows line endings aren't normalised, and doctest 
will choke on the \r characters. It's only useful if running on Windows.)

But the above only occurs when using a package loader. Otherwise, 
_load_testfile executes:

return open(filename).read(), filename

which doesn't do any line ending normalisation at all.

To my mind, this is a bug in doctest. Does anyone disagree? I think the 
simplest fix is to change it to:

return open(filename, 'rU').read(), filename


Comments?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread Steven D'Aprano
On Sun, 11 Apr 2010 03:00:50 +, geremy condra wrote:

> On Sun, Apr 11, 2010 at 1:17 AM, Steven D'Aprano
>  wrote:
>> On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:
>>
>>> Steven D'Aprano  writes:
 DISCLAIMER: obfuscate is not cryptographically strong, and should not
 be used where high security is required.
>>>
>>> Certainly no one should never use obfuscate's rot13 function for high
>>> security.  Use at least double-rot13 instead, or maybe even quadruple
>>> rot13 ;-).
>>
>> Ha ha, that's funny! I've never heard that one before! *wink*
> 
> I think I lost a sarcasm detector to this line- are you being serious?


Possibly I overloaded your sarcasm detector and broke it.

No, I'm not serious. If I had a dollar for every time somebody suggested 
using rot13 twice for extra security, I could buy out Microsoft.

Hell, if I had a dollar for every time *I* suggested using rot13 twice, I 
could buy out Google.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


[Possibly OT] Comments on PyPI

2010-04-10 Thread Steven D'Aprano
How do I leave comments on PyPI? There's a checkbox "Allow comments on 
releases" which I have checked, but no obvious way to actually post a 
comment.

There's a link on the sidebar called "Comments", but it goes to a page 
about the Catalog SIG.

I know there was a push to remove comments from PyPI last year, but the 
poll came back (marginally) in favour of keeping them.

http://old.nabble.com/Poll-results-td26597897.html


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: daemon.DaemonContext and logging

2010-04-10 Thread Ben Finney
Sean DiZazzo  writes:

> I'm finally getting around to trying out the python-daemon module and
> have hit a wall.  I'm trying to set up logging inside of the "with
> daemon.DaemonContext" block.  But when I try to use a logger inside
> the block it throws an error:

Specifically, it's throwing an error because a logger set up *outside*
the context is no longer open *inside* the context.

[…]
> handler = logging.FileHandler("log.file")
> logger.addHandler(handler)
>
> pid = daemon.pidlockfile.TimeoutPIDLockFile("/var/run/daemontest.pid",
> 10)
>
> with daemon.DaemonContext(pidfile=pid, gid=0, uid=0,
> stdout=sys.stdout, stderr=sys.stderr):
> logger.info("POO")

Here, the daemon.DaemonContext has not been told to preserve the file
descriptor that was opened by ‘handler’; so that file descriptor gets
closed along with all the others when the DaemonContext opens.

Also, there's no point binding the ‘stdout’ and ‘stderr’ options to the
system streams as you've done: as the documentation specifies, becoming
a daemon process involves detaching from the controlling terminal, so
those streams will no longer be connected to anything.

If you want specific file descriptors to remain open, you need to tell
the DaemonContext which ones they are via the ‘files_preserve’ option:

#! /usr/bin/python
# -*- coding: utf-8; -*-

from __future__ import with_statement

import logging
import daemon
import daemon.pidlockfile
import sys

logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("log.file")
logger.addHandler(handler)

pid = daemon.pidlockfile.TimeoutPIDLockFile(
"/tmp/dizazzo-daemontest.pid", 10)

daemon_context = daemon.DaemonContext(
pidfile=pid,
files_preserve=[handler.stream])

with daemon_context:
logger.info("POO")

Thanks for this question; it's now in the FAQ document for the next
version.

> Any advice? Also, I left in the call to TimeoutPIDLockfile() as well,
> because the library's documentation is pretty sparse, and I want to
> know if I'm using it properly.

Improvements to the documentation would be welcome, certainly.

-- 
 \ “We now have access to so much information that we can find |
  `\  support for any prejudice or opinion.” —David Suzuki, 2008-06-27 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest.testfile fails on text files with Windows line endings

2010-04-10 Thread Patrick Maupin
On Apr 10, 10:16 pm, Steven D'Aprano  wrote:
> After converting a text file containing doctests to use Windows line
> endings, I'm getting spurious errors:
>
> ValueError: line 19 of the docstring for examples.txt has inconsistent
> leading whitespace: '\r'
>
> I don't believe that doctest.testfile is documented as requiring Unix
> line endings, and the line endings in the file are okay. I've checked in
> a hex editor, and they are valid \r\n line endings.
>
> In doctest._load_testfile, I find this comment and code:
>
>     # get_data() opens files as 'rb', so one must do the equivalent
>     # conversion as universal newlines would do.
>     return file_contents.replace(os.linesep, '\n'), filename
>
> which I read as an attempt to normalise line endings in the file to \n.
>
> (But surely this will fail? If you're running, say, Linux or MacOS,
> linesep will already be '\n' not '\r\n', and consequently the replace
> does nothing, any Windows line endings aren't normalised, and doctest
> will choke on the \r characters. It's only useful if running on Windows.)
>
> But the above only occurs when using a package loader. Otherwise,
> _load_testfile executes:
>
>     return open(filename).read(), filename
>
> which doesn't do any line ending normalisation at all.
>
> To my mind, this is a bug in doctest. Does anyone disagree? I think the
> simplest fix is to change it to:
>
>     return open(filename, 'rU').read(), filename
>
> Comments?
>
> --
> Steven

Seems like a bug to me.  I often assume that I don't know where a
string is coming from, so one of the first steps I usually take when
parsing a string is:

s = s.replace('\r\n', '\n').replace('\r', '\n')

And, out of long-standing pre-Python habit, I always open files in
binary mode and then have my way with them.  I know universal mode is
available, but honestly, I don't care for all the bookkeeping on what
kinds of line endings have been seen -- I just want to normalize the
data.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.7 beta 1

2010-04-10 Thread Mensanator
On Apr 10, 7:15�pm, Chris Rebert  wrote:
> On Sat, Apr 10, 2010 at 4:47 PM, Mensanator  wrote:
> > On Apr 10, 5:45�pm, Michael Str�der  wrote:
> >> average wrote:
> >> >> On behalf of the Python development team, I'm merry to announce the 
> >> >> first beta
> >> >> release of Python 2.7.
>
> >> >> Python 2.7 is scheduled (by Guido and Python-dev) to be the last major 
> >> >> version
> >> >> in the 2.x series. �Though more major releases have not been absolutely 
> >> >> ruled
> >> >> out, it's likely that the 2.7 release will an extended period of 
> >> >> maintenance for
> >> >> the 2.x series.
>
> >> > May I propose that the developers consider keeping this release *beta*
> >> > until after the present Python moratorium? �That is, don't let it be
> >> > marked as *official* until after, say, Python 3.3.
>
> >> > There are so many features taken from 3.0 that I fear that it will
> >> > postpone its adoption interminably
>
> >> Whether 3.x is adopted by developers is IMO not influenced by the 2.7 
> >> release
> >> schedule. At least the effect is highly speculative. So please simply 
> >> release
> >> 2.7 when it's ready.
>
> > 3.x won't be adopted by developers until it's fixed. As of now, it's
> > seriously broken and unsuitable for production.
>
> In what ways do you consider it broken?

Issue 8093. Remarkably, this apparently hasn't been noticed before.
I expect 2.7 will be around for a long time.

>
> Cheers,
> Chris- Hide quoted text -
>
> - Show quoted text -

-- 
http://mail.python.org/mailman/listinfo/python-list


SEC proposes the use of Python and XML

2010-04-10 Thread Ted Larson Freeman
This week the SEC proposed new requirements for asset-backed
securities that include the use of XML and Python:

"The asset-level information would be provided according to proposed
standards and in a tagged data format using eXtensible Markup Language
(XML). In addition, we are proposing to require, along with the
prospectus filing, the filing of a computer program of the contractual
cash flow provisions expressed as downloadable source code in Python,
a commonly used open source interpretive programming language."

See:
http://www.sec.gov/news/press/2010/2010-54.htm
http://kelloggfinance.wordpress.com/2010/04/08/the-sec-gets-one-right

Ted
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Paul McGuire
On Apr 10, 8:38 pm, Paul Rubin  wrote:
> The impression that I have (from a distance) is that Pyparsing is a good
> interface abstraction with a kludgy and slow implementation.  That the
> implementation uses regexps just goes to show how kludgy it is.  One
> hopes that someday there will be a more serious implementation, perhaps
> using llvm-py (I wonder whatever happened to that project, by the way)
> so that your parser script will compile to executable machine code on
> the fly.

I am definitely flattered that pyparsing stirs up so much interest,
and among such a distinguished group. But I have to take some umbrage
at Paul Rubin's left-handed compliment,  "Pyparsing is a good
interface abstraction with a kludgy and slow implementation,"
especially since he forms his opinions "from a distance".

I actually *did* put some thought into what I wanted in pyparsing
before designing it, and this forms this chapter of "Getting Started
with Pyparsing" (available here as a free online excerpt:
http://my.safaribooksonline.com/9780596514235/what_makes_pyparsing_so_special#X2ludGVybmFsX0ZsYXNoUmVhZGVyP3htbGlkPTk3ODA1OTY1MTQyMzUvMTYmaW1hZ2VwYWdlPTE2),
the "Zen of Pyparsing" as it were. My goals were:

- build parsers using explicit constructs (such as words, groups,
repetition, alternatives), vs. expression encoding using specialized
character sequences, as found in regexen

- easy parser construction from primitive elements to complex groups
and alternatives, using Python's operator overloading for ease of
direct implementation of parsers using ordinary Python syntax; include
mechanisms for defining recursive parser expressions

- implicit skipping of whitespace between parser elements

- results returned not just as a list of strings, but as a rich data
object, with access to parsed fields by name or by list index, taking
interfaces from both dicts and lists for natural adoption into common
Python idioms

- no separate code-generation steps, a la lex/yacc

- support for parse-time callbacks, for specialized token handling,
conversion, and/or construction of data structures

- 100% pure Python, to be runnable on any platform that supports
Python

- liberal licensing, to permit easy adoption into any user's projects
anywhere

So raw performance really didn't even make my short-list, beyond the
obvious "should be tolerably fast enough."

I have found myself reading posts on c.l.py with wording like "I'm
trying to parse  and I've been trying for hours/days to get
this regex working."  For kicks, I'd spend 5-15 minutes working up a
working pyparsing solution, which *does* run comparatively slowly,
perhaps taking a few minutes to process the poster's data file.  But
the net solution is developed and running in under 1/2 an hour, which
to me seems like an overall gain compared to hours of fruitless
struggling with backslashes and regex character sequences.  On top of
which, the pyparsing solutions are still readable when I come back to
them weeks or months later, instead of staring at some line-noise
regex and just scratch my head wondering what it was for.  And
sometimes "comparatively slowly" means that it runs 50x slower than a
compiled method that runs in 0.02 seconds - that's still getting the
job done in just 1 second.

And is the internal use of regexes with pyparsing really a "kludge"?
Why? They are almost completely hidden from the parser developer. And
yet by using compiled regexes, I retain the portability of 100% Python
while leveraging the compiled speed of the re engine.

It does seem that there have been many posts of late (either on c.l.py
or the related posts on Stackoverflow) where the OP is trying to
either scrape content from HTML, or parse some type of recursive
expression.  HTML scrapers implemented using re's are terribly
fragile, since HTML in the wild often contains little surprises
(unexpected whitespace; upper/lower case inconsistencies; tag
attributes in unpredictable order; attribute values with double,
single, or no quotation marks) which completely frustrate any re-based
approach.  Granted, there are times when an re-parsing-of-HTML
endeavor *isn't* futile or doomed from the start - the OP may be
working with a very restricted set of HTML, generated from some other
script so that the output is very consistent. Unfortunately, this
poster usually gets thrown under the same "you'll never be able to
parse HTML with re's" bus. I can't explain the surge in these posts,
other than to wonder if we aren't just seeing a skewed sample - that
is, the many cases where people *are* successfully using re's to solve
their text extraction problems aren't getting posted to c.l.py, since
no one posts questions they already have the answers to.

So don't be too dismissive of pyparsing, Mr. Rubin. I've gotten many e-
mails, wiki, and forum posts from Python users at all levels of the
expertise scale, saying that pyparsing has helped them to be very
productive in one or another aspect of creating a command parse

Re: ANN: obfuscate 0.2.2

2010-04-10 Thread Aahz
In article ,
geremy condra   wrote:
>On Sun, Apr 11, 2010 at 1:17 AM, Steven D'Aprano
> wrote:
>> On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:
>>> Steven D'Aprano  writes:

 DISCLAIMER: obfuscate is not cryptographically strong, and should not
 be used where high security is required.
>>>
>>> Certainly no one should never use obfuscate's rot13 function for high
>>> security. Use at least double-rot13 instead, or maybe even quadruple
>>> rot13 ;-).
>>
>> Ha ha, that's funny! I've never heard that one before! *wink*
>
>I think I lost a sarcasm detector to this line- are you being serious?

There are people who have a .sig that says, "This message protected by
double-rot13 for extra security."  It's an extremely common jape.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread geremy condra
On Sun, Apr 11, 2010 at 3:44 AM, Steven D'Aprano
 wrote:
> On Sun, 11 Apr 2010 03:00:50 +, geremy condra wrote:
>
>> On Sun, Apr 11, 2010 at 1:17 AM, Steven D'Aprano
>>  wrote:
>>> On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:
>>>
 Steven D'Aprano  writes:
> DISCLAIMER: obfuscate is not cryptographically strong, and should not
> be used where high security is required.

 Certainly no one should never use obfuscate's rot13 function for high
 security.  Use at least double-rot13 instead, or maybe even quadruple
 rot13 ;-).
>>>
>>> Ha ha, that's funny! I've never heard that one before! *wink*
>>
>> I think I lost a sarcasm detector to this line- are you being serious?
>
>
> Possibly I overloaded your sarcasm detector and broke it.

I figured, but given how severely it broke I couldn't be sure.
I suppose the fact that you used exclamation points should
have tipped me off, though.

Geremy Condra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: obfuscate 0.2.2

2010-04-10 Thread geremy condra
On Sun, Apr 11, 2010 at 4:37 AM, Aahz  wrote:
> In article ,
> geremy condra   wrote:
>>On Sun, Apr 11, 2010 at 1:17 AM, Steven D'Aprano
>> wrote:
>>> On Sat, 10 Apr 2010 13:34:17 -0700, Paul Rubin wrote:
 Steven D'Aprano  writes:
>
> DISCLAIMER: obfuscate is not cryptographically strong, and should not
> be used where high security is required.

 Certainly no one should never use obfuscate's rot13 function for high
 security. Use at least double-rot13 instead, or maybe even quadruple
 rot13 ;-).
>>>
>>> Ha ha, that's funny! I've never heard that one before! *wink*
>>
>>I think I lost a sarcasm detector to this line- are you being serious?
>
> There are people who have a .sig that says, "This message protected by
> double-rot13 for extra security."  It's an extremely common jape.

I work in infosec. I've heard it ;)

Geremy Condra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.7 beta 1

2010-04-10 Thread alex23
Mensanator  wrote:
> 3.x won't be adopted by WINDOWS developers WHO USE IDLE until it's fixed.

I think you left your hyperbole level too high so I turned it down for
you. I don't know of _anyone_ who uses IDLE to run production code,
nor do I follow how one errant IDE shows that Python 3.x as a language
is broken.
-- 
http://mail.python.org/mailman/listinfo/python-list


Error Occurs: Replace a character in a String

2010-04-10 Thread Jimbo
Hello, I am getting an error in my python script when I try to change
a character in a string. [b]But I dont know why or what to do to fix
it?[/b]

I have commented in my code where the error occurs

[code]
def format_file(filename):

HTML_file   = open(filename,'r')
HTML_source = HTML_file.read()
HTML_file.close()

x = 0

# Format all ID's & classes correctly
temp_buf= HTML_source.lower()
class_occurence = temp_buf.count('class')
ID_occurence= temp_buf.count('id')

for n in range(class_occurence):
hit = temp_buf.find('class')
if not hit==-1:
temp_buf[hit] = '~' # Error: 'str' object does not support
item assignment
x = hit+5

# delete any spaces until we reach a letter or number
while xhttp://mail.python.org/mailman/listinfo/python-list


Re: Error Occurs: Replace a character in a String

2010-04-10 Thread Steven D'Aprano
On Sat, 10 Apr 2010 22:01:51 -0700, Jimbo wrote:

> Hello, I am getting an error in my python script when I try to change a
> character in a string. [b]But I dont know why or what to do to fix
> it?[/b]
> 
> I have commented in my code where the error occurs

Generally speaking, posting the actual error (not retyping it from 
memory, or summarising it, or eluding to something vaguely similar) is 
recommended. In this case though, your error is simple enough that you 
can get away without the full traceback:


> temp_buf[hit] = '~'
> # Error: 'str' object does not support item assignment

The error is exactly what it says: strings don't support item assignment.

Try this in an interactive session:

>>> s = 'abcd'
>>> s[1] = 'B'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

Just as it says: you can't assign to individual string items (characters).

This is because strings in Python are immutable -- once created, you 
can't modify them. There are all sorts of reasons for this, which I won't 
go into, but the consequence is that anytime you want to modify a string 
you need to create a new one:

>>> s = s[0] + 'B' + s[2:]
>>> s
'aBcd'

But don't do the above! String concatenation is okay if you only do it 
once or twice, but if you're doing a lot of it, your code will be 
sloow. Best to avoid it whenever possible.

The best way to replace substrings is, not surprisingly, to use the 
replace() method:

>>> print s.replace('B', '~')
a~cd

Or break the string up into a list of words:

words = mystring.split()

or a list of characters:

chars = list(mystring)

and operate on the list. Lists, unlike strings, are mutable and so you 
can assign to items.

But I see you're trying to manually parse HTML. Have you considered using 
the HTML parser that comes with Python?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SEC proposes the use of Python and XML

2010-04-10 Thread Chris Rebert
On Sat, Apr 10, 2010 at 9:13 PM, Ted Larson Freeman
 wrote:
> This week the SEC proposed new requirements for asset-backed
> securities that include the use of XML and Python:
>
> "The asset-level information would be provided according to proposed
> standards and in a tagged data format using eXtensible Markup Language
> (XML). In addition, we are proposing to require, along with the
> prospectus filing, the filing of a computer program of the contractual
> cash flow provisions expressed as downloadable source code in Python,
> a commonly used open source interpretive programming language."

I guess we've now gone from "executable pseudocode" to "executable
legal code" :-)

Cheers,
Chris
--
Cue the Perl jokes!
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error Occurs: Replace a character in a String

2010-04-10 Thread Patrick Maupin
On Apr 11, 12:01 am, Jimbo  wrote:
> Hello, I am getting an error in my python script when I try to change
> a character in a string. [b]But I dont know why or what to do to fix
> it?[/b]
>
> I have commented in my code where the error occurs
>
> [code]
> def format_file(filename):
>
>     HTML_file   = open(filename,'r')
>     HTML_source = HTML_file.read()
>     HTML_file.close()
>
>     x = 0
>
>     # Format all ID's & classes correctly
>     temp_buf        = HTML_source.lower()
>     class_occurence = temp_buf.count('class')
>     ID_occurence    = temp_buf.count('id')
>
>     for n in range(class_occurence):
>         hit = temp_buf.find('class')
>         if not hit==-1:
>             temp_buf[hit] = '~' # Error: 'str' object does not support
> item assignment
>             x = hit+5
>
>             # delete any spaces until we reach a letter or number
>             while x                 if temp_buf[x] == ' ':
>                     tempbuf[x]     = ''
>                     HTML_source[x] = ''
>                 elif temp_buf[x] == '=':
>                     pass
>                 #elif temp_buf[x] == "'" or temp_buf[x] == '"'
> isalpha(temp_buf[x])
>                 else:
>                     break
>                 x += 1
> [/code]

In Python, a string is an immutable (unchangeable) object.

You can convert a string into a list of characters (which is not
immutable:

mylist = list(temp_buf)

and then convert it back:

temp_buf = ''.join(mylist)

but you cannot do item assignments inside the string (and lists don't
have a find method, so you cannot use find on your list).  You can
maintain a parallel list and string if you want (with the same
indices).

Also, not sure what you want to accomplish with this statement:

   while xhttp://mail.python.org/mailman/listinfo/python-list


Re: SEC proposes the use of Python and XML

2010-04-10 Thread Patrick Maupin
On Apr 10, 11:13 pm, Ted Larson Freeman 
wrote:
> This week the SEC proposed new requirements for asset-backed
> securities that include the use of XML and Python:
>
> "The asset-level information would be provided according to proposed
> standards and in a tagged data format using eXtensible Markup Language
> (XML). In addition, we are proposing to require, along with the
> prospectus filing, the filing of a computer program of the contractual
> cash flow provisions expressed as downloadable source code in Python,
> a commonly used open source interpretive programming language."
>
> See:http://www.sec.gov/news/press/2010/2010-54.htmhttp://kelloggfinance.wordpress.com/2010/04/08/the-sec-gets-one-right
>
> Ted

Now all we need is for the IRS to follow suit...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Regular Expressions

2010-04-10 Thread Patrick Maupin
On Apr 10, 1:05 pm, Stefan Behnel  wrote:

> Running a Python program in CPython eventually boils down to a sequence of
> commands being executed by the CPU. That doesn't mean you should write
> those commands manually, even if you can. It's perfectly ok to write the
> program in Python instead.

Absolutely.  But (as I seem to have posted many times recently) if
somebody asks how to do "x" it may be useful to point out that it
sounds like he really wants "y" and there are already several canned
solutions that do "y", but if he really wants "x", here is how he
should do it, or here is why he will have problems if he attempts to
do it (hint: whether Jamie Zawinski decides to kill a puppy or not is
not really a problem for somebody just asking a programming question
-- that's really up to Jamie).

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list