Re: xml.dom's weirdness?

2008-07-26 Thread Fredrik Lundh

Lie wrote:


Why this generates AttributeError, then not?

Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import xml
xml.dom

Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'dom'

xml.dom




this is what I get, on both Windows and Linux:

>>> import xml
>>> xml.dom
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'dom'
>>> xml.dom
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'dom'



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


Insert character at a fixed position of lines

2008-07-26 Thread Francesco Pietra
How to insert letter "A" on each line (of a very long list of lines)
at position 22, i.e., one space after "LEU", leaving all other
characters at the same position as in the original example:


ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   1SG   2

In all lines"ATOM" is constant as to both position and string, while
"LEU" is constant as to position only, i.e., "LEU" may be replaced by
three different uppercase letters. Therefore, the most direct
indication would be position 22.

Should the script introduce blank lines, no problem. That I know how
to correct with a subsequent script.

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

Terry Reedy writes:

> [...]
>
> Or the proposal would have to be that 'self' is mandatory for all
> programmers in all languages.  I think *that* would be
> pernicious. People are now free to write the more compact 's.sum =
> s.a + s.b + s.c' if they want instead of the 'self' version.  And
> again, not everyone writes in English.

Of course, "self" would have to become a reserved word.  You could
say that this may break some code, but I don't see much freedom
removed from the language.  After all, being a German, I still can't
write "Für i in range(10)".  ;-)

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleJson is slow .... is there any C Compiled version ?

2008-07-26 Thread Richard Levasseur
On Jul 25, 5:52 pm, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> Also, simplejson and python-cjson might not be entirely compatible:
> there's one character that one escapes and the other doesn't, or something.
> --

They also have different interface.  simplejson uses load/loads/dump/
dumps, whereas cjson using encode/decode (its pretty simple to
monkeypatch cjson with some lambda's so it has the same interface,
though).

Yeah, its frustrating that there are so many json encoders for
python.  Its a bit disappointing simplejson is going into the stdlib;
i hope they rewrite it in C?

http://blog.hill-street.net/?p=7
Has a good comparison of encoders.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Carl Banks
On Jul 24, 4:11 am, Jordan <[EMAIL PROTECTED]> wrote:
> Of course not.
>
> I just think Explicit is better than Implicit is taken seriously by a
> large segment the Python community as a guiding principle,

Yeah, try telling that to the people who advise writing "if x" instead
of "if x==0", or "if s" instead of "if len(s)==0".


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


Re: Insert character at a fixed position of lines

2008-07-26 Thread Peter Otten
Francesco Pietra wrote:

> How to insert letter "A" on each line (of a very long list of lines)
> at position 22, i.e., one space after "LEU", leaving all other
> characters at the same position as in the original example:
> 
> 
> ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04  
> 1SG   2
> 
> In all lines"ATOM" is constant as to both position and string, while
> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
> three different uppercase letters. Therefore, the most direct
> indication would be position 22.

You insert a string into another one using slices

line = line[:22] + " " + line[22:]

(Python's strings are immutable, so you are not really modifying the old
string but creating a new one)

> Should the script introduce blank lines, no problem. That I know how
> to correct with a subsequent script.

You are probably printing lines read from a file. These lines already end
with a newline, and print introduces a second one. Use the file's write()
method instead of print to avoid that, e. g.:

import sys

for line in sys.stdin:
line = line[:22] + " " + line[22:]
sys.stdout.write(line)

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Carl Banks
On Jul 24, 1:41 am, Jordan <[EMAIL PROTECTED]> wrote:
> Except when it comes to Classes. I added some classes to code that had
> previously just been functions, and you know what I did - or rather,
> forgot to do? Put in the 'self'. In front of some of the variable
> accesses, but more noticably, at the start of *every single method
> argument list.* This cannot be any longer blamed as a hangover from
> Java - I've written a ton more code, more recently in Python than in
> Java or any other OO language. What's more, every time I go back to
> Python after a break of more than about a week or so, I start making
> this 'mistake' again. The perennial justification for this 'feature'
> of the language? That old Python favourite, "Explicit is better than
> implicit."

I'm sure some people use that argument, but in my observations the
more common justification for explicit self is that makes code easier
to read, by making it obvious that something is a class attribute
instead of a local or global variable.

Your claim is that self makes code a lot harder to write, but you've
disregarded the viewpoint of the reader altogether.  You probably are
aware that there is another Zen that says "Readability Counts".  Would
you also suggest that Zen needs to be done away with?


> If there was one change I could make to Python, it would be to get
> that damn line out of the Zen.

Personally, I think you've applied it to things that it wasn't really
intended for.  It's mostly applies to things like language syntax,
type conversions, and other semantics.  For instance in Perl there are
cases where you can omit quotes around strings; that'd be a major no-
no in Python.  Or how about this:

a = 1  # a is an integer
a += "hello"   # oops, now it's a string

Let me suggest that such things are a Very Bad Idea and so that line
is better left in place.


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


Re: An Attempt to download and install traits - to a Windows XP

2008-07-26 Thread Robert Kern
On Jul 25, 5:37 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
> Using >easy_install -v 
> -fhttp://code.enthought.com/enstaller/eggs/sourceenthought.traits
>
> The result is:
>
> ...
>    many lines
> ...
>
> copyingenthought\traits\ui\tests\shell_editor_test.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\table_editor_color_test.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\table_editor_focus_bug.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\table_editor_test.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\table_editor_test2.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\table_list_editor_test.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> copyingenthought\traits\ui\tests\tree_editor_test.py
> ->
> build\lib.win32-2.5\enthought\traits\ui\tests
> running build_ext
> error: Setup script exited with error:
> Python was built with Visual Studio 2003;
> extensions must be built with a compiler
> than can generate compatible binaries.
> Visual Studio 2003 was not found on this
> system. If you have Cygwin installed,
> you can try compiling with MingW32, by
> passing "-c mingw32" to setup.py.

Traits includes an extension module. You will need a suitable
compiler.

  http://www.develer.com/oss/GccWinBinaries

To tell distutils to use this compiler for all extension modules,
create pydistutils.cfg file with the following contents:

  [build_ext]
  compiler=mingw32

See this page for details about this file:

  http://docs.python.org/inst/config-syntax.html

You will get the most help about Traits and the rest of the Enthought
Tool Suite on the enthought-dev mailing list.

  https://mail.enthought.com/mailman/listinfo/enthought-dev

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


Just click and Enjoy the latest Shreya and Asin

2008-07-26 Thread Enjoy
Just click and Enjoy the latest Shreya and Asin
SEXY photes also your favorite Heroines...

http://lovegroup341.blogspot.com/
#

ENJOY each moments
--
http://mail.python.org/mailman/listinfo/python-list


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Martin v. Löwis
> The end result of that is on a 32-bit machine IronPython runs in a
> 32-bit process and on a 64-bit machine it runs in a 64-bit process.


That's probably not exactly true (although I haven't checked).

When you start a .NET .exe program, the operating system needs to decide
whether to create a 32-bit or a 64-bit process (assuming the processor
supports 64-bit mode).

The Microsoft .NET commercial framework uses the PE architecture of the
executable to make that decision (or, rather, it doesn't decide at all,
but the underlying OS decides). The C# compiler (more specifically, the
assembly linker) offers a choice of setting the .NET architecture to
Itanium, AMD64, x86, or "any"; people use typically "any". This "any"
choice is implemented by setting the PE architecture to "any", and then
indicating to the .NET run-time that any other architecture would be
fine as well.

As a consequence, an architecture-any executable launches as a 32-bit
process on a 64-bit system. To have the executable launch as 64-bit
code, you must tell csc.exe to create an AMD64 binary (say), which
then means that the binary won't launch on a 32-bit system. I haven't
checked, but my guess is that IronPython uses architecture-any
executables (unless you adjust the build process).

Things are different in a DLL: an architecture-any DLL will load into
a 32-bit process as 32-bit code, and into a 64-bit process as 64-bit
code.

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


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Martin v. Löwis
> (Any recommendations on a flavor of 64 bit of Linux for the Intel
> architecture would be appreciated)

My recommendation is to use Debian or Ubuntu, as that's my personal
preference. As MAL said, any recent distribution that supports AMD64
should be fine (assuming you are not interested in Itanium, SPARC64,
HPPA (2.0), PPC64, or Alpha, which are all 64-bit flavors of Linux).

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Bruno Desthuilliers

Carl Banks a écrit :

On Jul 24, 4:11 am, Jordan <[EMAIL PROTECTED]> wrote:

Of course not.

I just think Explicit is better than Implicit is taken seriously by a
large segment the Python community as a guiding principle,


Yeah, try telling that to the people who advise writing "if x" instead
of "if x==0", or "if s" instead of "if len(s)==0".


Anyone suggesting that 'if x' should be replaced by 'if x==0' should be 
shot down before he even get a chance to write any code. But perhaps you 
meant replacing 'if x' by 'if x != 0' and 'if s' by 'if len(s) != 0' ?-)


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


Re: Insert character at a fixed position of lines

2008-07-26 Thread Lie
On Jul 26, 2:41 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> How to insert letter "A" on each line (of a very long list of lines)
> at position 22, i.e., one space after "LEU", leaving all other
> characters at the same position as in the original example:
>
> ATOM      1  N   LEU     1     146.615  40.494 103.776  1.00 73.04       1SG  
>  2
>
> In all lines"ATOM" is constant as to both position and string, while
> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
> three different uppercase letters. Therefore, the most direct
> indication would be position 22.
>
> Should the script introduce blank lines, no problem. That I know how
> to correct with a subsequent script.
>
> Thanks
> chiendarret

If you want to leave the rest of the strings as-is (i.e. the letter A
overwrites whatever on position 22), Peter's code need to be modified
a little:
line = line[:22] + " " + line[23:]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Bruno Desthuilliers

Matthew Fitzgibbons a écrit :
(snip)

As for !=, it seems like there is a technical reason for the behavior. 
Remember, there is no default __ne__ method, so the behavior you want 
would have to live in the interpreter. If __ne__ isn't defined, it would 
have to try to call __eq__ and negate the result. Is there any other 
lookup that is treated this way?


There are quite a few cases in Python where there are both a specific 
magic method  *and* a default behaviour based on another magic method if 
the specific one is not implemented. Just out of my mind:

* __contains__ and __getitem__
* __iter__ and __getitem__
* __nonzero__ and __len__

Not to mention the fact that lookup rules even check the existence of 
special methods on class attributes (remember the descriptor protocol ?)...


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


EZ Recipe & Menu Costing

2008-07-26 Thread raja

Customized Excel Workbook to Cost All Your Recipes & Menu Items


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


Weinhaus Weiler

2008-07-26 Thread raja

Historical half-timbered house with excellent cuisine in Oberwesel


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


"Gain 700% More Muscle"

2008-07-26 Thread raja

How To Gain Freaky Muscle Mass. As Seen On CNN.



http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


How I Lost My Belly Fat

2008-07-26 Thread raja


I fought with excess belly fat for years until I found this 1 trick.


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


Parmigiano Reggiano DOP

2008-07-26 Thread raja

Eccelsa Qualità di Montagna per Rivenditori, Ristoranti e Privati.


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


re.findall(a patern,'function(dsf sdf sdf)')

2008-07-26 Thread gcmartijn
H!

First I have some random string below.

bla = """ 
// 
   """


Now I'm trying to get each BlaObject with the first (variable)
function argument

And I can say that this isn't working
for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla):
print a

The output must be something like:
# ('BlaObject','argh 1a')
# ('BlaObject','argh 1a')
or
# Blaobject("argh 1a", "argh 2a", "24", 24, 345)
# BlaObject("argh 1b", "argh 2b", ""+(sv), ""+(2f), "4");


My simple idea was to
a. the start position is the BlaObject
b. the stop position is the character )  (not ); because its a
javascript function)
c. the output [a (everything between) b]

Who knows the answer ?

Thanks very much,
GCMartijn
--
http://mail.python.org/mailman/listinfo/python-list


Traditional cuisine

2008-07-26 Thread raja

with italian regional recipes with italian master chefs


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


Superfruit strategy

2008-07-26 Thread raja

Six Elements of Superfruit Success Buy new book of expert insights!


http://food-drinks.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


Re: xml.dom's weirdness?

2008-07-26 Thread Lie
On Jul 26, 2:29 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > Why this generates AttributeError, then not?
>
> > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)
> > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
>  import xml
>  xml.dom
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > AttributeError: 'module' object has no attribute 'dom'
>  xml.dom
> > 
>
> this is what I get, on both Windows and Linux:
>
>  >>> import xml
>  >>> xml.dom
> Traceback (most recent call last):
>    File "", line 1, in 
> AttributeError: 'module' object has no attribute 'dom'
>  >>> xml.dom
> Traceback (most recent call last):
>    File "", line 1, in 
> AttributeError: 'module' object has no attribute 'dom'
>
> 

That was what I would have expected. The submodules shouldn't get
imported unless explicitly imported with import xml.dom, but what I
see right now in front of me... I wouldn't have believed such thing if
this isn't happening right under my eyes.

Doing several dir(xml) revealed that xml.dom and xml.parsers appeared
only after doing xml.dom and getting AttributeError

After further testing, I found that it also happens with xml.parsers,
but not xml.sax nor xml.etree, odd thing. And I tried PIL modules, the
oddities doesn't happen.

Then I tested the email module, the same thing happened:

Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import email
>>> dir(email)
['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header',
'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage',
'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText',
'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__',
'__builtins__', '__doc__', '__file__', '__name__', '__path__',
'__version__', '_name', 'base64MIME', 'email', 'importer',
'message_from_file', 'message_from_string', 'mime', 'quopriMIME',
'sys']
>>> email.parser
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'parser'
>>> dir(email)
['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header',
'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage',
'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText',
'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__',
'__builtins__', '__doc__', '__file__', '__name__', '__path__',
'__version__', '_name', '_parseaddr', 'base64MIME', 'base64mime',
'charset', 'email', 'encoders', 'errors', 'importer', 'iterators',
'message', 'message_from_file', 'message_from_string', 'mime',
'quopriMIME', 'quoprimime', 'sys', 'utils']
>>>

It seems python (or my version of python, which is the one that
shipped with Ubuntu) mysteriously imported several modules's
submodules in a (seemingly) random, yet consistent manner after an
error occurred (as far as now, it seems ANY error would trigger the
mysterious submodule import).

I got even more head scratching when I see this:

Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> ac
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'ac' is not defined
>>> import xml
>>> dir(xml)
['_MINIMUM_XMLPLUS_VERSION', '__all__', '__builtins__', '__doc__',
'__file__', '__name__', '__path__', '__version__', 'dom', 'parsers']
>>>

The triggering errors happened BEFORE I imported a module, yet later
module import would also import submodules

If you have any idea what black magic is happening in my computer
right now, I'd appreciate it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Nikolaus Rath
Terry Reedy <[EMAIL PROTECTED]> writes:
> Nikolaus Rath wrote:
>> Terry Reedy <[EMAIL PROTECTED]> writes:
>>> Torsten Bronger wrote:
 Hallöchen!
>>>  > And why does this make the implicit insertion of "self" difficult?
 I could easily write a preprocessor which does it after all.
>>> class C():
>>>   def f():
>>> a = 3
>>>
>>> Inserting self into the arg list is trivial.  Mindlessly deciding
>>> correctly whether or not to insert 'self.' before 'a' is impossible
>>> when 'a' could ambiguously be either an attribute of self or a local
>>> variable of f.  Or do you and/or Jordan plan to abolish local
>>> variables for methods?
>>
>> Why do you think that 'self' should be inserted anywhere except in the
>> arg list? AFAIU, the idea is to remove the need to write 'self' in the
>> arg list, not to get rid of it entirely.
>
> Because you must prefix self attributes with 'self.'. If you do not
> use any attributes of the instance of the class you are making the
> function an instance method of, then it is not really an instance
> method and need not and I would say should not be masqueraded as
> one. If the function is a static method, then it should be labeled
> as one and no 'self' is not needed and auto insertion would be a
> mistake. In brief, I assume the OP wants 'self' inserted in the body
> because inserting it only in the parameter list and never using it
> in the body is either silly or wrong.


I think you misunderstood him. What he wants is to write


class foo:
   def bar(arg):
   self.whatever = arg + 1


instead of

class foo:
   def bar(self, arg)
   self.whatever = arg + 1


so 'self' should *automatically* only be inserted in the function
declaration, and *manually* be typed for attributes.

Best,

   -Nikolaus

-- 
 »It is not worth an intelligent man's time to be in the majority.
  By definition, there are already enough people to do that.«
 -J.H. Hardy

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C

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

Re: Insert character at a fixed position of lines

2008-07-26 Thread Francesco Pietra
I am still at the stone age, using scripts (e.g., to insert a string
after a string) of the type

f = open("xxx.pdb", "r")
for line in f:
   print line
   if "H16Z POPC" in line:
   print "TER"
f.close()

That is, I have to learn about modules. In your scripts I am lost
about the filename for the pdb file to modify,

francesco

On Sat, Jul 26, 2008 at 11:35 AM, Lie <[EMAIL PROTECTED]> wrote:
> On Jul 26, 2:41 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
>> How to insert letter "A" on each line (of a very long list of lines)
>> at position 22, i.e., one space after "LEU", leaving all other
>> characters at the same position as in the original example:
>>
>> ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   1SG 
>>   2
>>
>> In all lines"ATOM" is constant as to both position and string, while
>> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
>> three different uppercase letters. Therefore, the most direct
>> indication would be position 22.
>>
>> Should the script introduce blank lines, no problem. That I know how
>> to correct with a subsequent script.
>>
>> Thanks
>> chiendarret
>
> If you want to leave the rest of the strings as-is (i.e. the letter A
> overwrites whatever on position 22), Peter's code need to be modified
> a little:
> line = line[:22] + " " + line[23:]
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Dr Francesco Pietra
Professor of Chemistry
Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594
Palazzo Ducale
55100 Lucca (Italy)
e-mail [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.findall(a patern,'function(dsf sdf sdf)')

2008-07-26 Thread Lie
On Jul 26, 5:03 pm, [EMAIL PROTECTED] wrote:
> H!
>
> First I have some random string below.
>
> bla = """          
>                 // 
>                 var bla = new Blaobject("argh 1a", "argh 2a", "24", 24, 345)
>
>                 function la( tec )
>                 {
>                   etc etc
>                 }
>
>                 function other thing( ){
>
>                   var two = new BlaObject("argh 1b", "argh 2b", ""+(sv), 
> ""+(2f), "4");
>
>                   bla die bla
>                 }
>
>                 // ]]>
>                  """
>
> Now I'm trying to get each BlaObject with the first (variable)
> function argument
>

First of all, since you're dealing with Javascript, which is case-
sensitive, Blaobject and BlaObject means different thing, if the dummy
code is real, it'd have raised a name not found error.

> And I can say that this isn't working
> for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla):
>     print a

Of course that doesn't work, you've put BlaObject in a square bracket
(character class notation), which means the re module would search for
_a single letter_ that exist inside the square bracket. Then you do a
'.*', a greedy match-all, something that you generally don't want to
do. Next is the '[)] *', a character class containing only a single
character is the same as the character itself, and the zero-or-more-
repetition (*) is applied to the white space after the character
class, not to the character class itself.

In short, the regular expression you used doesn't seem to be an effort
to solve the problem. In other words, you haven't read the regular
expression docs: http://docs.python.org/lib/module-re.html . In other
words, it's useless to talk with you until then.

(snip)
--
http://mail.python.org/mailman/listinfo/python-list


Re: xml.dom's weirdness?

2008-07-26 Thread Fredrik Lundh

Lie wrote:


If you have any idea what black magic is happening in my computer
right now, I'd appreciate it.


command completion?  (no ubuntu within reach right now, so I cannot 
check how they've set it up).


try starting python with the "-v" option, so you can see exactly when 
the import occurs.




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


Re: Insert character at a fixed position of lines

2008-07-26 Thread Lie
On Jul 26, 5:42 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> I am still at the stone age, using scripts (e.g., to insert a string
> after a string) of the type
>
> f = open("xxx.pdb", "r")
> for line in f:
>    print line
>    if "H16Z POPC" in line:
>        print "TER"
> f.close()
>
> That is, I have to learn about modules. In your scripts I am lost
> about the filename for the pdb file to modify,

In Python, stdin and stdout (as provided by the sys module) is a file-
like object, i.e. it have similar behavior as regular files you opened
with open(). stdin is a read-only file, while stdout is a write-only
file. You already know how to make read-only file, f = open("xxx.pdb",
"r"), to make it writable, you've got to use 'w' as the mode: f =
open("xxx.pdb", "w")

After that you can do this:
f.write('some string')


> francesco
>
>
>
> On Sat, Jul 26, 2008 at 11:35 AM, Lie <[EMAIL PROTECTED]> wrote:
> > On Jul 26, 2:41 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> >> How to insert letter "A" on each line (of a very long list of lines)
> >> at position 22, i.e., one space after "LEU", leaving all other
> >> characters at the same position as in the original example:
>
> >> ATOM      1  N   LEU     1     146.615  40.494 103.776  1.00 73.04       
> >> 1SG   2
>
> >> In all lines"ATOM" is constant as to both position and string, while
> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
> >> three different uppercase letters. Therefore, the most direct
> >> indication would be position 22.
>
> >> Should the script introduce blank lines, no problem. That I know how
> >> to correct with a subsequent script.
>
> >> Thanks
> >> chiendarret
>
> > If you want to leave the rest of the strings as-is (i.e. the letter A
> > overwrites whatever on position 22), Peter's code need to be modified
> > a little:
> > line = line[:22] + " " + line[23:]
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Dr Francesco Pietra
> Professor of Chemistry
> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594
> Palazzo Ducale
> 55100 Lucca (Italy)
> e-mail [EMAIL PROTECTED]

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


Re: scanf in python

2008-07-26 Thread AMD

Thanks Fredrik,

very nice examples.

André

AMD wrote:

For reading delimited fields in Python, you can use .split string 
method.


Yes, that is what I use right now, but I still have to do the 
conversion to integers, floats, dates as several separate steps. What 
is nice about the scanf function is that it is all done on the same 
step. Exactly like when you use % to format a string and you pass it a 
dictionary, it does all the conversions to string for you.


You're confusing surface syntax with processing steps.  If you want to 
do things on one line, just add a suitable helper to take care of the 
processing.  E.g. for whitespace-separated data:


 >>> def scan(s, *types):
... return tuple(f(v) for (f, v) in zip(types, s.split()))
...
 >>> scan("1 2 3", int, int, float)
(1, 2, 3.0)

This has the additional advantage that it works with any data type that 
provides a way to convert from string to that type, not just a small 
number of built-in types.  And you can even pass in your own local 
helper, of course:


 >>> def myfactory(n):
... return int(n) * "!"
...
 >>> scan("1 2 3", int, float, myfactory)
(1, 2.0, '!!!')

If you're reading multiple columns of the same type, you might as well 
inline the whole thing:


data = map(int, line.split())

For other formats, replace the split with slicing or a regexp.  Or use a 
ready-made module; there's hardly every any reason to read standard CSV 
files by hand when you can just do "import csv", for example.


Also note that function *creation* is relatively cheap in Python, and 
since "def" is an executable statement, you can create them pretty much 
anywhere; if you find that need a helper somewhere in your code, just 
put it there.  The following is a perfectly valid pattern:


def myfunc(...):

def myhelper(...):
...

myhelper(...)
myhelper(...)

for line in open(file):
myhelper(...)

(I'd say knowing when and how to abstract things away into a local 
helper is an important step towards full Python fluency -- that is, the 
point where you're able to pack "a lot of action in a small amount of 
clear code" most of the time.)





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


Re: Insert character at a fixed position of lines

2008-07-26 Thread Fredrik Lundh


Francesco Pietra wrote:


How to insert letter "A" on each line (of a very long list of lines)
at position 22, i.e., one space after "LEU", leaving all other
characters at the same position as in the original example:


ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   1SG   2

In all lines"ATOM" is constant as to both position and string, while
"LEU" is constant as to position only, i.e., "LEU" may be replaced by
three different uppercase letters. Therefore, the most direct
indication would be position 22.


you may find the fileinput module helpful, combined with the tips you've 
already gotten in this thread.


reference:

http://docs.python.org/lib/module-fileinput.html

examples:

http://effbot.org/librarybook/fileinput.htm
http://blog.doughellmann.com/2007/03/pymotw-fileinput.html



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


Re: re.findall(a patern,'function(dsf sdf sdf)')

2008-07-26 Thread gcmartijn
> In short, the regular expression you used doesn't seem to be an effort
> to solve the problem. In other words, you haven't read the regular
> expression docs:http://docs.python.org/lib/module-re.html. In other
> words, it's useless to talk with you until then.
>

Its a combination
- I don't understand english very good (yet)
- For me its hard to learn the re , I will try to search again at
google for examples and do some copy past things.

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :
(snip)
There are quite a few cases in Python where there are both a specific 
magic method  *and* a default behaviour based on another magic method if 
the specific one is not implemented. Just out of my mind:


s/out of my mind/Off the top of my head/

Pardon my french, and thanks to Tim Golden for the correction !-)


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


Re: Attack a sacred Python Cow

2008-07-26 Thread Steven D'Aprano
On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote:

> Terry Reedy <[EMAIL PROTECTED]> writes:
...
>> Because you must prefix self attributes with 'self.'. If you do not use
>> any attributes of the instance of the class you are making the function
>> an instance method of, then it is not really an instance method and
>> need not and I would say should not be masqueraded as one. If the
>> function is a static method, then it should be labeled as one and no
>> 'self' is not needed and auto insertion would be a mistake. In brief, I
>> assume the OP wants 'self' inserted in the body because inserting it
>> only in the parameter list and never using it in the body is either
>> silly or wrong.
> 
> 
> I think you misunderstood him. What he wants is to write
> 
> 
> class foo:
>def bar(arg):
>self.whatever = arg + 1
> 
> 
> instead of
> 
> class foo:
>def bar(self, arg)
>self.whatever = arg + 1
> 
> 
> so 'self' should *automatically* only be inserted in the function
> declaration, and *manually* be typed for attributes.


That idea might have worked many years ago, but not now. The problem is, 
what happens here?

class Foo(object):
def foo(self, arg):
self.whatever = arg + 1
@classmethod
def cfoo(cls, arg):
cls.whatever = arg - 1
@staticmethod
def sfoo(arg):
print arg


How does the compiler know to insert "self" into the argument list for 
foo, "cls" into that of cfoo, but do nothing for sfoo? Decorators can 
transform methods in arbitrarily complex ways using the Descriptor 
protocol.


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


Re: re.findall(a patern,'function(dsf sdf sdf)')

2008-07-26 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


- For me its hard to learn the re , I will try to search again at
google for examples and do some copy past things.


this might be useful when figuring out how RE:s work:

http://kodos.sourceforge.net/

also, don't forget the following guideline:

   "Some people, when confronted with a problem, think 'I know,
   I'll use regular expressions.'   Now they have two problems."

some advice:

- Keep the RE:s simple.  You can often simplify things a lot by doing 
multiple searches, or even by applying a second RE on the results from 
the first.  In this case, you could use one RE to search for BlaObject, 
and then use another one to extract the first argument.


- Ordinary string methods (e.g. find, partition, split) are often a very 
capable alternative (in combination with simple RE:s).  In your case, 
for JavaScript code that's as regular as the one in your example, you 
can split the string on "BlaObject(" and then use partition to strip off 
the first argument.


- only use RE:s to read specialized file formats if you know exactly 
what you're doing; there's often a ready-made library that does it much 
better.


- The regular expression machinery is not a parser.  You cannot handle 
all possible syntaxes with it, so don't even try.




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


Stripping parts of a path

2008-07-26 Thread Tim Cook
Hi All,

I just ran into an issue with the rstrip method when using it on path
strings.

When executing a function I have a need to strip off a portion of the
current working directory and add on a path to a log file.  Initially
this worked great but then I added a branch in SVN which caused the path
to contain 'LNCCWorkshop'.  The rstrip() then began removing the
characters 'shop' leaving an incorrect path to the log file.  When I
hard coded this path it worked okay but then did the same thing later in
the file when I needed to point to a database. The code worked fine with
a different path.  Here are some code fragments. 
 
logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log'

this worked when the path was: 
/home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr

the code above returns: 
/home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log

but when I tried a branches version that has the path:
/home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr

it SHOULD return:
/home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log
 
but I get:
/home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log

logfile=os.getcwd()
print logfile is correct; but when I add the .rstrip('src/oship/atbldr')
it also strips the 'shop' off of LNCCWorkshop and returns 
/home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log

I had two other people looking at this as we did troubleshooting and we
could not determine the cause.  It is repeatable with this path name.
In resolution I renamed the branch to just LNCC and it works fine.

Thoughts?

Tim







-- 
**
Join the OSHIP project.  It is the standards based, open source
healthcare application platform in Python.
Home page: https://launchpad.net/oship/ 
Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page 
**


signature.asc
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list

Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

Steven D'Aprano writes:

> On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote:
>
>> [...]
>> 
>> so 'self' should *automatically* only be inserted in the function
>> declaration, and *manually* be typed for attributes.
>
>
> That idea might have worked many years ago, but not now. The
> problem is, what happens here?
>
> class Foo(object):
> def foo(self, arg):
> self.whatever = arg + 1
> @classmethod
> def cfoo(cls, arg):
> cls.whatever = arg - 1
> @staticmethod
> def sfoo(arg):
> print arg

See .  It is only added
to non-decorated methods within a class.  This implies that you can
switch this mechanism off with a noop decorator.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.findall(a patern,'function(dsf sdf sdf)')

2008-07-26 Thread gcmartijn
On 26 jul, 14:25, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > - For me its hard to learn the re , I will try to search again at
> > google for examples and do some copy past things.
>
> this might be useful when figuring out how RE:s work:
>
>      http://kodos.sourceforge.net/
>
> also, don't forget the following guideline:
>
>     "Some people, when confronted with a problem, think 'I know,
>     I'll use regular expressions.'   Now they have two problems."
>
> some advice:
>
> - Keep the RE:s simple.  You can often simplify things a lot by doing
> multiple searches, or even by applying a second RE on the results from
> the first.  In this case, you could use one RE to search for BlaObject,
> and then use another one to extract the first argument.
>
> - Ordinary string methods (e.g. find, partition, split) are often a very
> capable alternative (in combination with simple RE:s).  In your case,
> for JavaScript code that's as regular as the one in your example, you
> can split the string on "BlaObject(" and then use partition to strip off
> the first argument.
>
> - only use RE:s to read specialized file formats if you know exactly
> what you're doing; there's often a ready-made library that does it much
> better.
>
> - The regular expression machinery is not a parser.  You cannot handle
> all possible syntaxes with it, so don't even try.
>
> 

Thanks for the info, I will download that program later so I can build
a re (i hope)

Because I can't wait for that re, I have made a non re solution what
is working for now.

for a in bla.split():
if a.find('BlaObject')<>-1:
print a[11:].replace("'","").replace('"',"").replace(",","")

(I know this is not the best way, but it helps me for now)
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2d graphics - what module to use?

2008-07-26 Thread sturlamolden
On Jul 26, 6:47 am, Matthew Fitzgibbons <[EMAIL PROTECTED]> wrote:

> If you're using wx, there is also wx.lib.plot, which I found to be
> _much_ faster than matplotlib in my application, especially when resizing.

Yes. Matplotlib creates beautiful graphics, but are terribly slow on
large data sets.


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


Re: Stripping parts of a path

2008-07-26 Thread Karen Tracey
On Sat, Jul 26, 2008 at 7:59 AM, Tim Cook <[EMAIL PROTECTED]>wrote:

> Hi All,
>
> I just ran into an issue with the rstrip method when using it on path
> strings.
>
> When executing a function I have a need to strip off a portion of the
> current working directory and add on a path to a log file.  Initially
> this worked great but then I added a branch in SVN which caused the path
> to contain 'LNCCWorkshop'.  The rstrip() then began removing the
> characters 'shop' leaving an incorrect path to the log file.  When I
> hard coded this path it worked okay but then did the same thing later in
> the file when I needed to point to a database. The code worked fine with
> a different path.  Here are some code fragments.
>
>
> logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log'
>
> this worked when the path was:
> /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr
>
> the code above returns:
> /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log
>
> but when I tried a branches version that has the path:
> /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr
>
> it SHOULD return:
>
> /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log
>
> but I get:
> /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log
>
> logfile=os.getcwd()
> print logfile is correct; but when I add the .rstrip('src/oship/atbldr')
> it also strips the 'shop' off of LNCCWorkshop and returns
> /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log
>
> I had two other people looking at this as we did troubleshooting and we
> could not determine the cause.  It is repeatable with this path name.
> In resolution I renamed the branch to just LNCC and it works fine.
>
> Thoughts?
>

I think rstrip does not do what you think it does.  From:

http://docs.python.org/lib/string-methods.html

"The chars argument is not a suffix; rather, all combinations of its values
are stripped"

Thus, since the characters p,o,h, and s are all in the argument you supplied
to rstrip, they are removed, then stripping is stopped at the k because that
is not in the chars arg you supplied.

To do what you really want I think you need to use rfind/rindex to locate
the last occurrence of the substring and then truncate the string yourself.

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

Re: Stripping parts of a path

2008-07-26 Thread Larry Bates

Tim Cook wrote:

Hi All,

I just ran into an issue with the rstrip method when using it on path
strings.

When executing a function I have a need to strip off a portion of the
current working directory and add on a path to a log file.  Initially
this worked great but then I added a branch in SVN which caused the path
to contain 'LNCCWorkshop'.  The rstrip() then began removing the
characters 'shop' leaving an incorrect path to the log file.  When I
hard coded this path it worked okay but then did the same thing later in
the file when I needed to point to a database. The code worked fine with
a different path.  Here are some code fragments. 
 
logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log'


this worked when the path was: 
/home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr


the code above returns: 
/home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log


but when I tried a branches version that has the path:
/home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr

it SHOULD return:
/home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log
 
but I get:

/home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log

logfile=os.getcwd()
print logfile is correct; but when I add the .rstrip('src/oship/atbldr')
it also strips the 'shop' off of LNCCWorkshop and returns 
/home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log


I had two other people looking at this as we did troubleshooting and we
could not determine the cause.  It is repeatable with this path name.
In resolution I renamed the branch to just LNCC and it works fine.

Thoughts?

Tim








Always helps to consult documentation when things don't work.

Help on built-in function rstrip:

rstrip(...)
S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping


If you give chars to rstrip() it removes all those characters from the string 
not that substring.


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


Re: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?)

2008-07-26 Thread D'Arcy J.M. Cain
On Sat, 26 Jul 2008 14:07:52 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> > sys.stdout = n
> 
> Re-binds the name 'sys.stdout' to the object already referenced by the
> name 'n'. No objects are changed by this; only bindings of names to
> objects.

I do agree that the object formerly known as sys.stdout hasn't changed.

> > print "Testing: 1, 2, 3..."
> 
> Doesn't rely at all on the name 'sys.stdout', so isn't affected by all
> the binding of names above.

Hmm.  Are you saying that the following doesn't work?

$ python
>>> f = open("test", "w")
>>> import sys
>>> sys.stdout = f
>>> print "test message"
>>> sys.exit(0)
$ cat test
test message

> In other words, you can't change the object used by the 'print'
> statement only by re-binding names (which is *all* that is done by the
> '=' operator).

Apparently I can.

> You can, however, specify which file 'print' should use
> http://www.python.org/doc/ref/print.html>.

Which contains this statement.

"Standard output is defined as the file object named stdout in the
built-in module sys."

I suppose that there might be some ambiguity there but the proof, as
they say, is in the pudding.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread D'Arcy J.M. Cain
On Sat, 26 Jul 2008 09:45:21 +0200
Torsten Bronger <[EMAIL PROTECTED]> wrote:
> Of course, "self" would have to become a reserved word.  You could
> say that this may break some code, but I don't see much freedom

Isn't this a showstopper all by itself?

> removed from the language.  After all, being a German, I still can't
> write "Für i in range(10)".  ;-)

Yes, this is why good languages try to limit the number of reserved
words as much as possible.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


clearing all warning module caches in a session

2008-07-26 Thread jason-sage

Hi all,

I just started using the warnings module in Python 2.5.2.  When I 
trigger a warning using the default warning options, an entry is created 
in a module-level cache so that the warning is ignored in the future.  
However, I don't see an easy way to clear or invalidate these 
module-level caches of previously triggered warnings.  That means that 
if I ever have a warning triggered with a "once" or a default warning 
level or filter, I can never see that warning again until I restart 
python (or figure out what module contains the cache and delete it 
manually).


I thought resetwarnings would invalidate the module-level caches, so 
that I could trigger a "once" warning, then do resetwarnings() and make 
the default an "always" action and see my warning displayed again.  At 
least, the name seems to indicate that all *warnings* would be reset, 
not just the filter list.  But apparently resetwarnings() just clears 
the filter list, which is helpful, but doesn't do anything for the 
already-cached warnings.


A very small change in the code would make this possible.  Instead of 
making the value of the warnings module-level cache just "1", make it an 
integer which is incremented each time resetwarnings() is called.  That 
way calling resetwarnings() can invalidate the cache (i.e., the warnings 
processing would ignore the cache record if the value wasn't the current 
integer).


Again, the question is: is there an easy way to invalidate all the 
module-level caches of warnings so that the entire warning system is 
truly reset?


Thanks,

Jason

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

D'Arcy J.M. Cain writes:

> On Sat, 26 Jul 2008 09:45:21 +0200
> Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
>> Of course, "self" would have to become a reserved word.  You
>> could say that this may break some code, but I don't see much
>> freedom
>
> Isn't this a showstopper all by itself?

Yes.  But I've seen no code that uses some other word.  Emacs'
syntax highlighting even treats it as reserved.  So I think that
other counter-arguments are stronger.

The in my opinion strongest one is that automatic insertion of
"self" would make Python less verbose but more complicated.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread D'Arcy J.M. Cain
On Sat, 26 Jul 2008 16:25:18 +0200
Torsten Bronger <[EMAIL PROTECTED]> wrote:
> > Isn't this a showstopper all by itself?
> 
> Yes.  But I've seen no code that uses some other word.  Emacs'
> syntax highlighting even treats it as reserved.  So I think that
> other counter-arguments are stronger.
> 
> The in my opinion strongest one is that automatic insertion of
> "self" would make Python less verbose but more complicated.

Well, if we are arguing over which reason to not change it is more
important than I would say that we are in "violent agreement."  :-)

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

D'Arcy J.M. Cain writes:

> On Sat, 26 Jul 2008 16:25:18 +0200
> Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
>>> Isn't this a showstopper all by itself?
>> 
>> Yes.  But I've seen no code that uses some other word.  Emacs'
>> syntax highlighting even treats it as reserved.  So I think that
>> other counter-arguments are stronger.
>> 
>> The in my opinion strongest one is that automatic insertion of
>> "self" would make Python less verbose but more complicated.
>
> Well, if we are arguing over which reason to not change it is more
> important than I would say that we are in "violent agreement."
> :-)

Oh, I've never been in favour of the change
(news:[EMAIL PROTECTED]).  I just don't think
that some popular counter-arguments are compelling.  ;-)

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Kay Schluehr
On 26 Jul., 09:45, Torsten Bronger <[EMAIL PROTECTED]>
wrote:
> Hallöchen!
>
> Terry Reedy writes:
> > [...]
>
> > Or the proposal would have to be that 'self' is mandatory for all
> > programmers in all languages.  I think *that* would be
> > pernicious. People are now free to write the more compact 's.sum =
> > s.a + s.b + s.c' if they want instead of the 'self' version.  And
> > again, not everyone writes in English.
>
> Of course, "self" would have to become a reserved word.

??

This is an extra requirement. Why do you want to make 'self' a keyword?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

Kay Schluehr writes:

> On 26 Jul., 09:45, Torsten Bronger <[EMAIL PROTECTED]>
> wrote:
>>
>> Terry Reedy writes:
>>
>>> [...]
>>>
>>> Or the proposal would have to be that 'self' is mandatory for
>>> all programmers in all languages.  I think *that* would be
>>> pernicious. People are now free to write the more compact 's.sum
>>> = s.a + s.b + s.c' if they want instead of the 'self' version.
>>> And again, not everyone writes in English.
>>
>> Of course, "self" would have to become a reserved word.
>
> ??
>
> This is an extra requirement. Why do you want to make 'self' a
> keyword?

How could one determine which other identifier must be inserted into
the method's signature?

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jordan  <[EMAIL PROTECTED]> wrote:
>
>The point I was trying to make originally was that applying any mantra
>dogmatically, including Explicit is better than implicit, can lead to
>bad results. Perhaps having Practicality beats purity is enough of a
>reminder of that fact for the Python community :-)

IMO, you made a big mistake in combining your point with two other meaty
issues (whether method definitions should include self and whether !=
should use __eq__() as a fallback).  Moreover, your point is IMO not
sufficiently proven (that is, I see little evidence that Python
development follows any one point of the Zen of Python dogmatically).

You should therefore not be particularly surprised that the discussion
has gone sideways to your intentions -- especially when you start with a
flamebait Subject: line of "attacking sacred cows"!  If solid discussion
is your goal, I suggest that you wait a couple of weeks and start over
with a brand-new thread.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Adopt A Process -- stop killing all your children!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Rob Williscroft
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

>> The end result of that is on a 32-bit machine IronPython runs in a
>> 32-bit process and on a 64-bit machine it runs in a 64-bit process.
> 
> 
> That's probably not exactly true (although I haven't checked).
> 
> When you start a .NET .exe program, the operating system needs to
> decide whether to create a 32-bit or a 64-bit process (assuming the
> processor supports 64-bit mode). 
> 
> The Microsoft .NET commercial framework uses the PE architecture of the

Whats the "Commercial framework" ? I've only come accross 3, the 
standard 32 bit one and 2 64 bit variants. 

> executable to make that decision (or, rather, it doesn't decide at all,
> but the underlying OS decides). The C# compiler (more specifically, the
> assembly linker) offers a choice of setting the .NET architecture to
> Itanium, AMD64, x86, or "any"; people use typically "any". This "any"
> choice is implemented by setting the PE architecture to "any", and then
> indicating to the .NET run-time that any other architecture would be
> fine as well.
> 
> As a consequence, an architecture-any executable launches as a 32-bit
> process on a 64-bit system. 


I just tested, I built a default C# forms app using the "AnyCPU" option
and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64.

I have though installed the AMD64 version of the 2.0 framework and 
AFAICT neither windows update or the Visual Studio installer
will install that by default, you have to go get it your self.

>   To have the executable launch as 64-bit
> code, you must tell csc.exe to create an AMD64 binary (say), which
> then means that the binary won't launch on a 32-bit system. I haven't
> checked, but my guess is that IronPython uses architecture-any
> executables (unless you adjust the build process).

I just started ipy.exe the 1.1 and 2.0B1, both ran as 64 bit processes

IronPython 1.1 (1.1) on .NET 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.
>>>

I don't know what happens if you have both 32 bit and 64 bit versions
of the framwork installed (presumably with slightly different minor 
version numbers) as I uninstalled the 32 bit version before I installed the
AMD64 version.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list

Find Sofas

2008-07-26 Thread lindi
Huge Selections at Great Prices The Convenience of OneCart!



http://good-furniture-care.page.tl/
--
http://mail.python.org/mailman/listinfo/python-list


Re: print doesn't respect file inheritance?

2008-07-26 Thread Lie
On Jul 26, 8:50 am, bukzor <[EMAIL PROTECTED]> wrote:
> I was trying to change the behaviour of print (tee all output to a
> temp file) by inheriting from file and overwriting sys.stdout, but it
> looks like print uses C-level stuff  to do its writes which bypasses
> the python object/inhertiance system. It looks like I need to use
> composition instead of inheritance, but thought this was strange
> enough to note.
>
> $python -V
> Python 2.5
>
> """A short demo script"""
> class notafile(file):
>     def __init__(self, *args, **kwargs):
>         readonly = ['closed', '__class__', 'encoding', 'mode', 'name',
> 'newlines', 'softspace']
>         file.__init__(self, *args, **kwargs)
>         for attr in dir(file):
>             if attr in readonly: continue
>             setattr(self, attr, None)
>
> def main():
>     n = notafile('/dev/stdout', "w")
>     print vars(n)
>
>     import sys
>     sys.stdout = n
>     print "Testing: 1, 2, 3..."
>
> output:
> {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush':
> None, 'close': None, 'seek': None, '__init__': None, '__setattr__':
> None, '__reduce_ex__': None, '__new__': None, 'readinto': None,
> 'next': None, 'write': None, '__doc__': None, 'isatty': None,
> 'truncate': None, 'read': None, '__reduce__': None,
> '__getattribute__': None, '__iter__': None, 'readline': None,
> 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None,
> '__repr__': None, '__hash__': None}
> Testing: 1, 2, 3...

Use this:

class fakefile(object):
def __init__(self, writeto, transformer):
self.target = writeto
self.transform = transformer
def write(self, s):
s = self.transform(s)
self.target.write(s)
sys.stdout = fakefile(sys.stdout, lambda s: '"' + s + '"')

Inheriting from file is not the best way to do it since there is a
requirement that child class' interface must be compatible with the
parent class' interface, since the file-like object you're creating
must have extremely different interface than regular file, the best
way is to use Duck Typing, i.e. write a class that have .write()
method.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Insert character at a fixed position of lines

2008-07-26 Thread Francesco Pietra
Sorry to come again for the same problem. On commanding:

$ python script.py 2>&1 | tee fileout.pdb

nothing occurred (fileout.pdb was zero byte). The script reads:

f = open("xxx.pdb", "w")
f.write('line = line[:22] + "A" + line[23:]')
f.close()

File xxx.pdb is opened by the command: when I forgot the single quote
' after [23:] the error answer was:
SynthaxError: EOL while scanning single-quoted string.

Thanks
francesco

On Sat, Jul 26, 2008 at 1:10 PM, Lie <[EMAIL PROTECTED]> wrote:
> On Jul 26, 5:42 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
>> I am still at the stone age, using scripts (e.g., to insert a string
>> after a string) of the type
>>
>> f = open("xxx.pdb", "r")
>> for line in f:
>>print line
>>if "H16Z POPC" in line:
>>print "TER"
>> f.close()
>>
>> That is, I have to learn about modules. In your scripts I am lost
>> about the filename for the pdb file to modify,
>
> In Python, stdin and stdout (as provided by the sys module) is a file-
> like object, i.e. it have similar behavior as regular files you opened
> with open(). stdin is a read-only file, while stdout is a write-only
> file. You already know how to make read-only file, f = open("xxx.pdb",
> "r"), to make it writable, you've got to use 'w' as the mode: f =
> open("xxx.pdb", "w")
>
> After that you can do this:
> f.write('some string')
>
>
>> francesco
>>
>>
>>
>> On Sat, Jul 26, 2008 at 11:35 AM, Lie <[EMAIL PROTECTED]> wrote:
>> > On Jul 26, 2:41 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
>> >> How to insert letter "A" on each line (of a very long list of lines)
>> >> at position 22, i.e., one space after "LEU", leaving all other
>> >> characters at the same position as in the original example:
>>
>> >> ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   
>> >> 1SG   2
>>
>> >> In all lines"ATOM" is constant as to both position and string, while
>> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
>> >> three different uppercase letters. Therefore, the most direct
>> >> indication would be position 22.
>>
>> >> Should the script introduce blank lines, no problem. That I know how
>> >> to correct with a subsequent script.
>>
>> >> Thanks
>> >> chiendarret
>>
>> > If you want to leave the rest of the strings as-is (i.e. the letter A
>> > overwrites whatever on position 22), Peter's code need to be modified
>> > a little:
>> > line = line[:22] + " " + line[23:]
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> --
>> Dr Francesco Pietra
>> Professor of Chemistry
>> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594
>> Palazzo Ducale
>> 55100 Lucca (Italy)
>> e-mail [EMAIL PROTECTED]
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easier way to get the "here" path?

2008-07-26 Thread Andrew

bukzor wrote:

I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
  
If you just need the current path (where it is executed) why not use 
os.getcwd()

which returns a string of the absolute path to the module being executed.


$ echo "print __file__" > path.py
$ ipython
In [1]: import path
path.pyc

In [2]: import os

In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easier way to get the "here" path?

2008-07-26 Thread Andrew

bukzor wrote:

from os.path import abspath, realpath
realpath(path.__file__.rstrip("c"))


'/home/bgolemon/python/symlinks/path.py'
  

realpath(abspath(path.__file__.rstrip("c")))


'/home/bgolemon/python/symlinks/symlinks/path.py'
--
http://mail.python.org/mailman/listinfo/python-list
  

I find it interesting that I get something different:

In [1]: import path
path.pyc

In [2]: path.__file__
Out[2]: 'path.pyc'

In [3]: path.__file__.rstrip("c")
Out[3]: 'path.py'

In [4]: from os.path import abspath, realpath

In [5]: realpath(path.__file__.rstrip("c"))
Out[5]: '/home/andrew/sym/sym/path.py'

In [6]: realpath(abspath(path.__file__.rstrip("c")))
Out[6]: '/home/andrew/sym/sym/path.py'

I get the same thing for realpath() and realpath(abspath())
It seems to me you can just use:

In [1]: import path
path.pyc

In [2]: from os.path import abspath

In [3]: realpath(path.__file__.rstrip("c"))
Out[3]: '/home/andrew/sym/sym/path.py'

By the way, I am in /home/andrew/sym and path is symlinked from 
/home/andrew/sym/sym/path.py to /home/andrew/sym/path.py


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


Re: Easier way to get the "here" path?

2008-07-26 Thread MRAB
On Jul 25, 10:08 pm, bukzor <[EMAIL PROTECTED]> wrote:
> I have to go into these convulsions to get the directory that the
> script is in whenever I need to use relative paths. I was wondering if
> you guys have a better way:
>
> from os.path import dirname, realpath, abspath
> here = dirname(realpath(abspath(__file__.rstrip("c"
>
> In particular, this takes care of the case of symlinked, compiled
> scripts, which is fairly common at my workplace, and I imagine in many
> *nix evironments.
>
> An illustration:
> $echo "print __file__" > symlinks/path.py
> $ln -s symlinks/path.py
> $python>>> import path
> path.py
> >>> reload(path)
>
> path.pyc
> >>> path.__file__
> 'path.pyc'
> >>> path.__file__.rstrip("c")
> 'path.py'
> >>> from os.path import abspath, realpath
> >>> realpath(path.__file__.rstrip("c"))
>
> '/home/bgolemon/python/symlinks/path.py'>>> 
> realpath(abspath(path.__file__.rstrip("c")))
>
> '/home/bgolemon/python/symlinks/symlinks/path.py'

How about:

import os
import sys
here = os.path.realpath(os.path.dirname(sys.argv[0]))

It's a little clearer. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easier way to get the "here" path?

2008-07-26 Thread Andrew

Andrew wrote:

bukzor wrote:

I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
  
If you just need the current path (where it is executed) why not use 
os.getcwd()

which returns a string of the absolute path to the module being executed.


$ echo "print __file__" > path.py
$ ipython
In [1]: import path
path.pyc

In [2]: import os

In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
I was thinking of this in the module being imported, but now that I try, 
it doesn't work. It is still seeing itself from the symlink's position.


This works, in the module being imported:
$ less path.py
from os.path import realpath
here = realpath(__file__.rstrip("c"))

$ python
>>> import path
>>> path.here
'/home/andrew/sym/sym/path.py'

--
Andrew

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


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Martin v. Löwis
>> The Microsoft .NET commercial framework uses the PE architecture of the
> 
> Whats the "Commercial framework" ? I've only come accross 3, the 
> standard 32 bit one and 2 64 bit variants. 

That's the name of the Microsoft .NET product available for Windows.
There are other implementations as well, such as the Compact Framework,
or GNU Mono.

It's correct that the commercial framework is available for three
architectures. In addition, the compact framework is also available
for ARM. Mono is available for many more platforms, such as SPARC,
PowerPC, MIPS and HPPA.

> I just tested, I built a default C# forms app using the "AnyCPU" option
> and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64.
> 
> I have though installed the AMD64 version of the 2.0 framework and 
> AFAICT neither windows update or the Visual Studio installer
> will install that by default, you have to go get it your self.

Interesting. I only tested this in .NET 1.1. Perhaps they have changed
something since. How exactly did you launch the program? Does it change
if you use Python's os.spawn* to launch it?

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Michele Simionato
On Jul 26, 5:28 pm, [EMAIL PROTECTED] (Aahz) wrote:
> IMO, you made a big mistake in combining your point with two other meaty
> issues (whether method definitions should include self and whether !=
> should use __eq__() as a fallback).

>  If solid discussion
> is your goal, I suggest that you wait a couple of weeks and start over
> with a brand-new thread.

I fully subscribe this. The point about __eq__ is legitimate and could
be discussed with quite tones.
I was bitten by this surprising behavior just a few
days ago, I had defined __eq__ and I expected __neq__
to be defined in the obvious way. I saw that it was
not the case and I figured out immediately that
I had to override __neq__ explicitely (I have
the "explicit is better than implicit" mantra
ingrained in my mind too), I did so and everything
worked out as a charm. Total time loss: five minutes.
So, it is not a big point. Still I think
that it would make sense to automatically
define __neq__ as the negation of __eq__.
I suppose the developers did not want to make a special
case in the implementation and this is also a legitimate
concern.

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


how to upload files to "google code" filesection ?

2008-07-26 Thread Stef Mientki

hello,

In a program I want to download (updated) files from google code (not 
the svn section).

I could find a python script to upload files,
but not for downloading.

Anyone has a hint or a solution ?

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


urllib and login with passwords

2008-07-26 Thread Jive Dadson

Hey folks!

There are various web pages that I would like to read using urllib, but 
they require login with passwords. Can anyone tell me how to find out 
how to do that, both in general and specifically for YouTube.com.


Thankee.

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


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Paul Boddie
On 25 Jul, 12:35, "M.-A. Lemburg" <[EMAIL PROTECTED]> wrote:
>
> But then Intel Itanium is being phased out anyway

Citation needed! ;-)

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Paul Boddie
On 26 Jul, 06:06, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Paul Boddie wrote:
> > "The problem is that the explicit requirement to have self at the
> > start of every method is something that should be shipped off to the
> > implicit category."

Here, I presume that the author meant "at the start of every method
signature".

> There is no requirement to have 'self' in the parameter list.  It can be
> 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or
> any other identifier in whatever language.

But Jordan apparently wanted to omit that parameter. The omission of
all mentions of "self" could be regarded as a bonus, but it's a non-
trivial goal.

> In 3.0, identifiers are not restricted to ascii but can be any unicode
> 'word' as defined in the manual.
>
> So the proposal would have to be that the compiler scan the function
> body and decide which dotted name prefix is the one to be implicitly
> added.  Have fun writing the discovery algorithm.  However, I think this
> is pretty silly.  Just write the name you want.

If, as I wrote, you permit the omission of "self" in method signatures
defined within class definitions, then you could still insist on
instance attribute qualification using "self" - exactly as one would
when writing Java according to certain style guidelines.

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


Re: Gracefull application exit.

2008-07-26 Thread M.-A. Lemburg

On 2008-07-24 18:06, Robert Rawlins wrote:

Chaps,

 


I'm looking to implement an exit/termination process for an application
which can be triggered by A) a keyboard interrupt or B) termination of the
application as a Daemon using a signal.

 


I have a whole bunch of tasks I want to perform as a cleanup before the
application is terminated, cleaning files, database calls, closing open
connections and a few other things.

 


I know we have:

 


# I'm the main application started method.

if __name__ == "__main__":

 


For starting an application, but do we have an equivalent methods for when
an application is terminated which we can use to close down any current
internal processes before the application exits?

 


I'd really love to have your thoughts and experience on gracefully killing
an application.


Warp your whole application into a main() function and then use:

try:
main()
finally:
cleanup()

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 25 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Gracefull application exit.

2008-07-26 Thread M.-A. Lemburg

On 2008-07-26 20:30, M.-A. Lemburg wrote:

On 2008-07-24 18:06, Robert Rawlins wrote:

Chaps,

 


I'm looking to implement an exit/termination process for an application
which can be triggered by A) a keyboard interrupt or B) termination of 
the

application as a Daemon using a signal.

 


I have a whole bunch of tasks I want to perform as a cleanup before the
application is terminated, cleaning files, database calls, closing open
connections and a few other things.

 


I know we have:

 


# I'm the main application started method.

if __name__ == "__main__":

 

For starting an application, but do we have an equivalent methods for 
when

an application is terminated which we can use to close down any current
internal processes before the application exits?

 

I'd really love to have your thoughts and experience on gracefully 
killing

an application.


Wrap your whole application into a main() function and then use:

try:
main()
finally:
cleanup()



BTW: In order to catch signals, you'll have to install signal handlers
which then raise Python exceptions, e.g. SystemExit.

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 26 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Simple Path issues

2008-07-26 Thread Brett Ritter
New to Python, and I have some questions on how to best set up a basic
development environment, particular relating to path issues.

Note: I am not root on my development box (which is some flavor of
BSD)

Where should I develop my own modules so as to refer to them in the
standard way.  I.E. I want:
import proj

to work regardless of my current working directory, and to function as
if "proj" were a core or third-party module.

I saw that I can set PYTHONPATH, but that seems sub-prime.  I noted
that in installing pysqlite (the local installation of python is 2.4)
that I had it install in a lib under my home dir...should I use that
locale?

What is the command to tell me what directories python is checking in?

While I'm at it, what is the best (read: standard) locale to stick my
test cases?  same dir as my project?  A subdir?

Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confounded by Python objects

2008-07-26 Thread Robert Latest
satoru wrote:

> As to "sample", it never get assigned to and when you say "append" the
> class variable is changed in place.
> hope my explaination helps.

Sure does, thanks a lot.

Here's an interesting side note: After fixing my "Channel" thingy the
whole project behaved as expected. But there was an interesting hitch.
The main part revolves around another class, "Sequence", which has a
list of Channels as attribute. I was curious about the performance of my
script, because eventually this construct is supposed to handle
megabytes of data. So I wrote a simple loop that creates a new Sequence,
fills all the Channels with data, and repeats.

Interistingly, the first couple of dozens iterations went satisfactorily
quickly (took about 1 second total), but after a hundred or so times it
got really slow -- like a couple of seconds per iteration.

Playing around with the code, not really knowing what to do, I found
that in the "Sequence" class I had again erroneously declared a class-level
attribute -- rather harmlessly, just a string, that got assigned to once in each
iteration on object creation. 

After I had deleted that, the loop went blindingly fast without slowing
down.

What's the mechanics behind this behavior?

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


Re: Simple Path issues

2008-07-26 Thread Gary Josack

Brett Ritter wrote:

New to Python, and I have some questions on how to best set up a basic
development environment, particular relating to path issues.

Note: I am not root on my development box (which is some flavor of
BSD)

Where should I develop my own modules so as to refer to them in the
standard way.  I.E. I want:
import proj

to work regardless of my current working directory, and to function as
if "proj" were a core or third-party module.

I saw that I can set PYTHONPATH, but that seems sub-prime.  I noted
that in installing pysqlite (the local installation of python is 2.4)
that I had it install in a lib under my home dir...should I use that
locale?

What is the command to tell me what directories python is checking in?

While I'm at it, what is the best (read: standard) locale to stick my
test cases?  same dir as my project?  A subdir?

Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list
  


sys.path is a list that will tell you where python is looking. You can 
append to this in your scripts to have python look in a specific 
directory for your own modules.


Thanks,
Gary M. Josack

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


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Rob Williscroft
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 
>> I just tested, I built a default C# forms app using the "AnyCPU"
>> option and it ran as a 64 bit app (no *32 in Task Manager), this is
>> on XP64. 
>> 
>> I have though installed the AMD64 version of the 2.0 framework and 
>> AFAICT neither windows update or the Visual Studio installer
>> will install that by default, you have to go get it your self.
> 
> Interesting. I only tested this in .NET 1.1. Perhaps they have changed
> something since. How exactly did you launch the program? Does it change
> if you use Python's os.spawn* to launch it?

If subprocess.call will do then I can report the same results, a
64 bit process, using 32 bit CPython 2.5 to call it.
 
Also if the programme (C#) is built with the 3.5 framework I 
get the same results, however interestingly there is no 64 bit 
build for the 3.5 framework (or at least I was unable to find one).

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Stripping parts of a path

2008-07-26 Thread Dan Stromberg
On Sat, 26 Jul 2008 08:59:15 -0300, Tim Cook wrote:

> Hi All,
> 
> I just ran into an issue with the rstrip method when using it on path
> strings.
> 
> When executing a function I have a need to strip off a portion of the
> current working directory and add on a path to a log file.  Initially
> this worked great but then I added a branch in SVN which caused the path
> to contain 'LNCCWorkshop'.  The rstrip() then began removing the
> characters 'shop' leaving an incorrect path to the log file.  When I
> hard coded this path it worked okay but then did the same thing later in
> the file when I needed to point to a database. The code worked fine with
> a different path.  Here are some code fragments.
>  
> logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/
at_build_errors.log'
> 
> this worked when the path was:
> /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr
> 
> the code above returns:
> /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log
> 
> but when I tried a branches version that has the path:
> /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr
> 
> it SHOULD return:
> /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/
at_build_errors.log
>  
> but I get:
> /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/
at_build_errors.log
> 
> logfile=os.getcwd()
> print logfile is correct; but when I add the .rstrip('src/oship/atbldr')
> it also strips the 'shop' off of LNCCWorkshop and returns
> /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/
at_build_errors.log
> 
> I had two other people looking at this as we did troubleshooting and we
> could not determine the cause.  It is repeatable with this path name. In
> resolution I renamed the branch to just LNCC and it works fine.
> 
> Thoughts?
> 
> Tim

Is this the Tim Cook I worked with at UCI?

Anyway, I think the os.path module might have something for you.  As a 
little bonus, it should produce code that works well with other operating 
systems, and should deal gracefully with repeated slashes.

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


wx.Timer not working

2008-07-26 Thread 5lvqbwl02
Windows XP SP3
Python 2.5
wx.version() = '2.8.1.1 (msw-unicode)'
--
I have written the following *simplest* implementation of wx.timer I
can think of.  No workie.   I want an exception, a print statement, or
something.

The wxpython demos all work, but for some reason this isn't.  The
demos are simple and straghtforward, so I think I understand how it
should work.  Clues please?  I've tried variations of ID's, SetOwners,
using and redefining Notify(), Bind, Connect, etc.  In the cases where
the interpreter doesn't complain about passed argument types, the
callback function is never called.


import wx

class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, pos=(100, 100))

timer = wx.Timer(self, -1)
self.Bind(wx.EVT_TIMER, self.OnTick, timer)
timer.Start(100)

def OnTick(self, event):
print 'Hi. Bye.'
1/0 #<-- should crash as evidence callback is being called

class MyApp(wx.App):
def OnInit(self):
frame1 = MyFrame(None, wx.ID_ANY, "This is a test")
frame1.Show(True)
return True

app = MyApp(0)
app.MainLoop()


Thanks for any advice!!

Michael




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


Re: Simple Path issues

2008-07-26 Thread Brett Ritter
On Jul 26, 2:57 pm, Gary Josack <[EMAIL PROTECTED]> wrote:
> sys.path is a list that will tell you where python is looking. You can
> append to this in your scripts to have python look in a specific
> directory for your own modules.

I can, but that is almost certainly not the standard way to develop a
module.

I see nothing in sys.path that I have write permissions to.

Is altering my PYTHONPATH the normal way to develop (under the
assumption that later users will install in their conventional python
search path)?

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


Re: urllib and login with passwords

2008-07-26 Thread Rob Williscroft
Jive Dadson wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

> Hey folks!
> 
> There are various web pages that I would like to read using urllib, but 
> they require login with passwords. Can anyone tell me how to find out 
> how to do that, both in general and specifically for YouTube.com.
> 

A typical pattern is submit a form to login and get a cookie back,
subsuquent request with the cookie set are then "loged in".

import cookielib, urllib2

cj = cookielib.CookieJar()

opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj) )

page = opener.open( LOGIN_URL, data = LOGIN_FORM )
page.close()

page = opener.open( DOWNLOAD_URL )

print page.read() 
page.close()


You will need to work out what goes in LOGIN_FORM, it likely
something like:

LOGIN_FORM = "username=name&password=pass&submit-button=Some+value"

where username, password and submit-button are the name of the 
controls on the form you would normally login from.

If the form has an enctype='multipart/form-data' then things
get a little more complex, possibly start here:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Russ P.

> If, as I wrote, you permit the omission of "self" in method signatures
> defined within class definitions, then you could still insist on
> instance attribute qualification using "self" - exactly as one would
> when writing Java according to certain style guidelines.

I'm not sure exactly what people mean here by allowing "self" to be
"omitted" in method signatures. If it is omitted, then it seems to me
that a place holder would be needed to the interpreter that the first
argument is not just another name for "self."

In an earlier post on this thread (don't feel like looking it up at
the moment), someone suggested that member data could be accessed
using simply ".member". I think he might be on to something. The dot
is a minimal indicator that the data is a class member rather than
just local. However, a placeholder is still needed in the signature.

So why not allow something like this?:

class MyClass:

def func( , xxx, yyy):

.xxx = xxx

local = .yyy

The "self" argument is replaced with nothing, but a comma is used as a
placeholder.

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


Re: Execution speed question

2008-07-26 Thread Eric Wertman
> The number of nodes is very large: millions for sure, maybe tens
> of millions.  If considering (2), take note of my BOLD text above, which
> means I can't remove nodes as I iterate through them in the main loop.

Since your use of 'node' is pretty vague and I don't have a good sense
of what tests you are running and how long they would take,  I'm only
speculating, but a single loop might be the wrong way to go about
that.

If you are going to be frequently running tests and switching nodes
on/off, have you considered a separate set of processes to do both?
For example:


A set of some number of "tester" threads, that loop through and test,
recording thier results (somewhere).


You could then have a separate loop that runs every so often, checks
all the current test values, and runs through the nodes once,
switching them on or off.


I know it's not exactly what you asked, but depending on what your
nodes are exactly, you can avoid a lot of  other problems down the
road.  What if your single loop dies or gets hung on a test?  With a
separate approach, you'll have a lot more resilience too.. if there's
some problem with a single tester or node, it won't keep the rest of
the program from continuing to function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.walk question

2008-07-26 Thread Eric Wertman
I do this, mabye a no-no?


import os

for root,dirs,files in os.walk(dir) : break
--
http://mail.python.org/mailman/listinfo/python-list


Re: wx.Timer not working

2008-07-26 Thread Vlastimil Brom
2008/7/26 <[EMAIL PROTECTED]>

> Windows XP SP3
> Python 2.5
> wx.version() = '2.8.1.1 (msw-unicode)'
> --
> I have written the following *simplest* implementation of wx.timer I
> can think of.  No workie.   I want an exception, a print statement, or
> something.
>
> The wxpython demos all work, but for some reason this isn't.  The
> demos are simple and straghtforward, so I think I understand how it
> should work.  Clues please?  I've tried variations of ID's, SetOwners,
> using and redefining Notify(), Bind, Connect, etc.  In the cases where
> the interpreter doesn't complain about passed argument types, the
> callback function is never called.
>
>
> import wx
>
> class MyFrame(wx.Frame):
>def __init__(self, parent, id, title):
>wx.Frame.__init__(self, parent, id, title, pos=(100,
> 100))
>
>timer = wx.Timer(self, -1)
>self.Bind(wx.EVT_TIMER, self.OnTick, timer)
>timer.Start(100)
>
>def OnTick(self, event):
>print 'Hi. Bye.'
>1/0 #<-- should crash as evidence callback is being called
>
> class MyApp(wx.App):
>def OnInit(self):
>frame1 = MyFrame(None, wx.ID_ANY, "This is a test")
>frame1.Show(True)
>return True
>
> app = MyApp(0)
> app.MainLoop()
>
>
> Thanks for any advice!!
>
> Michael
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Hi,

not exactly sure, but compared to the demo, it seems to be a binding
problem;

Using "self.timer" instead of "timer" in the __init__ section

and

self.Bind(wx.EVT_TIMER, self.OnTick)
instead of

self.Bind(wx.EVT_TIMER, self.OnTick, timer)

seems to work;

HTH,

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

Re: An Attempt to download and install traits - to a Windows XP

2008-07-26 Thread Colin J. Williams

Robert,

Many thanks, this has put me on track.

Colin W.

Robert Kern wrote:

On Jul 25, 5:37 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:

Using >easy_install -v 
-fhttp://code.enthought.com/enstaller/eggs/sourceenthought.traits

The result is:

...
   many lines
...

copyingenthought\traits\ui\tests\shell_editor_test.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\table_editor_color_test.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\table_editor_focus_bug.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\table_editor_test.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\table_editor_test2.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\table_list_editor_test.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
copyingenthought\traits\ui\tests\tree_editor_test.py
->
build\lib.win32-2.5\enthought\traits\ui\tests
running build_ext
error: Setup script exited with error:
Python was built with Visual Studio 2003;
extensions must be built with a compiler
than can generate compatible binaries.
Visual Studio 2003 was not found on this
system. If you have Cygwin installed,
you can try compiling with MingW32, by
passing "-c mingw32" to setup.py.


Traits includes an extension module. You will need a suitable
compiler.

  http://www.develer.com/oss/GccWinBinaries

To tell distutils to use this compiler for all extension modules,
create pydistutils.cfg file with the following contents:

  [build_ext]
  compiler=mingw32

See this page for details about this file:

  http://docs.python.org/inst/config-syntax.html

You will get the most help about Traits and the rest of the Enthought
Tool Suite on the enthought-dev mailing list.

  https://mail.enthought.com/mailman/listinfo/enthought-dev

--
Robert Kern

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


Re: tcp socket problem

2008-07-26 Thread Dan Stromberg
On Fri, 25 Jul 2008 16:09:13 -0700, jm.carp wrote:

> I'm writing a tcp client that grabs data from a server at 32hz. But the
> connection drops exactly one minute after it's opened. I can get data
> from the server fine for the first 60s, and then the connection goes
> dead. What's going on?

What does "goes dead" mean in this case?  Is python giving a traceback?  
Is some I/O blocking?

I'd probably use a system call tracer to track down something like that, 
unless there's a useful traceback.  It may be useful in the client, or 
the server, or both.

http://stromberg.dnsalias.org/~strombrg/debugging-with-syscall-
tracers.html

Also, be careful to check that you aren't reading two chunks when you 
think you're getting one or something.  That could cause some I/O to 
block in a hard-to-track-down way.  IOW, TCP feels free to chop your 
packets into multiple packets, or to aggregate multiple packets into a 
smaller number of them - whatever it wants, pretty much.  This sometimes 
helps performance or reliability, but it complicates writing socket 
programs at times.  Put another way, a single send might show up as two 
recv's, for example.

Oh, and using a sniffer may help too.  I like wireshark or tshark (GUI 
and text interfaces of the same underlying sniffer), but there are many 
available.  Old hands seem to prefer tcpdump, though I'm clear on why.  
If you fire up a sniffer against your network communication, it should be 
possible to see, for example, the last packet transferred, which system 
it was to, and which system it was from. You may not know which host is 
having the problem without a detailed knowledge of the protocol, but 
since you're coding the program, you may  have that.  :)  This may show 
packet splitting/aggregation too, but keep in mind that a sniffer only 
shows you the data stream at a particular point in the transfer - you 
could see different things when running a sniffer on the client, on the 
server, or even on a subnet in between the two.  Oh, and many networks 
are switched now, so most sniffers don't do that well on subnets in 
between, but they frequently still work well on the client and server 
themselves.

HTH



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


Re: SimpleJson is slow .... is there any C Compiled version ?

2008-07-26 Thread Dan Stromberg
On Sat, 26 Jul 2008 00:49:20 -0700, Richard Levasseur wrote:

> On Jul 25, 5:52 pm, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
>> Also, simplejson and python-cjson might not be entirely compatible:
>> there's one character that one escapes and the other doesn't, or
>> something. --
> 
> They also have different interface.  simplejson uses load/loads/dump/
> dumps, whereas cjson using encode/decode (its pretty simple to
> monkeypatch cjson with some lambda's so it has the same interface,
> though).
> 
> Yeah, its frustrating that there are so many json encoders for python. 
> Its a bit disappointing simplejson is going into the stdlib; i hope they
> rewrite it in C?

C's great for performance, but if you want something featureful and 
reliable, you're probably better off in something else - including but 
not limited to python, optionally with psyco.

I wish the pypy people would package up their stuff into a form that you 
can just ./configure && make && make install and then #! to - I believe 
it'd grow/mature faster than it is if they did (and they may have, but 
last time I looked it didn't appear so).  But once they do, that might be 
a convenient way of getting better performance.

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

Re: Attack a sacred Python Cow

2008-07-26 Thread Colin J. Williams

Russ P. wrote:

If, as I wrote, you permit the omission of "self" in method signatures
defined within class definitions, then you could still insist on
instance attribute qualification using "self" - exactly as one would
when writing Java according to certain style guidelines.


I'm not sure exactly what people mean here by allowing "self" to be
"omitted" in method signatures. If it is omitted, then it seems to me
that a place holder would be needed to the interpreter that the first
argument is not just another name for "self."

In an earlier post on this thread (don't feel like looking it up at
the moment), someone suggested that member data could be accessed
using simply ".member". I think he might be on to something. The dot
is a minimal indicator that the data is a class member rather than
just local. However, a placeholder is still needed in the signature.

So why not allow something like this?:

class MyClass:

def func( , xxx, yyy):

.xxx = xxx

local = .yyy

The "self" argument is replaced with nothing, but a comma is used as a
placeholder.

(+1) but why retain the leading comma in 
the argument list?


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


Re: Attack a sacred Python Cow

2008-07-26 Thread Terry Reedy



Carl Banks wrote:

On Jul 24, 4:11 am, Jordan <[EMAIL PROTECTED]> wrote:

Of course not.

I just think Explicit is better than Implicit is taken seriously by a
large segment the Python community as a guiding principle,


Yeah, try telling that to the people who advise writing "if x" instead
of "if x==0", or "if s" instead of "if len(s)==0".


Whether or not one should write 'if x' or 'if x != 0' [typo corrected] 
depends on whether one means the general 'if x is any non-null object 
for which bool(x) == True' or the specific 'if x is anything other than 
numeric zero'.  The two are not equivalent.  Ditto for the length example.


What people do properly advise against is the strictly redundant 'if x 
is True' or 'if x == True'.  Both imply a misunderstanding of how 'if' 
works in Python.


As a side note, the usefulness of specific comparisons is greater in 3.0 
where spurious comparisons raise exceptions.  In 3.0, 'if x >= 0' 
specifically means 'if x is a number comparable to ints that is greater 
than or equal to 0'.  In 3.0, [] ==/!= 0 are still False/True, but one 
could exclude incomparables with 'if 0 <= x >= 0' (==0) or 'if x > 0 or 
x < 0' (!=0).  Any such specific comparisons could be used with this 
pattern.


try:
x = []
if x >= 0:
print('should not get here')
except TypeError as m:
if m.args[0].startswith('unorderable types:'):
print('Here because of bad comparison')

Terry Jan Reedy

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Terry Reedy



Torsten Bronger wrote:

Hallöchen!

Terry Reedy writes:


[...]

Or the proposal would have to be that 'self' is mandatory for all
programmers in all languages.  I think *that* would be
pernicious. People are now free to write the more compact 's.sum =
s.a + s.b + s.c' if they want instead of the 'self' version.  And
again, not everyone writes in English.


Of course, "self" would have to become a reserved word.  You could
say that this may break some code,


Will break.


but I don't see much freedom removed from the language.

>  After all, being a German, I still can't

write "Für i in range(10)".  ;-)


But you can write 'for ubermenchen in range(10):' and in 3.0, with 
diacritics added.  Would you really feel no loss of freedom if Guido 
make i0, i1, ... into keywords, which means they could not be used 
elsewhere, and mandated them as for loop index variables?


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


Re: pixel colour on screen

2008-07-26 Thread chris
On Jun 30, 4:37 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
> >Could anyone help me, I'm a python noob and need some help. im trying
> >to find some code that will, given ascreenco-ordinate, will give me
> >thecolourof thatpixelin RGB. i have found a lot about getting the
> >pixelcolourfrom a picture file with a given co-ordinate, but is it
> >possible to do it from the wholescreenoutput regardless what
> >application the selectedpixelis in?
>
> Which operating system?  If you are on Windows, and you have pywin32
> loaded. you can use the Windows APIs GetDC and GetPixel.
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

i have ubuntu hardy. does that help?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-26 Thread Russ P.

> > So why not allow something like this?:
>
> > class MyClass:
>
> > def func( , xxx, yyy):
>
> > .xxx = xxx
>
> > local = .yyy
>
> > The "self" argument is replaced with nothing, but a comma is used as a
> > placeholder.
>
> (+1) but why retain the leading comma in
> the argument list?

As I said, the leading comma is a place holder. Without it, the
interpreter would have no way of knowing that the first argument is
not just another name for "self."

We need to maintain compatibility with existing Python rules. If we
were designing a new language, we could omit the "self" argument in
the signature, and allow either ".xxx" or "self.xxx," at the
programmers discretion (i.e., let "self" be the standard name, like
"this" in C++).

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Terry Reedy



Nikolaus Rath wrote:


I think you misunderstood him.


I did, but addressed the below in another post.

> What he wants is to write




 > class foo:

   def bar(arg):
   self.whatever = arg + 1

instead of

class foo:
   def bar(self, arg)
   self.whatever = arg + 1

so 'self' should *automatically* only be inserted in the function
declaration, and *manually* be typed for attributes.


which means making 'self' a keyword just so it can be omitted.  Silly 
and pernicious.


tjr

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Terry Reedy



Torsten Bronger wrote:

Hallöchen!

D'Arcy J.M. Cain writes:


On Sat, 26 Jul 2008 09:45:21 +0200
Torsten Bronger <[EMAIL PROTECTED]> wrote:


Of course, "self" would have to become a reserved word.  You
could say that this may break some code, but I don't see much
freedom

Isn't this a showstopper all by itself?


Yes.  But I've seen no code that uses some other word.


There is a lot of code you have not seen.  Really.  In informal code I 
use 's' and 'o' for 'self' and 'other'.  I don't usually post such 
because it is not considered polite.  So you have seen a biased sample 
of the universe.


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


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

Terry Reedy writes:

> Torsten Bronger wrote:
>
>> Terry Reedy writes:
>>
>>> [...]
>>>
>>> Or the proposal would have to be that 'self' is mandatory for
>>> all programmers in all languages.  I think *that* would be
>>> pernicious. People are now free to write the more compact 's.sum
>>> = s.a + s.b + s.c' if they want instead of the 'self' version.
>>> And again, not everyone writes in English.
>>
>> Of course, "self" would have to become a reserved word.  You
>> could say that this may break some code,
>
> Will break.

No more than Python 3.0 breaks.

>> but I don't see much freedom removed from the language.  After
>> all, being a German, I still can't write "Für i in range(10)".
>> ;-)
>
> But you can write 'for ubermenchen in range(10):' and in 3.0, with
> diacritics added.  Would you really feel no loss of freedom if
> Guido make i0, i1, ... into keywords, which means they could not
> be used elsewhere, and mandated them as for loop index variables?

I would, but I consider "self" becoming a keyword not even in the
same league as i0, i1 etc.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Insert string into string

2008-07-26 Thread Francesco Pietra
I am posting ex novo as it became confusing to me. I take the
opportunity to ask advice for a second problem.

FIRST PROBLEM
For file xxx.pdb, insert letter "A" into each line that starts with
"ATOM". "A" should be inserted at position 22, i.e., one space after
"LEU", leaving all other characters at the same position as in the
original example:


ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   1SG   2

In all lines starting with "ATOM", "LEU" is constant as to position
only (18-20), i.e., "LEU" may be replaced by
three different uppercase letters. Therefore, the most direct
indication would be position 22. If specifying line starting with
"ATOM" makes complication, forget about that as most lines begin with
"ATOM" so that hand correction will be easy.

Script
f = open("xxx.pdb", "w")
import sys

for line in sys.stdin:
line = line[:22] + "A" + line[23:]
sys.stdout.write(line)

destroys the .pdb file and python exits witha non zero exit status.

The same occurs with script

f = open("hASIC1a.B0003.pdb", "w")
f.write(' line = line[:22] + "A" + line[23:]')
f.close()

I must have misunderstood the suggestion I received on previous posting.

SECOND PROBLEM
File xxx.pdb above has 426 lines stating with "ATOM", this serial
number occupying positions 7-11, right justified (Thus 1, as in the
line example above, means first line). A second, similar file yyy.pdb
has to be concatenated to xxx.pdb. Before that it should be added of
"A" as above and renumbered at position 7-11, starting from 428 (there
is an intermediate line to add). How should a script look like for
this string insertion into string with recursive +1?


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


Re: Attack a sacred Python Cow

2008-07-26 Thread Terry Reedy



Paul Boddie wrote:

On 26 Jul, 06:06, Terry Reedy <[EMAIL PROTECTED]> wrote:

Paul Boddie wrote:

"The problem is that the explicit requirement to have self at the
start of every method is something that should be shipped off to the
implicit category."


Here, I presume that the author meant "at the start of every method
signature".


There is no requirement to have 'self' in the parameter list.  It can be
's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or
any other identifier in whatever language.


But Jordan apparently wanted to omit that parameter. The omission of
all mentions of "self" could be regarded as a bonus, but it's a non-
trivial goal.


Reword.  There is no requirement to name the instance anything in 
particular.  Thus there is no requirement at present that the first 
parameter, which gives the name of the instance, be anything in 
particular.



In 3.0, identifiers are not restricted to ascii but can be any unicode
'word' as defined in the manual.

So the proposal would have to be that the compiler scan the function
body and decide which dotted name prefix is the one to be implicitly
added.  Have fun writing the discovery algorithm.  However, I think this
is pretty silly.  Just write the name you want.


If, as I wrote, you permit the omission of "self" in method signatures
defined within class definitions, then you could still insist on
instance attribute qualification using "self" - exactly as one would
when writing Java according to certain style guidelines.


Which is what I said in the first sentence of my next paragraph, which 
you clipped.
"Or the proposal would have to be that 'self' is mandatory for all 
programmers in all languages."  To clarify " ... that 'self' be the 
mandatory instance name for all Python programmers regardless of 
inclination or the natural language they otherwise use as a basis for 
identifiers."


In sum, if the instance name is omitted from the parameter list, it must 
either be discovered or mandated, and def statements in direct class 
scope have to be treated differently from def statements elsewhere.


Terry Jan Reedy

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Torsten Bronger
Hallöchen!

Terry Reedy writes:

> Torsten Bronger wrote:
>
>> D'Arcy J.M. Cain writes:
>>
>>> On Sat, 26 Jul 2008 09:45:21 +0200
>>> Torsten Bronger <[EMAIL PROTECTED]> wrote:
>>>
 Of course, "self" would have to become a reserved word.  You
 could say that this may break some code, but I don't see much
 freedom
>>>
>>> Isn't this a showstopper all by itself?
>>
>> Yes.  But I've seen no code that uses some other word.
>
> There is a lot of code you have not seen.  Really.  In informal
> code I use 's' and 'o' for 'self' and 'other'.  I don't usually
> post such because it is not considered polite.  So you have seen a
> biased sample of the universe.

I didn't say that no code breaks, nor that I've analysed more than
0.1% of the global Python code.  But still, this doesn't convice me.
I still think that only a very small fraction of Python code would
break.  Since no one can make a global analysis, it is more sensible
to compare it with the amount of code broken by Python 3.0 in my
opinion.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: wx.Timer not working

2008-07-26 Thread Mike Driscoll
On Jul 26, 2:33 pm, [EMAIL PROTECTED] wrote:
> Windows XP SP3
> Python 2.5
> wx.version() = '2.8.1.1 (msw-unicode)'
> --
> I have written the following *simplest* implementation of wx.timer I
> can think of.  No workie.   I want an exception, a print statement, or
> something.
>
> The wxpython demos all work, but for some reason this isn't.  The
> demos are simple and straghtforward, so I think I understand how it
> should work.  Clues please?  I've tried variations of ID's, SetOwners,
> using and redefining Notify(), Bind, Connect, etc.  In the cases where
> the interpreter doesn't complain about passed argument types, the
> callback function is never called.
>
> import wx
>
> class MyFrame(wx.Frame):
>         def __init__(self, parent, id, title):
>                 wx.Frame.__init__(self, parent, id,     title, pos=(100, 100))
>
>                 timer = wx.Timer(self, -1)
>                 self.Bind(wx.EVT_TIMER, self.OnTick, timer)
>                 timer.Start(100)
>
>         def OnTick(self, event):
>                 print 'Hi. Bye.'
>                 1/0 #<-- should crash as evidence callback is being called
>
> class MyApp(wx.App):
>         def OnInit(self):
>                 frame1 = MyFrame(None, wx.ID_ANY, "This is a test")
>                 frame1.Show(True)
>                 return True
>
> app     = MyApp(0)
> app.MainLoop()
>
> Thanks for any advice!!
>
> Michael

I'm not seeing anything either. Please post this to the wxPython
user's group for additional help:

http://www.wxpython.org/maillist.php

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


Re: os.walk question

2008-07-26 Thread Terry Reedy



Eric Wertman wrote:

I do this, mabye a no-no?


It is a roundabout way to do multiple assignment:


import os



for root,dirs,files in os.walk(dir) : break


root,dirs,files = os.walk(dir).next #2.x
root,dirs,files = next(os.walk(dir))#3.x

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


Re: wx.Timer not working

2008-07-26 Thread 5lvqbwl02
On Jul 26, 3:13 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Jul 26, 2:33 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Windows XP SP3
> > Python 2.5
> > wx.version() = '2.8.1.1 (msw-unicode)'
> > --
> > I have written the following *simplest* implementation of wx.timer I
> > can think of.  No workie.   I want an exception, a print statement, or
> > something.
>
> > The wxpython demos all work, but for some reason this isn't.  The
> > demos are simple and straghtforward, so I think I understand how it
> > should work.  Clues please?  I've tried variations of ID's, SetOwners,
> > using and redefining Notify(), Bind, Connect, etc.  In the cases where
> > the interpreter doesn't complain about passed argument types, the
> > callback function is never called.
>
> > import wx
>
> > class MyFrame(wx.Frame):
> >         def __init__(self, parent, id, title):
> >                 wx.Frame.__init__(self, parent, id,     title, pos=(100, 
> > 100))
>
> >                 timer = wx.Timer(self, -1)
> >                 self.Bind(wx.EVT_TIMER, self.OnTick, timer)
> >                 timer.Start(100)
>
> >         def OnTick(self, event):
> >                 print 'Hi. Bye.'
> >                 1/0 #<-- should crash as evidence callback is being called
>
> > class MyApp(wx.App):
> >         def OnInit(self):
> >                 frame1 = MyFrame(None, wx.ID_ANY, "This is a test")
> >                 frame1.Show(True)
> >                 return True
>
> > app     = MyApp(0)
> > app.MainLoop()
>
> > Thanks for any advice!!
>
> > Michael
>
> I'm not seeing anything either. Please post this to the wxPython
> user's group for additional help:
>
> http://www.wxpython.org/maillist.php
>
> Mike


I think I figured it out.  By looking at the wxTimer example here:
http://wiki.wxpython.org/AnotherTutorial#head-420329f7c159d81cb03a6dd226ddb822ea296c92

My code created a temporary timer object and did not make it a class
member.  When I changed it to be a class member with self.timer, then
it worked.

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


Re: Attack a sacred Python Cow

2008-07-26 Thread Carl Banks
On Jul 26, 5:07 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Whether or not one should write 'if x' or 'if x != 0' [typo corrected]
> depends on whether one means the general 'if x is any non-null object
> for which bool(x) == True' or the specific 'if x is anything other than
> numeric zero'.  The two are not equivalent.  Ditto for the length example.

Can you think of any use cases for the former?  And I mean something
where it can't be boiled down to a simple explicit test for the sorts
of arguments you're expecting; something that really takes advantage
of the "all objects are either true or false" paradigm.

The best thing I can come up with out of my mind is cases where you
want to check for zero or an empty sequence, and you want to accept
None as an alternative negative as well.  But that's pretty weak.

The use case of simply passing something to a function that accepts
any boolean doesn't count.  For instance, I could write:

def nand(a,b):
return not (a and b)

And then I could use it like this, even if x is an interger and y a
string:

if nand(x,y):

But that doesn't buy much since I could just pass in the explicit
tests like this:

if nand(x!=0,y!=""):


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


Re: urllib and login with passwords

2008-07-26 Thread Jive Dadson
Thanks, Rob!  Some of that is beyond my maturity level, but I'll try to 
figure it out.  If anyone has specific info on about how YouTube does 
it, I would appreciate the info.

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


Re: Insert character at a fixed position of lines

2008-07-26 Thread Lie Ryan
On Sat, 2008-07-26 at 17:47 +0200, Francesco Pietra wrote:
> Sorry to come again for the same problem. On commanding:
> 
> $ python script.py 2>&1 | tee fileout.pdb
> 
> nothing occurred (fileout.pdb was zero byte). The script reads:
> 
> f = open("xxx.pdb", "w")
> f.write('line = line[:22] + "A" + line[23:]')
> f.close()
> 
> File xxx.pdb is opened by the command: when I forgot the single quote
> ' after [23:] the error answer was:
> SynthaxError: EOL while scanning single-quoted string.
> 
> Thanks
> francesco

I'd expect fileout.pdb to be zero bytes, what you have piped to tee
fileout.pdb is the stdout of your script, i.e. whatever you "print".
Since you "print"ed nothing, nothing is written to fileout.pdb 

You'd find your written material in the file referenced by f, i.e.
"xxx.pdb". 

Btw, if you do f.write('line = line[:22] + "A" + line[23:]'), you'd
output exactly that, and not inserting the 23rd character, you'd want to
do this instead: f.write(line = line[:22] + "A" + line[23:])

> On Sat, Jul 26, 2008 at 1:10 PM, Lie <[EMAIL PROTECTED]> wrote:
> > On Jul 26, 5:42 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> >> I am still at the stone age, using scripts (e.g., to insert a string
> >> after a string) of the type
> >>
> >> f = open("xxx.pdb", "r")
> >> for line in f:
> >>print line
> >>if "H16Z POPC" in line:
> >>print "TER"
> >> f.close()
> >>
> >> That is, I have to learn about modules. In your scripts I am lost
> >> about the filename for the pdb file to modify,
> >
> > In Python, stdin and stdout (as provided by the sys module) is a file-
> > like object, i.e. it have similar behavior as regular files you opened
> > with open(). stdin is a read-only file, while stdout is a write-only
> > file. You already know how to make read-only file, f = open("xxx.pdb",
> > "r"), to make it writable, you've got to use 'w' as the mode: f =
> > open("xxx.pdb", "w")
> >
> > After that you can do this:
> > f.write('some string')
> >
> >
> >> francesco
> >>
> >>
> >>
> >> On Sat, Jul 26, 2008 at 11:35 AM, Lie <[EMAIL PROTECTED]> wrote:
> >> > On Jul 26, 2:41 pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> >> >> How to insert letter "A" on each line (of a very long list of lines)
> >> >> at position 22, i.e., one space after "LEU", leaving all other
> >> >> characters at the same position as in the original example:
> >>
> >> >> ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04  
> >> >>  1SG   2
> >>
> >> >> In all lines"ATOM" is constant as to both position and string, while
> >> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
> >> >> three different uppercase letters. Therefore, the most direct
> >> >> indication would be position 22.
> >>
> >> >> Should the script introduce blank lines, no problem. That I know how
> >> >> to correct with a subsequent script.
> >>
> >> >> Thanks
> >> >> chiendarret
> >>
> >> > If you want to leave the rest of the strings as-is (i.e. the letter A
> >> > overwrites whatever on position 22), Peter's code need to be modified
> >> > a little:
> >> > line = line[:22] + " " + line[23:]
> >> > --
> >> >http://mail.python.org/mailman/listinfo/python-list
> >>
> >> --
> >> Dr Francesco Pietra
> >> Professor of Chemistry
> >> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594
> >> Palazzo Ducale
> >> 55100 Lucca (Italy)
> >> e-mail [EMAIL PROTECTED]
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >

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

Re: Insert string into string

2008-07-26 Thread Mensanator
On Jul 26, 4:40�pm, "Francesco Pietra" <[EMAIL PROTECTED]> wrote:
> I am posting ex novo as it became confusing to me. I take the
> opportunity to ask advice for a second problem.
>
> FIRST PROBLEM
> For file xxx.pdb, insert letter "A" into each line that starts with
> "ATOM". "A" should be inserted at position 22, i.e., one space after
> "LEU", leaving all other characters at the same position as in the
> original example:
>
> ATOM � � �1 �N � LEU � � 1 � � 146.615 �40.494 103.776 �1.00 73.04 � � � 1SG 
> � 2
>
> In all lines starting with "ATOM", "LEU" is constant as to position
> only (18-20), i.e., "LEU" may be replaced by
> three different uppercase letters. Therefore, the most direct
> indication would be position 22. If specifying line starting with
> "ATOM" makes complication, forget about that as most lines begin with
> "ATOM" so that hand correction will be easy.
>
> Script
> f = open("xxx.pdb", "w")
> import sys
>
> for line in sys.stdin:
> � � line = line[:22] + "A" + line[23:]
> � � sys.stdout.write(line)
>
> destroys the .pdb file and python exits witha non zero exit status.
>
> The same occurs with script
>
> f = open("hASIC1a.B0003.pdb", "w")
> f.write(' line = line[:22] + "A" + line[23:]')
> f.close()
>
> I must have misunderstood the suggestion I received on previous posting.
> 
> SECOND PROBLEM
> File xxx.pdb above has 426 lines stating with "ATOM", this serial
> number occupying positions 7-11, right justified (Thus 1, as in the
> line example above, means first line). A second, similar file yyy.pdb
> has to be concatenated to xxx.pdb. Before that it should be added of
> "A" as above and renumbered at position 7-11, starting from 428 (there
> is an intermediate line to add). How should a script look like for
> this string insertion into string with recursive +1?
>
> Thanks
> francesco

I don't know why you're using stdin if you're reading from a file.

Also, the serial number isn't 7-11, it's 6-10 (remember to
count from 0, so character 1 is position 0, etc.)

fx = open('xxx.pdb','r') # first input file
fy = open('yyy.pdb','r') # second input file
fz = open('zzz.pdb','w') # output file (to be created)

for xline in fx: # read input one line at a time
  if len(xline) >= 80:   # don't process invalid lines
line_index = int(xline[7:12]) # keep track of this
if xline[:4]=='ATOM':
  fz.write(xline[:22] + 'A' + xline[23:])
else:
  fz.write(xline)

fx.close() # done with first file

fz.write('the extra line \n')
line_index += 1   # don't forget to count it

for yline in fy:  # read second file
  if len(yline) >= 80:# again, valid only
line_index += 1   # ignore serial number, use
  #   where we left off from
  #   from first file
if yline[:4]=='ATOM':
  # note use of .rjust(5) to creat new serial number
  fz.write(yline[:6] + \
   str(line_index).rjust(5) + \
   yline[11:22] + 'A' + yline[23:])
else:
  fz.write(yline[:6] + \
   str(line_index).rjust(5) + yline[11:])

fy.close() # done with second file

fz.close() # done with output file
--
http://mail.python.org/mailman/listinfo/python-list

Re: scanf in python

2008-07-26 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, AMD wrote:

>> In message <[EMAIL PROTECTED]>, AMD wrote:
>> 
>>> Actually it is quite common, it is used for processing of files not for
>>> reading parameters. You can use it whenever you need to read a simple
>>> csv file or fixed format file which contains many lines with several
>>> fields per line.
>> 
>> I do that all the time, in Python and C++, but I've never felt the need
>> for a scanf-type function.
> 
> I agree scanf is not a must have function but rather a nice to have
> function.

I've never felt that scanf would be "nice" to have. Not in Python, not in
C++.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function editing with Vim throws IndentError

2008-07-26 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Matimus
wrote:

> On Jul 24, 9:32 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> central.gen.new_zealand> wrote:
>
>> In message
>> <[EMAIL PROTECTED]>,
>> Matimus wrote:
>>
>> > On Jul 24, 2:54 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
>> > central.gen.new_zealand> wrote:
>> >> In message
>> >> <[EMAIL PROTECTED]>,
>>
>> >> Matimus wrote:
>> >> > That isn't the standard. With that setup tabs will show up as 4
>> >> > spaces, and still confuse you.
>>
>> >> Why should that be confusing? The most common tab-stop setting is 4
>> >> columns.
>>
>> > A tab character is specified as 8 spaces.
>>
>> Specified by whom? The most common setting these days is 4 columns.
> 
> All argument about specification aside, Python interprets a tab
> character as equivalent to 8 spaces. If you are treating tabs as
> equivalent to 4 spaces in your python code it will cause
> IndentationError exceptions to be raised.

I have Emacs configured to show tabs as 4 columns wide, and I've never had
such an exception happen in my Python code as a result.
--
http://mail.python.org/mailman/listinfo/python-list

  1   2   >