Re: Python Pop Quiz

2007-06-02 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Roy Smith
wrote:

 In article [EMAIL PROTECTED],
  [EMAIL PROTECTED] wrote:
 7. How many Z80 assembly language programmers does it take to equal
 one Python guru?
 
 Trick question, the Z80 was a figment of your imagination.

http://en.wikipedia.org/wiki/Zilog_Z80

 Essay: C++ is better than C, agree or disagree? (four word maximum)
 
 STL compile error diagnostics.

So do you agree or disagree!?  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange PyLint configuration

2007-06-01 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Bjoern Schliessmann wrote:

 [ripped out of context :-)]
 Has this been updated recently? I could've sworn I had read that
 stuff like has_key was old.

Yes, `has_key()` is old, it's spelled ``in`` these days.  :-)

if mapping.has_key(ham): pass

# -

if ham in mapping: pass

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: c[:]()

2007-06-01 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Warren Stringer
wrote:

 I like your use case. Am I correct in assuming that `y = x[:]; y()` is NOT
 to be found in working code? If that is the case, then nothing gets broken.
 It would be instructive to have a use case where enabling c[:]() would break
 existing code. 

What does enabling c[:]() mean?  Do you expect after enabling it
``c()`` and ``c[:]()`` to be different for the same list or tuple `c`?

 My use case is this:
 
   do(orchestra(score)).pickle()
   do(orchestra(conductor)).sequence()

This isn't a use case unless you also say what the involved objects are
and what semantic you expect from this source snippet.  Just guessing,
but might the following do what you want without the need to make lists
and tuples callable?

def do(iterable, func):
for item in iterable:
func(item)

do(orchestra(score), pickle)
do(orchestra(conductor), sequence)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: c[:]()

2007-06-01 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Warren Stringer
wrote:

 Warren Stringer wrote:
 
  As mentioned a while back, I'm now predisposed towards using `do(c)()`
  because square brackets are hard with cell phones. The one mitigating
 factor
  for more general use, outside of cell phones, is speed.
 
 The speed at which you can type code is almost _never_ a valid reason to
 make something brief.  Code gains readability from verbosity.  (That can
 be taken too far, of course, but that certainly doesn't apply here.)
 
 There is code that you type which persists and code that you type from a
 command line. Two completely different idioms. A credo inside the cell phone
 game industry is that you lose half your audience with each menu keystroke.
 That's how precious keystrokes are. 
 
 What may be confusing is speaking about both idioms at once. 
 
 snip
 
 In short, your repeated use of `c[:]()` indicates a fundamental
 misunderstanding about Pythonic style _and_ substance.
 
 Please define Pythonic. Is this like a certain US senator who defined porn
 as I know it when I see it.

Yes you are right, pythonic is not a hard fact.  But one indicator is
consistency and no surprising behavior if possible.  And that your
insisting on ``c[:]()`` instead of just ``c()`` seems to indicate you want
a change that is quite surprising.  It would mean that a slice of a list
returns an other type with the __call__ method implemented.

 28 years ago, I wrote a hierarchical DBMS that used lexical indentation. 15
 years ago I wrote a multimedia script language that used lexical indentation
 and automatic garbage collection - it was deployed on millons of clients. 2
 years ago I hand coded every line of the Python 2.2 BNF into another style
 of language description. Up until last month, I had tokenized a subset of
 said definition in C++, using templates to manage cardinality. Recently, I
 decided to forgo the C++ parser and am now rewriting it in Python. This is a
 risk. So, what hoop does one jump though to earn that oh so coveted
 pythonic merit badge?

Grok The Zen of Python (``import this`` at the interpreter prompt)? 
Write pythonic code?

I don't see how writing other languages and Python parsers and translators
into other representations tells you much about the spirit and idiomatic
*usage* of a language.  Your proposal is not about syntax, it's about
semantics.  ``obj[:]()`` is basically syntactic sugar for:
``obj.__getitem__(slice(None)).__call__()`` and you want a change in the
implementation of `list.__getitem__()` and `tuple.__getitem__()`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: c[:]()

2007-05-31 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Warren Stringer
wrote:

 Oops! guess I should have tested my rather hasty complaint about executable
 containers. This is nice:
 
 def a(): return 'b'
 def b(): print 'polly! wakey wakey'
 c = {}
 c['a'] = b
 c[a()]()  #works!
 
 
 c[a()]() is a switch statement with an amorphous selector- very handy in its
 own right. But, using a() as a generator would be more expressive. This
 seems to work:
 
 c = [a,a]
 [d() for d in c]

If you are using the list comprehension just for the side effect of
calling `d` then consider this bad style.  You are building a list of
`None` objects just to have a cool one liner then.

 But that still isn't as simple or as direct as:
 
 c[:]()
 
 Which would you rather explain to a 12-year-old writing code for the first
 time?

for func in funcs:
func()

Because it is explicit and readable and matches the english description
for every function in functions: call that function very closely while a
list comprehension or your perlish line noise is much more magic to
explain and harder to remember.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory handling

2007-05-31 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], frederic.pica
wrote:

 So as I can see, python maintain a memory pool for lists.
 In my first example, if I reparse the xml file, the memory doesn't
 grow very much (0.1 Mb precisely)
 So I think I'm right with the memory pool.
 
 But is there a way to force python to release this memory ?!

AFAIK not.  But why is this important as long as the memory consumption
doesn't grow constantly?  The virtual memory management of the operating
system usually takes care that only actually used memory is in physical
RAM.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-31 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], kc wrote:

 Joe Riopel [EMAIL PROTECTED] writes:
 
 Using camel case instead of the under_score means less typing. I am lazy.

 fooBar
 foo_bar
 Each requires exactly the same number of key strokes when I do the
 math. (Too lazy to explain further...)

Let's leave 'foo' and 'ar':

1. B = Shift + B = 2 key strokes.
2. _b = Shift + - and b = 3 key strokes.

At least on my keyboard + layout.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file reading by record separator (not line by line)

2007-05-31 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Lee Sander
wrote:

 Dear all,
 I would like to read a really huge file that looks like this:
 
 name1
 line_11
 line_12
 line_13
 ...
name2 ...
 line_21
 line_22
 ...
 etc
 
 where line_ij is just a free form text on that line.
 
 how can i read file so that every time i do a read() i get exactly
 one record
 up to the next 

There was just recently a thread with a `itertools.groupby()` solution. 
Something like this:

from itertools import count, groupby, imap
from operator import itemgetter

def mark_records(lines):
counter = 0
for line in lines:
if line.startswith(''):
counter += 1
yield (counter, line)


def iter_records(lines):
fst = itemgetter(0)
snd = itemgetter(1)
for dummy, record_lines in groupby(mark_records(lines), fst):
yield imap(snd, record_lines)


def main():
source = \
 name1
line_11
line_12
line_13
...
 name2 ...
line_21
line_22
splitlines()

for record in iter_records(source):
print 'Start of record...'
for line in record:
print ':', line

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WEATHER PROGRAMMING IN PYTHON

2007-05-31 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], sandeep patil
wrote:

 how to diplay the weather condiction on my webpage
 suppose i want to read weather from www.bbc.co.uk/weather.html
 how i can read it usin program

It's hard to scrape information about weather from an 404 error page.  ;-)

Find some page with actual weather reports or forecasts and use the
BeautifulSoup module to scrape the information you need.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Error in optparse documentation

2007-05-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Shatadal
wrote:

 I think the documentation should be modified so that it is made clear
 that %default in the help string behaves as is claimed only in version
 2.4 and higher.

Maybe something should be added for clarity but I don't think it's an
error in the docs.  You are reading documentation for Python 2.5 and
expect everything in it to work in older versions too?

Pick the right documentation from http://www.python.org/doc/versions/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], half.italian
wrote:

 [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
 links]
 
 btw...I was curious of this too.  I used 'dir(dict)' and looked for a
 method that might do what we wanted and bingo!

This is really ugly.  Except `__init__()` it's always a code smell if you
call a magic method directly instead of using the corresponding
syntactic sugar or built in function.  And using a list comprehension just
for side effects is misleading because the reader expects a (useful) list
to be build when stumbling over a list comp and it's wasteful because an
unnecessary list of `None`\s is build and thrown away for no reason other
than to have a one liner.  This is not Perl!  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: totally lost newbie

2007-05-27 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], mark wrote:

 Hi all
 
 I posted earlier on this but have changed my approach so here is my
 latest attempt at solving a problem. I have been working on this for
 around 12 hours straight and am still struggling with it.
 
 Write a program that reads the values for a random list of cards from
 a file, where each line in the file specifies a single card with the
 rank and then the suit separated by a space. The rank should be an
 integer in the range of 1 to 13 (Ace:1, King:13), while the suit
 should be a lower case character in the set { 'h', 'd', 'c', 's' }.
 Sort the card entries into suits ordered by rank, and print out the
 ordered list. Hint: sort the list first by rank, and then by suit.
 
 The format of the cards.txt file is;
 
 1 h
 1 d
 13 c
 10 s
 
 and so on for the whole deck.
 
 Can someone help me to get the mycomp function to work.
 
 Any help appreciated
 
 J
 
 def read_cards(filename):
 
 cards = []
 for card in open(filename, 'r'):
 # strip the trailing newline character
 cards.append(card.strip())
 return cards
 
 filename = 'cards.txt'
 cards = read_cards(filename)
 
 
 
 def cards_str2tup(cards):
 
 cards_tup = []
 for card in cards:
 rank, suit = card.split()
 cards_tup.append((suit, int(rank)))
 return cards_tup
 
 def cards_tup2str(cards_tup):
 
 cards = []
 space = ' '
 for tup in cards_tup:
 suit, rank = tup
 s = str(rank) + space + suit
 cards.append(s)
 return cards
 
 def mycmp( a, b):
 #define the order in which the characters are to be sorted
 order = [ 'h', 'd', 'c', 's' ]
 # if the characters from each element ARENT the same
 if a[1]  b[1]:
 #return the result of comparing the index of each elements
 character in the order list
 return cmp( order.index( a[1] ), order.index( b[1] ) )
 #otherwise
 else :
 #return the result of comparing each elements number
 return cmp( a[0], b[0] )
 
 cards.sort( mycmp )
 #print cards

Maybe it's easier to use a key function instead of a compare function.  A
key function receives an element and must return something that is then
sorted and the element ends up where the computed key is in the sorted
list.  Little example for sorting a list of strings first by length and
strings of the same length by alphabetical order:

def key_func(item):
return (len(item), item)

data = ['viking', 'spam', 'parrot', 'ham', 'eric']
data.sort(key=key_func)
print data

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: totally lost newbie

2007-05-27 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Steve Howell
wrote:

 def key_func(item):
 return (len(item), item)
 
 data = ['viking', 'spam', 'parrot', 'ham', 'eric']
 data.sort(key=key_func)
 print data
 
 
 Marc, when did the key feature get introduced, 2.4 or
 2.5?  I'm asking on behalf of the newbie, who's going
 to struggle with your solution if he's still running
 2.3.

It's available in 2.4 but I don't know when it was introduced.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Amount of Data

2007-05-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Jack wrote:

 I have tens of millions (could be more) of document in files. Each of them 
 has other properties in separate files. I need to check if they exist,
 update and merge properties, etc.
 And this is not a one time job. Because of the quantity of the files, I
 think querying and updating a database will take a long time...

But databases are exactly build and optimized to handle large amounts of
data.

 Let's say, I want to do something a search engine needs to do in terms
 of the amount of data to be processed on a server. I doubt any serious
 search engine would use a database for indexing and searching. A hash
 table is what I need, not powerful queries.

You are not forced to use complex queries and an index is much like a hash
table, often even implemented as a hash table.  And a database doesn't
have to be an SQL database.  The `shelve` module or an object DB like zodb
or Durus are databases too.

Maybe you should try it and measure before claiming it's going to be too
slow and spend time to implement something like a database yourself.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Struggling again 'map'

2007-05-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], mosscliffe
wrote:

 for x,y in map(None, lista, listb):  #  Also fine - extends as
 expected
 print MAP:, x, x  y, y
 
 for x,y in map(N/A, lista, listb): ## Fails - Can not call a
 'str'
 print MAP:, x, x  y, y
 
 def fillwith(fillchars):
 return fillchars
 
 for x,y in map(fillwith(N/A), lista, listb): ## Fails also -
 Can not call a 'str'
 print MAP:, x, x  y, y

`map()` expects a function as first argument that will be applied to the
elements in the other the arguments which have to be iterable.  That you
can give `None` as a function and the resulting behavior is IMHO a very
ugly thing and has not much to to with the semantics expected from a
`map()` function.  The `None` is not the default fill value but a
placeholder for the identity function.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?)

2007-05-25 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], sim.sim wrote:

 Below the code that tryes to parse an well-formed xml, but it fails
 with error message:
 not well-formed (invalid token): line 3, column 85

How did you verified that it is well formed?  `xmllint` barf on it too.

 The problem within CDATA-section: it consists a part of utf-8
 encoded string wich was splited (widely used for memory limited
 devices).
 
 When minidom parses the xml-string, it fails becouse it tryes to convert
 into unicode the data within CDATA-section, insted of just to return the
 value of the section as is. The convertion contradicts the
 specification http://www.w3.org/TR/REC-xml/#sec-cdata-sect

An XML document contains unicode characters, so does the CDTATA section.
CDATA is not meant to put arbitrary bytes into a document.  It must
contain valid characters of this type
http://www.w3.org/TR/REC-xml/#NT-Char (linked from the grammar of CDATA in
your link above).

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a file and resuming reading.

2007-05-25 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Karim Ali
wrote:

 Simple question. Is it possible in python to write code of the type:
 
 -
 while not eof  - really want the EOF and not just an empty line!
 readline by line
 end while;
 -

while True:
line = f.readline()
if not line:
break
# Do something with `line`.

 What I am using now is the implicit for loop after a readlines(). I don't 
 like this at all as a matter of opinion (my background is C++).

Both look ugly to Pythonistas too.  Files are iterable:

for line in f:
# Do something with `line`.

 But also, in case for one reason or another the program crashes, I want to 
 be able to rexecute it and for it to resume reading from the same position 
 as it left. If a while loop like the one above can be implemented I can do 
 this simply by counting the lines!

for line_nr, line in enumerate(f):
# Do something with `line_nr` and `line`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Amount of Data

2007-05-25 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Jack wrote:

 I need to process large amount of data. The data structure fits well
 in a dictionary but the amount is large - close to or more than the size
 of physical memory. I wonder what will happen if I try to load the data
 into a dictionary. Will Python use swap memory or will it fail?

What about putting the data into a database?  If the keys are strings the
`shelve` module might be a solution.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: of destructors, open files and garbage collection

2007-05-24 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], massimo s.
wrote:

 I have a for loop that looks like the following :
 
 for item in long_list:
foo(item)
 
 def foo(item):
item.create_blah() #--this creates item.blah; by doing that it
 opens a file and leaves it open until blah.__del__() is called
 
 Now, what I thought is that if I call
 
 del(item)
 
 it will delete item and also all objects created inside item.

It will delete the *name* `item`.  It does nothing to the object that was
bound to that name.  If the name was the only reference to that object, it
may be garbage collected sooner or later.  Read the documentation for the
`__del__()` method for more details and why implementing such a method
increases the chance that the object *won't* be garbage collected!

Relying on the `__del__()` method isn't a good idea because there are no
really hard guaranties by the language if and when it will be called.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use imaageop.scale

2007-05-23 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Bruce wrote:

 Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band
 (24bit per pixel), 100 * 100 size to 50 * 50 size. I
 tried to use scale function in imageop module but failed. Any
 suggestions about this? Thanks!

I guess you are talking about the Python Imaging Library (PIL) here?  What
have you tried and in which way did it fail?

What about the `resize()` method on image objects?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: too much memory use

2007-05-22 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], rohit wrote:

 i am making a program for desktop search.
 in order to make it more effective im implementing the records in the
 form of a tree(files starting with 'a','b','c'have different
 trees ..so 26 trees in all) in memory and writing it down in file.
 the max size file has 16000 records...now to implement the tree in
 list i'm using line no as index ..and empty child nodes are
 represented as \n
 all this work is going on in the memory..
 problem is the system eats up my 512 mb RAM +1gb virtual store n hangs
 cant think of an effective way to implement tree in memory(i can
 compact it on disk by writing just the index no..along with the record
 from which tree in memory can be reconstructed, but i have to
 implement tree as previous to implement random access)

I'm not quite sure what exactly you have as in-memory data structures and
how many records -- are you sure you don't keep references to objects
you don't really need anymore?  Or maybe you have object cycles and
implemented the `__del__()` method on those objects?

Anyway… If the data doesn't fit into memory anymore it's time to put
them into a database.  Either a `shelve`, an SQL database like SQLite or
maybe an object database like zodb or Durus.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: re.compile for names

2007-05-21 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], brad wrote:

 I am developing a list of 3 character strings like this:
 
 and
 bra
 cam
 dom
 emi
 mar
 smi
 ...
 
 The goal of the list is to have enough strings to identify files that 
 may contain the names of people. Missing a name in a file is unacceptable.

Then simply return `True` for any file that contains at least two or three
ASCII letters in a row.  Easily written as a short re.  ;-)

 I may end up with a thousand or so of these 3 character strings. Is that 
 too much for an re.compile to handle? Also, is this a bad way to 
 approach this problem? Any ideas for improvement are welcome!

Unless you can come up with some restrictions to the names, just follow
the advice above or give up.  I saw a documentation about someone with the
name Scary Guy in his ID papers recently.  What about names with letters
not in the ASCII range?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python compared to other language

2007-05-21 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 Python is a strongly typed but dynamic language ...
 
 In the A few questions thread, John Nagle's summary of Python begins
 Python is a byte-code interpreted untyped procedural dynamic
 language with implicit declaration. 
 
 Is Python strongly typed or untyped?

Strongly typed.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: TIFF to PDF

2007-05-20 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], revuesbio
wrote:

 I'm looking for :
 1/ the best method to convert tiff files to PDF.
 2/ and I want to merge these pdf files.

If it doesn't need to be done in pure Python I would use the
command line tools from libtiff: `tiffcp` to copy several tiffs into one
multipage tiff and `tiff2pdf` to convert it into PDF.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regex matching question

2007-05-19 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
bullockbefriending bard wrote:

 first, regex part:
 
 I am new to regexes and have come up with the following expression:
  ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9])
 
 to exactly match strings which look like this:
 
  1,2/3,4/5,6/7,8/9,10/11,12
 
 i.e. 6 comma-delimited pairs of integer numbers separated by the
 backslash character + constraint that numbers must be in range 1-14.
 
 i should add that i am only interested in finding exact matches (doing
 some kind of command line validation).

 […]

 the idea in the above code being that i want to use the regex match as
 a test of whether or not the input string (results) is correctly
 formatted. if the string results is not exactly matched by the regex,
 i want my program to barf an exception and bail out. apart from
 whether or not the regex is good idiom, is my approach suitably
 pythonic?

I would use a simple regular expression to extract candidates and a
Python function to split the candidate and check for the extra
constraints.  Especially the all pairs different constraint is something
I would not even attempt to put in a regex.  For searching candidates this
should be good enough::

  r'(\d+,\d+/){5}\d+,\d+'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie: Joining Lists

2007-05-17 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], mosscliffe
wrote:

 --- CODE --
 import os
 import glob
 
 filenames = []
 patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt') #  Can these patterns
 for glob processing be specified in the glob call *ONE
 for pattern in patterns:
 filenames = filenames + glob.glob(pattern)   # Is there a better
 way for this line in joining lists *TWO

You can `extend()` the list instead of creating new concatenated copies in
each iteration.

 Ps  \\ is because I needed to get the path element for my test and
 windoze does not return a path element  if in current directory

Maybe using `os.path.abspath()` on the file names is a more portable and
robust solution here.

If you don't need all the functionality of `glob.glob()` you can write a
simple function that takes multiple file name patterns:

import fnmatch
import os
import re

def multiglob(patterns):
pattern_re = re.compile('|'.join(map(fnmatch.translate, patterns)))
return [os.path.abspath(path)
for path in os.listdir('.')
if pattern_re.match(path)]

This lacks `glob.glob()`\s special handling of patterns containing
directory names though.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Stefan Behnel wrote:

 René Fleschenberg wrote:
 We all know what the PEP is about (we can read). The point is: If we do
 not *need* non-English/ASCII identifiers, we do not need the PEP. If the
 PEP does not solve an actual *problem* and still introduces some
 potential for *new* problems, it should be rejected. So far, the
 problem seems to just not exist. The burden of proof is on those who
 support the PEP.
 
 The main problem here seems to be proving the need of something to people who
 do not need it themselves. So, if a simple but I need it because a, b, c is
 not enough, what good is any further prove?

Maybe all the (potential) programmers that can't understand english and
would benefit from the ability to use non-ASCII characters in identifiers
could step up and take part in this debate.  In an english speaking
newsgroup…  =:o)

There are potential users of Python who don't know much english or no
english at all.  This includes kids, old people, people from countries
that have letters that are not that easy to transliterate like european
languages, people who just want to learn Python for fun or to customize
their applications like office suites or GIS software with a Python
scripting option.

Some people here seem to think the user base is or should be only from the
computer science domain.  Yes, if you are a programming professional it
may be mandatory to be able to write english identifiers, comments and
documentation, but there are not just programming professionals out there.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Execute commands from file

2007-05-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], tmp123 wrote:

 We have very big files with python commands (more or less, 50
 commands each file).
 
 It is possible to execute them command by command, like if the
 commands was typed one after the other in a interactive session?

Take a look at the `code` module in the standard library:

In [31]: code?
Type:   module
Base Class: type 'module'
String Form:module 'code' from '/usr/lib/python2.4/code.pyc'
Namespace:  Interactive
File:   /usr/lib/python2.4/code.py
Docstring:
Utilities needed to emulate Python's interactive interpreter.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Stefan Behnel wrote:

 René Fleschenberg wrote:
 Marc 'BlackJack' Rintsch schrieb:
 There are potential users of Python who don't know much english or no
 english at all.  This includes kids, old people, people from countries
 that have letters that are not that easy to transliterate like european
 languages, people who just want to learn Python for fun or to customize
 their applications like office suites or GIS software with a Python
 scripting option.
 
 Make it an interpreter option that can be turned on for those cases.
 
 No. Make ASCII-only an interpreter option that can be turned on for the
 cases where it is really required.

Make no interpreter options and use `pylint` and `pychecker` for checking
if the sources follow your style guide in respect to identifiers.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: cPickle.dumps differs from Pickle.dumps; looks like a bug.

2007-05-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Daniel Nogradi
wrote:

 The OP was not comparing identity but equality. So it looks like a
 real bug, I think the following should be True for any function f:
 
 if a == b: f(a) == f(b)
 
 or not?

In [74]: def f(x):
   : return x / 2
   :

In [75]: a = 5

In [76]: b = 5.0

In [77]: a == b
Out[77]: True

In [78]: f(a) == f(b)
Out[78]: False

And `f()` doesn't even use something like `random()` or `time()` here.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to choose between python and java

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Anthony Irwin wrote:

 #1 Does python have something like javas .jar packages. A jar file 
 contains all the program files and you can execute the program with 
 java -jar program.jar

There are .egg files but usually distributing a program consisting of
several files isn't a big problem.  There is a mechanism to write a
`setup.py` that copies the files into the correct locations.  Look for
`distutils` in the library docs.

 #2 What database do people recommend for using with python that is 
 easy to distribute across linux, mac, windows.

From Python 2.5 the standard library contains SQLite support.  There are
third party libraries to many DBMSs like MySQL, PostgreSQL, Oracle etc.

The situation with MySQL bindings under Windows was a bit troublesome
recently.  The author of the bindings doesn't use Windows and does not
provide pre-built binaries.

 #4 If I write a program a test it with python-wxgtk2.6 under linux are 
 the program windows likely to look right under windows and mac?

Likely yes, but you better check.  Same applies to Java GUIs.

 #5 someone said that they used to use python but stopped because the 
 language changed or made stuff depreciated (I can fully remember 
 which) and old code stopped working. Is code written today likely to 
 still work in 5+ years or do they depreciate stuff and you have to update?

That sounds odd because the language and standard library is very
backwards compatible.  There are some things deprecated with a comment in
the docs and in some cases runtime warnings, but the code still works.

With Python 3.0 some things will break, because there's some cruft in the
language and library that accumulated over time, just because backwards
compatibility was such a high priority.  The 2.x series will be supported
for some time parallel to 3.x, so there is enough time to migrate.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], René
Fleschenberg wrote:

 Stefan Behnel schrieb:
 :) This is not about technical English, this is about domain specific
 English. How big is your knowledge about, say, biological terms or banking
 terms in English? Would you say you're capable of modelling an application
 from the domain of biology, well specified in a large German document, in
 perfect English terms?
 
 As I have said, I don't need to be able to do that (model the
 application in perfect English terms). It is better to model it in
 non-perfect English terms than to model it in perfect German terms. Yes,
 I do sometimes use a dictionary to look up the correct English term for
 a domain-specific German word when programming. It is rarely necessary,
 but when it is, I usually prefer to take that effort over writing a
 mixture of German and English.

What about words that can't really be translated because they are not only
domain specific but some code within the organization the project is
written for?  Wouldn't it be much easier for maintenance if the
specification, the code, and the users of the program use the same terms
for the same things or concepts instead of mixing this with some
artificial translations?

Maybe you don't need this. The field of programming is very broad and many
domains can be translated and make sense in an international context, but
e.g. software that should map the workflow of a local company with local
laws and regulations and internal names for things and concepts looks
strange in both, pure english and mixed local language and english.  But
the latter is easier to map to the specifications and language of the end
users.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], René Fleschenberg wrote:

 Stefan Behnel schrieb:
 2) The with-statement does have proven substantial benefits, IMO.
 
 Not to me. I don't use it, so no-one should. 
 
 Now you are starting to troll?

I thought he starts to argument like you.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Storing and searching nodes of a tree

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 I use these names as keys in a dictionary, and store node's data.
 Now given a name like abc, I want to find the key with the following
 rule:
 If the key exists return the value
 If the key does not exist, return the value of the leaf node whose
 name is in the given name. For, abc, it is ab . For, ad, it is
 a.
 
 I suppose there must be a simpler solution to this problem. I
 implemented it like this:
 d = {'a':0, 'aa':12, 'ab':43, 'aaa':22, 'aab':343, 'ac':33}
 name = 'abc'
 key = max( [ x for x in d.iterkeys() if x in name] )
 value =  d[key]
 
 I can change the data structure from dictinory to tuple of key,value
 pairs or any thing, and afford to keep them in a particular order. Is
 there any way I can speed up this as I have to do this for around 4000
 times with tree size being ~5000.

What about this:

def search(tree, path):
while path:
result = tree.get(path)
if result is not None:
return result
path = path[:-1]
raise KeyError('path not on tree')

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing and searching nodes of a tree

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 If I have the tree in the dictionary, the code would like this,
 def search(tree, path):
while path and not(tree.haskey(path)):
  path = path[:-1]
if path:
  return tree[path]
else:
  raise KeyError('path not on tree')
 
 Another qn -- dict.haskey() takes logn time, am I right?

No it's O(1).  Dictionaries are implemented as hash tables.  You may write
the condition as:

while path and path not in tree:

That's a little easier to read and a bit faster too as a method lookup is
spared.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Ross Ridge wrote:

 [EMAIL PROTECTED] wrote:
So, please provide feedback, e.g. perhaps by answering these
questions:
- should non-ASCII identifiers be supported? why?
  
 Ross Ridge wrote:
 I think the biggest argument against this PEP is how little similar
 features are used in other languages
 
 Carsten Haese  [EMAIL PROTECTED] wrote:
That observation is biased by your limited sample.
 
 No.  I've actually looked hard to find examples of source code that use
 non-ASCII identifiers.  While it's easy to find code where comments use
 non-ASCII characters, I was never able to find a non-made up example
 that used them in identifiers.

I think you have to search examples of ASCII sources with transliterated
identifiers too, because the authors may have skipped the transliteration
if they could have written the non-ASCII characters in the first place.

And then I dare to guess that much of that code is not open source.  One
example are macros in office programs like spreadsheets.  Often those are
written by semi professional programmers or even end users with
transliterated identifiers.  If the OpenOffice API wouldn't be so
javaesque this would be a good use case for code with non-ASCII
identifiers.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing part of string

2007-05-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], saif.shakeel
wrote:

 Hi,
 I am parsing an xml file ,and one part of structure looks
 something like this:
 
 - COMPARAM id=_338 DDORef=_18 Semantics=timing
 PhysicalLink=Infotainment_Control_Bus_CAN
   SHORTNAMEInfotainment_Control_Bus_CAN_TIMEOUT_AX/SHORTNAME
   LONGNAMETimeout N_As/N_Ar/LONGNAME
   DESCRIPTIONTime from transmit request until a CAN frame transmit
 confirmation is received./DESCRIPTION
   /COMPARAM
 
   In my code i am extracting the data within
 LONGNAME,which is Timeout N_As/N_Ar.These tags repeat and will have
 different timer names..like
 
 - COMPARAM id=_339 DDORef=_18 Semantics=timing
 PhysicalLink=Infotainment_Control_Bus_CAN
   SHORTNAMEInfotainment_Control_Bus_CAN_TIMEOUT_BS/SHORTNAME
   LONGNAMETimeout N_Bs/LONGNAME
   DESCRIPTIONTime that the transmitter of a multi-frame message
 shall wait to receive a flow control (FC) frame before timing out with
 a network layer error./DESCRIPTION
   /COMPARAM
 
  I need to remove the words Timeout from the data,and
 take only the abbrevation..i.e.N_As/N_bs like that .In short i have to
 remove the words which come with name Time,and also the space which
 comes next to it.
 and take only the abbreviation.Can someone help me in this.

You can test for the prefix with the `startswith()` method and use string
slicing to create a new string without the prefix:

In [3]: prefix = 'Timeout '

In [4]: longname = 'Timeout N_Bs'

In [5]: longname.startswith(prefix)
Out[5]: True

In [6]: longname = longname[len(prefix):]

In [7]: longname
Out[7]: 'N_Bs'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Paul Rubin wrote:

 Alexander Schmolck [EMAIL PROTECTED] writes:
 Plenty of programming languages already support unicode identifiers, 
 
 Could you name a few?  Thanks.

Haskell.  AFAIK the Haskell Report says so but the compilers don't
supported it last time I tried.  :-)

Ciao,
Marc 'BlackJack' Rintsch

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Nick Craig-Wood
wrote:

 My initial reaction is that it would be cool to use all those great
 symbols.  A variable called OHM etc!

This is a nice candidate for homoglyph confusion.  There's the Greek
letter omega (U+03A9) Ω and the SI unit symbol (U+2126) Ω, and I think
some omegas in the mathematical symbols area too.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Michel Claveau
wrote:

 And  Il1 O0 ?

Hm, we should ban digits from identifier names.  :-)

Ciao,
Marc 'BlackJack' Rintsch

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-13 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Michael Torrie
wrote:

 I think non-ASCII characters makes the problem far far worse.  While I
 may not understand what the function is by it's name in your example,
 allowing non-ASCII characters makes it works by forcing all would-be
 code readers have to have all kinds of necessary fonts just to view the
 source code.  Things like reporting exceptions too.  At least in your
 example I know the exception occurred in zieheDreiAbVon.  But if that
 identifier is some UTF-8 string, how do I go about finding it in my text
 editor, or even reporting the message to the developers?  I don't happen
 to have that particular keymap installed in my linux system, so I can't
 even type the letters!

You find it in the sources by the line number from the traceback and the
letters can be copy'n'pasted if you don't know how to input them with your
keymap or keyboard layout.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finally started on python..

2007-05-12 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Roger Gammans
wrote:

 I found myself using this sort of code a bit in one of my recent
 scripts
  class Something:
   def Entries(self):
sort=self._data.keys()
  sort.sort()
  for i in sort:
 yield i
 
 IS this preferable to just returning the sort array from the function
 or not? Which is more runtime efficent.

I see no benefit for a generator here as the whole list mus be build for
sorting anyway.  If you still want return an iterable here it could be
written this way:

class Something(object):
def iter_entries(self):
return iter(sorted(self._data.keys()))

Just leave out the `iter()` call to return a sorted list.

If you want to make `Something` objects iterable over the sorted keys,
change the method name to `__iter__()`.  Then you can use `Something`
objects like this:

something = Something()
# Puts some entries into `something`.
for entry in something:
print entry

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to refer to partial list, slice is too slow?

2007-05-11 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
人言落日是天涯,望极天涯不见家 wrote:

 I make a sample here for the more clearly explanation
 
 s =  . - this is a large string data - ...
 
 def parser1(data)
  # do some parser
  ...
  # pass the remainder to next parser
  parser2(data[100:])
 
 def parser2(data)
  # do some parser
  ...
  # pass the remainder to next parser
  parser3(data[100:])
 
 def parser3(data)
  # do some parser
  ...
  # pass the remainder to next parser
  parser4(data[100:])
 
 ...

Do you need the remainder within the parser functions?  If not you could
split the data into chunks of 100 bytes and pass an iterator from function
to function.  Untested:

def iter_chunks(data, chunksize):
offset = chunksize
while True:
result = data[offset:offset + chunksize]
if not result:
break
yield result


def parser1(data):
chunk = data.next()
# ...
parser2(data)


def parser2(data):
chunk = data.next()
# ...
parser3(data)

# ...

def main():
# Read or create data.
# ...
parser1(iter_chunks(data, 100))

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: replacing string in xml file--revisited

2007-05-10 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], saif.shakeel
wrote:

  Although this works alone it is nto
 working when i handle multiple file I/O.Is there a alternative to do
 this.(maybe without read() operation)

Why do you want to change the part that *works* instead of fixing the code
that doesn't!?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minor bug in tempfile module (possibly __doc__ error)

2007-05-10 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], James T. Dennis wrote:

 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 In [EMAIL PROTECTED], James T. Dennis wrote:
 
 You can change it by simply assigning to the name:
 
 In [15]: tempfile.template = 'spam'
 
 In [16]: tempfile.template
 Out[16]: 'spam'
 
   I know you can change it.  But changing it in your namespace
   doesn't change the results returned by the functions called
   from the module.

I'm not changing it in my namespace but in the namespace of the `tempfile`
module.

   I don't quite understand how this name/variable in
   my namespace (__main__) is able to change the value
   while the functions in the module still hold the old
   value.

Default arguments are evaluated *once* when the ``def`` is executed and
not at every function call.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble with generators

2007-05-10 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Hans-Peter Jansen wrote:

 class Gen(object):
 def records(self, cls):
 for i in range(3):
 setattr(cls, id, %s%s % (cls.__doc__,  i))
 yield cls

 […]

 class GenA(Gen):
 def __init__(self):
 self.genB = GenB()
 
 def records(self):
 for a in Gen.records(self, A()):

Here you create an instance of `A` and pass that *instance* and not the
*class*.  If  you would pass the class here, you must create objects in
`Gen.records()`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Minor bug in tempfile module (possibly __doc__ error)

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], James T. Dennis wrote:

  Tonight I discovered something odd in the __doc__ for tempfile
  as shipped with Python 2.4.4 and 2.5: it says:
 
   This module also provides some data items to the user:
 
 TMP_MAX  - maximum number of names that will be tried before
giving up.
 template - the default prefix for all temporary names.
You may change this to control the default prefix.
 
  ... which would lead one to think that the following code would work:
 
import tempfile
tempfile.template = 'mytest'
tf = tempfile.NamedTemporaryFile()
  tf.name
   '/tmp/mytest-XX'
 
  It doesn't.

The source says:

__all__ = [
NamedTemporaryFile, TemporaryFile, # high level safe interfaces
mkstemp, mkdtemp,  # low level safe interfaces
mktemp,  # deprecated unsafe interface
TMP_MAX, gettempprefix,# constants
tempdir, gettempdir
   ]

Maybe the doc should be clearer in saying constants too.

  Secondly, the author(s) of the tempfile module apparently didn't
  understand this either.  And no one else even noticed that the __doc__
  is wrong (or at least misleading -- since the only way I can see to
  change tempfile.template is to edit the .py file!

You can change it by simply assigning to the name:

In [15]: tempfile.template = 'spam'

In [16]: tempfile.template
Out[16]: 'spam'

If you want to change the outcome of the functions and objects then simply
give the prefix as argument.

In [21]: tempfile.mktemp(prefix='eggs')
Out[21]: '/tmp/eggsBqiqZD'

In [22]: a = tempfile.NamedTemporaryFile(prefix='eric')

In [23]: a.name
Out[23]: '/tmp/ericHcns14'

  ... why can't I change that value in that other namespace?  Is it
  a closure?  (Or like a closure?)  Where is this particular aspect
  of the import/namespace semantics documented?

You *can* change it, but it is not used by the code in that module.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error in the if, elif, else statement ?

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
juan-manuel.behrendt wrote:

 Hello together,
 
 I wrote a script for the engineering software abaqus/CAE. It worked
 well until I implemented a selection in order to variate the variable
 lGwU through an if elif, else statement. I am going to post the
 first 82 lines of the script, since the error message points at line
 80:
 
 from abaqusConstants import *
 from abaqus import *
 
 def CreateSchraube(name, l, flag=None, flag2=None):
 import part
 vp = session.currentViewportName
 model = session.sessionState[vp]['modelName']
 m = mdb.models[model]
 s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
 s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0))
 
 if flag==1:
 
   dh = 15.0
   z = 15.0
   dz = 60.0
   d = 72.0
   f = 1.0
   dD = f*62.0
   lGwO = 110.0
 
   if flag2==11:   # here appears the
 beginning of the new impletation in order to variate lGwU
  lGwU = 0.8*d  # you can see these inner
 if, elif, else statement 4 times, because
   elif flag2==12:# the outer if, elif,
 else statement (which works!) has 4 cases
  lGwU = 1.0*d
   elif flag==13:
  lGwU = 1.2*d
   else: pass
 
 elif flag==2:
 
   dh = 15.0
   z = 15.0
   dz = 60.0
   d = 72.0
   f = 1.0
   dD = f*62.0
   lGwO = 110.0
 
   if flag2==11:
  lGwU = 0.8*d
   elif flag2==12:
  lGwU = 1.0*d
   elif flag==13:
  lGwU = 1.2*d
   else: pass
 
 elif flag==3:
 
   dh = 25.0
   z = 15.0
   dz = 68.0
   d = 80.0
   f = 1.0
   dD = f*71.5
   lGwO = 120.0
 
   if flag2==11:
 lGwU = 0.8*d
   elif flag2==12:
 lGwU = 1.0*d
   elif flag==13:
 lGwU = 1.2*d
   else: pass
 
 elif flag==4:
 
  dh = 25.0
   z = 15.0
   dz = 68.0
   d = 80.0
   f = 1.0
   dD = f*71.5
   lGwO = 120.0
 
   if flag2==11:
 lGwU = 0.8*d
   elif flag2==12:
 lGwU = 1.0*d
   elif flag==13:
 lGwU = 1.2*d
   else: pass
 
 else: pass
 
 xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0),#
 this is line 80, where the error message points at
(d/2, lGwU), (dD/2, (d-dD)/
 (2*tan(radians(12)))+lGwU),
(dD/2, l-lGwO-z-(d-dD)/
 (2*tan(radians(20, (d/2, l-lGwO-z), (d/2, l-z), (dh/2, l-z), (dh/
 2, -z))
 
 So, a lot of code, I hope somebody will read it.
 My Problem ist the error message, which says:
 
  #* UnboundLocalError: local variable 'lGwU' referenced before
 assignment
   #*File C:\ABAQUS_Products\6.6-3\abaqus_plugins\Schraube.py, line
 80, in
   #*CreateSchraube
   #* xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), 
 
 So the error message is quite clear, however it is not suitable to
 what I've written in my script, because the local variable 'lGwU' IS
 assigned before referenced and, furthermore in line 80 lGwU does not
 appear.

It is not assigned, otherwise you would not get this error.  The line
number is also correct because it's the start of the construct or logical
line where the name is referenced.  Just look at the very next line in
the source.

 Another strange thing is, that the first two cases, where lGwU = 0.8*d
 and lGwU = 1.0*d is, do work in my abaqus script.
 So the error message only occurs if I choose lGwU = 1.2*d.

Take a look at the condition for that case(s).  You are testing `flag`
instead of `flag2`.  Maybe you should have written ``raise SomeError`` or
``assert False`` instead of all those useless ``else: pass``.  If this
branch is taken, obviously `lGwU` is not bound.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Getting some element from sets.Set

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 Since any element of the set serves as a name (and you know the sets are
 all non- empty), it'd be very nice to have a .element() method, or some
 such. I guess iter(s).next() works okay, but it's not very readable,
 and I wonder if it's efficient.

Give it a name and it gets more readable:

def get_name(setobj):
return iter(setobj).next()

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Designing a graph study program

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], andrea wrote:

 But I have some design doubts, I'd like to keep the algorithm (for
 example bfs) as clean as possible, being independent from the drawing
 methods.
 And how could I make it step through algorithms without having a more
 complicated code? Maybe using threads?

Create an API that informs some observer about actions like visiting a
node, traversing or adding an egde and so on.  This way you can register
callbacks that translate between the graph and the GUI.

If you don't want to change the algorithm or graph and node classes this
notification can be injected by wrapper classes to some degree.

For very fine grained observation of an algorithm you might try to
implement a step by step debugger.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ipython environment question

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Shane Geiger
wrote:

 Run the script and then try to change the variable project_name from the 
 ipython prompt and then type create()
 and the new value you assigned will *not* be used.  I tried to use def 
 create(project_name = project_name):  Even that didn't work.
 
 What slight of hand is necessary?
 
 import os, sys
 
 project_name = 'python_packages'
 group_name = 'sgeiger'
 repo = '/var/svn'
 
 def create(repo=repo,group_name=group_name,project_name=project_name):
 #def create():
#os.system(sudo mkdir -p  + repo )
#os.system(sudo svnadmin create  + repo)
#os.system(sudo chown -R  + group_name +   + repo)
print sudo mkdir -p  + repo + '/' + project_name
print sudo svnadmin create  + repo + '/' + project_name
print sudo chown -R  + group_name +   + repo + '/' + project_name
 
 if __name__ == '__main__':
sys.argv.append('-cl')
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
print Please set these variables:  project_name, group_name   ...and 
 then type create()
### I even tried to put all my
ipshell() # this call anywhere in your program will start IPython

You have to call the function with arguments.  The default values are only
evaluated once when the ``def`` statement is executed, not every time the
function is called.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Atttribute error

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], HMS Surprise
wrote:

 The snippet below causes an attribute error.
 
 AttributeError: module 'urllib' has no attribute 'urlopen'
 
 I am using python 2.2.3. According to the documentation at C:
 \Python22\Doc\lib urllib has a function called urlopen.

Do you have a file called `urllib.py` in the current directory?  Then this
gets imported instead of the module in the standard library.

Add this directly after the ``import`` to see what's happening:

print urllib.__file__
print dir(urllib)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Towards faster Python implementations - theory

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Paul Boddie
wrote:

 On the typing front, the neatest way to express typing is via
 initialization.  With the Shed Skin restrictions, if all variables are
 initialized before use (preferably in __init__), there's no need to
 maintain an undefined flag for a variable.  And, of course, if
 the type of a varaible is simple and can't change, it doesn't have to
 be boxed, (enclosed in an object) which is a big win.

A variable? :-)

Maybe that last sentence should start with: And, of course, if the type of
objects bound to a name won't change…

 I'm fairly sure, although my intuition unfortunately doesn't provide a
 ready example right now, that typing via initialisation, whilst an
 important tool, may either impose unacceptable restrictions if
 enforced too rigidly or limit the precision that one might desire in
 determining type information in the resulting system.

I often bind a name to `None` first if it is going to be bound to it's
real value later on.  So this initialization doesn't say anything about
the type(s) that will be bound to it later.

I don't see how this type inference for static types will work unless some
of the dynamism of the language will get restricted.  But is this really
necessary?  Isn't a JIT compiler and maybe type hinting good enough?  By
type hinting I really mean just recommendations from the programmer.  So
you can say this name should be an `int` and the JIT compiler produces
code in advance, but it's okay to pass another object instead.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: File Name Format

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Grant Edwards wrote:

 On 2007-05-08, Anand [EMAIL PROTECTED] wrote:
 
 How do I convert programmatically the file names from WIN32 to UNIX format?
 
 You don't need to.  AFAIK, all legal WIN32 filenames are legal
 UNIX file names.

Doesn't this depend more on the file system than the operating system?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestions for how to approach this problem?

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], John Salerno wrote:

 I have a large list of publication citations that are numbered. The 
 numbers are simply typed in with the rest of the text. What I want to do 
 is remove the numbers and then put bullets instead. Now, this alone 
 would be easy enough, with a little Python and a little work by hand, 
 but the real issue is that because of the way these citations were 
 typed, there are often line breaks at the end of each line -- in other 
 words, the person didn't just let the line flow to the next line, they 
 manually pressed Enter. So inserting bullets at this point would put a 
 bullet at each line break.
 
 So I need to remove the line breaks too, but of course not *all* of them 
 because each reference still needs a line break between it. So I'm 
 hoping I could get an idea or two for approaching this. I figure regular 
 expressions will be needed, and maybe it would be good to remove the 
 line breaks first and *not* remove a line break that comes before the 
 numbers (because that would be the proper place for one), and then 
 finally remove the numbers.

I think I have vague idea how the input looks like, but it would be
helpful if you show some example input and wanted output.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Designing a graph study program

2007-05-08 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], andrea wrote:

 Interesting but what do you mean for two graph-implementatio that
 share the same interface??
 I don't have abstract classes or interfaces in python, am I wrong?

You are thinking of some kind of types or enforcements.  If two classes
have some methods with the same names and the same semantics they share
the same interface.  And a class that isn't meant to be instantiated or
doesn't implement all methods is an abstract class.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: N00b question on Py modules

2007-05-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], lokesh.jagasia
wrote:

 My python module:
 
 _exitcode = 0
 
 def setExitCode():
 _exitcode = 1
 
 if __name__ == '__main__':
 print _exitcode
 setExitCode()
 print _exitcode
 
 Actual O/P:
 0
 0
 
 I expected to see an output of 0 followed by 1. But it turns out that
 the _exitcode variable is not changed at all. It seems that
 setExitCode() might be editing a local copy of the _exitcode variable.
 But then, how do I tell it to change the value of the module variable
 and not its local variable.

Any name that gets bound to an object within a function is local to that
function unless you declare it as ``global``.  But using lots of global
variables is considered bad style so you may think about rewriting
functions with ``global`` names to return the value(s) instead:

_exitcode = 0

def set_exitcode():
return 1

if __name__ == '__main__':
print _exitcode
_exitcode = set_exitcode()
print _exitcode

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Examples / Links needed

2007-05-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Andy wrote:

 Gurus, I'm looking for definite examples (pardon me if I'm not clear
 here) on Stack class...Somewhat like this :
 
 class Stack(object):
   def __init__(self__)
   self.__contents = []

I don't know what to tell you here without writing the thing for you.  Ask
yourself what operations a `Stack` needs and look at the documentation for
`list` operations.  It's pretty easy to map the stack operations to `list`
ones.

 and ad hoc implementation of a class based on number system like for
 example somewhat like this
 
 
 def __imult__(self, other):
self.__numerator   *= other.__numerator
self.__denominator *= other.__denominator
.
.
   return self

So what exactly is your problem?  Take a number like, look at the
methods it implements and do this for your number like class.

 I'm not satisfied with Python Docs.

Why?  What does `Emulating numeric types`_ in the reference manual lack in
your opinion?

.. _Emulating numeric types: http://docs.python.org/ref/numeric-types.html

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: long lists

2007-05-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Merrigan wrote:

 The Script it available at this url : 
 http://www.lewendewoord.co.za/theScript.py
 
 P.S. I know it looks like crap, but I'm a n00b, and not yet through
 the OOP part of the tutorial.

One spot of really horrible runtime is the `comp_are()` function, it has
quadratic runtime. Why the funny spelling BTW?

Why are you binding the objects to new names all the time and calling
`str()` repeatedly on string objects?  The names `a`, `b` and `fn2up` are
unnecessary, you can use `file1`, `file2` and `filename` instead.  And
``str(str(b))`` on a string object is a no-operation.  It's the same as
simply writing ``b``.

Those two nested ``for``-loops can be replaced by converting both lists
into `set()` objects, calculating the difference and convert back to a
sorted list:

def compare(remote, local):
return sorted(set(local) - set(remote))

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is for reliable?

2007-05-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], [EMAIL PROTECTED]
wrote:

 Hi to all I have a question about the for statement of python. I have the
 following piece of code where cachefilesSet is a set that contains the
 names of 1398 html files cached on my hard disk
 
 [snipped code]
 
 this code stops at the 473th file instead of reaching 1398
 
 however I changed the for and substituted it with a while in this way
 
 while cachefilesSet:
 fn = cachefilesSet.pop()
 ...
 ...
 
 the while loop reaches the 1398th file and is some 3-4 times faster than
 the for loop
 
 How is this possible?

Good question.  ``for`` loops are of course reliable.  Can you give a
short self contained example that shows the behavior?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie prob: How to write a file with 3 threads?

2007-05-06 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], est wrote:

 I need to write a file using 3 threads simutaniously, e.g. Thread 1
 write the first byte of test.bin with an a, second thread write the
 second byte b, third thread write the third byte c. Anyone could
 give a little example on how to do that?

Simplest solution is: don't do that.  Write from one thread and send the
date from the other threads via a `Queue.Queue` to the writing thread. 
Send the number of the thread with the data so the writer thread knows in
which order the data has to be written.

 I have my code, but it makes python intepreter crash everytime on my
 Vista.

Show minimal (non-)working  code, tell us the exception plus traceback and
explain crash.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping over lists

2007-05-05 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], prad wrote:

 On Friday 04 May 2007 18:40:53 Tommy Grav wrote:
 Can anyone help me with the right approach for this
 in python?
 
 for each in a:
 for item in a[a.index(each)+1:]:
 print each,item
 
 will produce 
 
 1 2
 1 3
 1 4
 1 5
 2 3
 2 4
 2 5
 3 4
 3 5
 4 5

But only if the elements in the list are unique.  And the runtime is
suboptimal because `index()` is doing a linear search -- the outer loop
becomes slower and slower with each iteration.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Wiseman wrote:

 Note: I know there are LALR parser generators/parsers for Python, but
 the very reason why re exists is to provide a much simpler, more
 productive way to parse or validate simple languages and process text.
 (The pyparse/yappy/yapps/insert your favourite Python parser
 generator here argument could have been used to skip regular
 expression support in the language, or to deprecate re. Would you want
 that? And following the same rule, why would we have Python when
 there's C?)

I don't follow your reasoning here.  `re` is useful for matching tokens
for a higher level parser and C is useful for writing parts that need
hardware access or raw speed where pure Python is too slow.

Regular expressions can become very unreadable compared to Python source
code or EBNF grammars but modeling the tokens in EBNF or Python objects
isn't as compact and readable as simple regular expressions.  So both `re`
and higher level parsers are useful together and don't supersede each
other.

The same holds for C and Python.  IMHO.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get type methods?

2007-05-04 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Thomas Nelson
wrote:

 On May 4, 7:59 am, [EMAIL PROTECTED] wrote:
 Let me retype my question: what I 'dir()' in case of 'pyuno' type
 instance?
 Or in case of 'dict' type instance? Or in case of any other new python
 type?
 
 class Foo:
 ... def f(self,x):
 ... print x+1
 ... def g(self,x):
 ... print x-1
 ...
 dir(Foo)
 ['__doc__', '__module__', 'f', 'g']
 
 Is this not what you want?  These are the only methods in the Foo
 class.

The OPs problem is, there is no access to the class or type because
there is no name.  You can get just instances from a factory function. 

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: copy base class fields

2007-05-03 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], tmp123 wrote:

 The following small program gives an error:
 
 #!/usr/bin/python
 #
 
 class A:
   def __init__(self):
 self.v1=1
 
   def __repr__(self):
  return v1=%d\n % self.v1
 
 class B(A):
   def __init__(self,a):
 self=a
 self.v2=2
 
   def __repr__(self):
  return A.__repr__(self) + (v2=%d\n % self.v2)
 
 x=A()
 print x
 
 y=B(x)
 print y
 
 
 
 $ ./prueba.pl
 v1=1
 
 Traceback (most recent call last):
   File ./prueba.pl, line 23, in module
 print y
   File ./prueba.pl, line 17, in __repr__
 return A.__repr__(self) + (v2=%d\n % self.v2)
   File ./prueba.pl, line 9, in __repr__
 return v1=%d\n % self.v1
 AttributeError: B instance has no attribute 'v1'
 
 
 It seems that the statement self=a is not the correct way to copy
 all the fields of the base class from the __init__ argument to the new
 object.

This binds the local name `self` to the same object that is bound to `a`. 
Now you have lost the reference to the instance, so the next line sets the
attribute `v2` on the object passed to the constructor of the `B` object.

 Of course, it is not an option to copy one by one all the fields of
 class A inside the __init__ of B.
 
 Several variants of the program produces similar results.
 
 Please, could someone explain which way is the correct way?

Call the `__init__()` of `A`:

class B(A):
def __init__(self, a):
A.__init__(self)
self.v2 = 2

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ascii to unicode line endings

2007-05-03 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], fidtz wrote:

 import codecs
 testASCII = file(c:\\temp\\test1.txt,'w')
 testASCII.write(\n)
 testASCII.close()
 testASCII = file(c:\\temp\\test1.txt,'r')
 testASCII.read()
 '\n'
 Bit pattern on disk : \0x0D\0x0A
 testASCII.seek(0)
 testUNI = codecs.open(c:\\temp\\test2.txt,'w','utf16')
 testUNI.write(testASCII.read())
 testUNI.close()
 testUNI = file(c:\\temp\\test2.txt,'r')
 testUNI.read()
 '\xff\xfe\n\x00'
 Bit pattern on disk:\0xff\0xfe\0x0a\0x00
 Bit pattern I was expecting:\0xff\0xfe\0x0d\0x00\0x0a\0x00
 testUNI.close()

Files opened with `codecs.open()` are always opened in binary mode.  So if
you want '\n' to be translated into a platform specific character sequence
you have to do it yourself.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace the last (and only last) character in a string?

2007-05-03 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Johny wrote:

 Let's suppose
 s='12345 4343 454'
 How can I replace the last '4' character?
 I tried
 string.replace(s,s[len(s)-1],'r')
 where 'r' should replace  the last '4'.
 But it doesn't work.
 Can anyone explain why?

Because you can't change strings.  Any function or method that changes a
string returns a new and modified copy.  So does the `string.replace()`
function.  And you don't bind the result to a name, so it is lost.

This is shorter than using `replace()`:

In [9]: s = '12345 4343 454'

In [10]: s = s[:-1] + 'r'

In [11]: s
Out[11]: '12345 4343 45r'

BTW most things in the `string` module are deprecate because they are
available as methods on string objects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: _csv.Error: string with NUL bytes

2007-05-03 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], fscked wrote:

 The traceback is as follows:
 
 Traceback (most recent call last):
   File createXMLPackage.py, line 35, in ?
 for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name,
 address, phone, country, city, in csvreader:
 _csv.Error: string with NUL bytes
 Exit code: 1 , 0001h

As Larry said, this most likely means there are null bytes in the CSV file.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Exe from Python

2007-05-02 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], M Abbas wrote:

 This is what i am required to do.
 Call an executable from my python script, and when the executable is
 fininshed running, i should continue with my python script.
 
 I have tried os.exec() but it calls the executable and never returns
 to the calling python script.
 I tried os.fork it will start an independent process,
 since logic of my program depends on the results of executable.

Take a look at `os.system()` or the `subprocess` module.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I need help speeding up an app that reads football scores and generates rankings

2007-05-02 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], jocknerd wrote:

 The biggest difference in my two apps is the C app uses linked lists.
 I feel my Python app is doing too many lookups  which is causing the
 bottleneck.

Then replace those linear searches you wrote in Python with a dictionary.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time functions

2007-05-02 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], HMS Surprise
wrote:

 I wish to generate a datetime string that has the following format.
 '05/02/2007 12:46'. The leading zeros are required.
 
 I found '14.2 time' in the library reference and have pulled in
 localtime. Are there any formatting functions available or do I need
 to make my own? Perhaps there is something similar to C's printf
 formatting.

You mean like `time.strftime()`!?  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I/O Operations .....

2007-04-30 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], saif.shakeel
wrote:

 File writing can be done in that way,but my query is
 something different.I have to rename the output file by default with
 input file name(only changing the extension.

Take a look at the functions in `os.path`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regexp match string with word1 and not word2

2007-04-30 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Flyzone wrote:

 for y in range(0, len(skip_lst) ):
  if (re.search(skip_lst[y], line)):
   skip=1
break

Please try to avoid unnecessary indexes::

for regexp in skip_list:
if re.search(regexp, line):
skip = True
break

And if you don't intent to count the `skip`\s a `True` seems to be more
readable.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I can't inherit from compiled classes ?

2007-04-29 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Maxim Veksler
wrote:

 Hello list,
 
 I'm trying to subclass socket and select, for both I get:
  TypeError: Error when calling the metaclass bases
 module.__init__() takes at most 2 arguments (3 given) , I don't
 understand this error. Why would python try to pass 3 arguments (what
 are they) ?
 
 Googling for this error gave random results talking about try to
 inherit a Package but socket is definitely a class,
 (/usr/lib/python2.4/socket.py). Not sure about select thought.
 
 I've did the following to receive the error:
 
 In [1]: import socket
 
 In [2]: class PollingSocket(socket):
...: pass
...:
 ---
 exceptions.TypeError Traceback (most
 recent call last)
 
 /home/hq4ever/ipython console
 
 TypeError: Error when calling the metaclass bases
 module.__init__() takes at most 2 arguments (3 given)
 
 
 
 What am I breaking wrong?

You are trying to subclass a module here, just like the error message
says.  The module contains a `socket` type:

In [3]: import socket

In [4]: type(socket)
Out[4]: type 'module'

In [5]: type(socket.socket)
Out[5]: type 'type'

`select.select()` is a function:

In [6]: import select

In [7]: type(select.select)
Out[7]: type 'builtin_function_or_method'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Ping program

2007-04-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Linus Cohen
wrote:

 I'm a newbie to python and programming in general, so I wanted a
 simple project to start off. What I'm trying to do here is write a
 python command-line ping program, much like the Unix and Windows ping
 programs. I've got this much worked out already:
 
 class ping
 def PING(IP, pings, size):

Why is it a class?  I would have expected a `ping()` function.

And you might have a look at `PEP 8 -- Style Guide for Python Code`_ for
spelling conventions for class and function names.

.. _PEP 8 -- Style Guide for Python Code:
   http://www.python.org/dev/peps/pep-0008/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My newbie annoyances so far

2007-04-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Bjoern Schliessmann wrote:

 Dennis Lee Bieber wrote:
 
 HP RPL made more sense: b if c [else d] end
 
 Please explain.
 
 HP RPL: b if c [else d] end
 Python: b if c else d
 
 What's the more sense here?

The HP RPL leaves even more questions.  If the square brackets mean the
``else`` part is optional, what would be the result of the expression if
`c` is `False`?

Hypothetical HP RPL syntax construct in Python::

  x = 42 if False end
  print x   # - ???

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which are your favorite UML tools?

2007-04-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Russell E. Owen
wrote:

 Some problems are intrinsic to UML (for instance it has no concept of 
 linking use case information to other elements). And I don't know of any 
 way to model functions (only classes).

Just model modules as classes and functions as static methods of the
module's class. Modules are objects too and can be seen as singletons.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Ping program

2007-04-28 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Linus Cohen
wrote:

 Actually the class ping bit is a placeholder. I'm actually developing
 a module with python implementations of most standard network/internet
 tools such as telnet, tracert, whois etc. It will be called inettools,
 and the ping function is what I'm working on first.

Still doesn't explain why it is a class.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python annoyances so far

2007-04-27 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Steven Howe
wrote:

 And before someone get's all technical, I know everything in Python is 
 an 'object' even None, which implies class, or is it the other way around?

Objects don't imply classes.  There are object oriented languages without
classes like the Io language.  Everything there is an object and the base
object has a `clone()` method to make a copy.  So you make copies of
objects and modify them to tweak them into the way you want them.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory addressing

2007-04-27 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Simon Berube
wrote:

 In short, how do I used Object at Memory Address strings to recreate
 a an object.

You already got the answer: you can't.  Either you still have a reference
to that object, or the memory address is not guaranteed to point to the
object anymore even if you could get an object from a raw memory address.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Dict Contains a particular key

2007-04-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 On Apr 24, 1:41 pm, Steven Bethard [EMAIL PROTECTED] wrote:
 Steven Howe wrote:

  or try:
  thedict = { 'a': 1, 'b':2, 'c':3 }
  if 'a' in thedict.keys():
 print thedict['a']

 Better yet, just:

  if 'a' in thedict:
  ...

 There's no need for the call to keys().
 
 Why not
 
 if thedict.has_key('a'):
 pass
 elde:
 pass

Additional to the speed argument, the ``in`` operator works with more
types, like lists, sets and iterables.  And if someone implements a
container class with membership testing, it is more likely he writes a
`__contains__()` method than a `has_key()` method.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File not read to end

2007-04-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
andrew.jefferies wrote:

 On Apr 25, 2:51 pm, Larry Bates [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Hi,

  I'm trying to write a simple log parsing program. I noticed that it
  isn't reading my log file to the end.

  My log is around 200,000 lines but it is stopping at line 26,428. I
  checked that line and there aren't any special characters.

  This is the file reading code segment that I'm using:
  sysFile=open(sysFilename,'r')
  lineCount = 0
  for line in sysFile:
  lineCount +=1
  print str(lineCount) +  --  + line

  I also stuck this same code bit into a test script and it was able to
  parse the entire log without problem. Very quirky.

 […]

 I've attached the whole script. Thanks again for your help.

There are ``break`` statements in the loop body!?  Do you really want to
leave the loop at those places?

And I've seen at least two times ``somefile.close`` which does just
reference the `close()` method but does not *call* it.  Parenthesis are
the call operator in Python and they are not optional!

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python keywords

2007-04-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], gtb wrote:

 Have done some searching but have not found a place where I can look
 up python keywords. I was looking at a script that contained the
 following line:
 
 assert self.getResponseCode() in (200, 304, 302)
 
 I can infer the usage here but previously I had thought that in was
 only used with 'for. I looked thru 'the Python Reference Manual and
 found in is a keyword but in skimming thru I found it only with
 for. The reference manual seems good but seems not to be setup for
 searching. Or maybe I just missed something.

If you look in the library reference index you'll find a link to the
`Sequence Types`_ section where it is mentioned as an operator that tests
if some object contains another.  And the reference manual has an index
entry called `in operator` which leads to the page Comparisons_, telling
how to overwrite the behaviour in your own classes.

.. _Sequence Types: http://docs.python.org/lib/typesseq.html
.. _Comparisons: http://docs.python.org/ref/comparisons.html

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python annoyances so far

2007-04-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], flifus wrote:

 Well, why do some things in the library have to be functions, and
 other things have to be class methods?
 
 Why aren't they all just either functions or class methods? like
 perhaps ruby.

To which class should `sorted()` belong to then?  Or the functions in the
`math` module?  What about `itertools`?

In languages without functions, like Java, you'll have to write static
methods where you really want functions, just because Java forces you to
stuff everything into classes.

And instead of a simple ``lambda`` function one needs to write an
anonymous class with a method.  Quite convoluted.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding conventions for class names

2007-04-25 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Kay Schluehr
wrote:

 set, int, float, list, object,...
 
 Don't see any of the basic types following the capitalized word
 convention for classes covered by PEP 08. This does not hold only for
 __builtins__ in the strict sense but also for types defined in builtin
 modules like datetime.

Most built-ins are easy to explain:  They were functions long before it
was possible to use them as base classes and stayed lowercase for
backwards compatibility.  Don't know about `set` and `object`.  I guess
it's foolish consistency!?

 My question is: does anyone actually follow guidelines here and if yes
 which ones and are they resonable ( e.g. stable with regard to
 refactoring etc. )?

I follow PEP 8 in my (mostly unpublished) code if that does matter to you.  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subprocess.Popen fails, but os.system works

2007-04-24 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], bahoo wrote:

 This line of code fails (see error message at the end),
 
 last_line = subprocess.Popen([D:/release/win.exe 0.5 1000 100 D:/
 images/img.ppm out.ppm], stdout=subprocess.PIPE).communicate()[0]
 
 but using os.system works:
 os.system('D:/release/win.exe 0.5 1000 100 D:/images/img.ppm out.ppm')
 
 --
 C:/Python25/pythonw.exe -u  D:/run.pyw
 Traceback (most recent call last):
   File D:/run.pyw, line 59, in module
 process_dir(mydir)
   File D:/run.pyw, line 52, in process_dir
 segmentation (dir,f)
   File D:/run.pyw, line 35, in segmentation
 last_line = subprocess.Popen([D:/release/win.exe 0.5 1000 100 D:/
 images/img.ppm out.ppm], stdout=subprocess.PIPE).communicate()[0]
   File C:\Python25\lib\subprocess.py, line 593, in __init__
 errread, errwrite)
   File C:\Python25\lib\subprocess.py, line 793, in _execute_child
 startupinfo)
 WindowsError: [Error 22] The filename, directory name, or volume label
 syntax is incorrect
 ---
 
 Can anyone tell me why?

You are trying to execute a program named::

  D:/release/win.exe 0.5 1000 100 D:/images/img.ppm out.ppm

Such a program does not exist on your computer.  ;-)

Give `subprocess.Popen()` a list with the program name and the individual
arguments as elements instead.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Javascript equivalence

2007-04-23 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Prateek wrote:

 Try creating a dict with sequential numeric keys.
 
 If you already have a list called my_list, you can do:
 
 com_array = dict(zip(range(len(my_list)), my_list))

com_array = dict(enumerate(my_list))

That doesn't create the intermediate lists.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion: str.itersplit()

2007-04-21 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Dustan wrote:

 From my searches here, there is no equivalent to java's
 StringTokenizer in python, which seems like a real shame to me.
 
 However, str.split() works just as well, except for the fact that it
 creates it all at one go. I suggest an itersplit be introduced for
 lazy evaluation, if you don't want to take up recourses, and it could
 be used just like java's StringTokenizer.
 
 Comments?

Does it really make such a difference?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python un-plugging the Interpreter

2007-04-20 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], John Nagle wrote:

 Many cases are easy.  If a smart compiler sees
 
   for i in range(n) :
  ... # something
 
 and there are no other assignments to i, then it's clear that
 i can be represented as an integer, without boxing into a
 general object.

How is it clear that `i` is restricted to integers?  That works only if
you assume `range` refers to the built-in `range()` function.  So the
smart compiler has to check all possible control flows up to this point
and be sure `range` was not bound to something different.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Feature Request: Explicit variable declarations

2007-04-20 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Alex Martelli wrote:

 Jorgen Grahn [EMAIL PROTECTED] wrote:
 
 As a C and C++ programmer (not a C/C++ programmer), I have to say that
 
 Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...?

Isn't it 1 unless `C` is 0?  The increment happens after the division,
right?  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling private base methods

2007-04-20 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Isaac
Rodriguez wrote:

 But the truth is that C++ and Java made a decision to do that for a
 reason, and the times when you have to work around those language
 features come once in a blue moon; they are the exception, not the
 rule, and you don't implement features in a language, or for that
 matter in an application, to simplify the exceptions; you try to
 implement the most common scenarios.

So the most common scenario is that programmers try to poke around all the
time in the internals of classes even if the need to do so is
very rare?  Otherwise it would not be necessary to have and use a
mechanism to declare everything private.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested dictionaries trouble

2007-04-18 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], IamIan wrote:

 years = [199%s % x for x in range(0,10)]
 years += [200%s % x for x in range(0,10)]
 
 I haven't had any luck doing this in one line though. Is it possible?

In [48]: years = map(str, xrange(1999, 2011))

In [49]: years
Out[49]:
['1999',
 '2000',
 '2001',
 '2002',
 '2003',
 '2004',
 '2005',
 '2006',
 '2007',
 '2008',
 '2009',
 '2010']

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Syntax error

2007-04-17 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], hg wrote:

 I had the customer comment out the first two lines of the file:
 
 
 #!/bin/env python
 # -*- coding: iso-8859-15 -*-
 
 
 ... and the problem disappeared.
 
 I am at a loss.
 
 Any clue ?

There was once a bug in Python that lead to such errors if an encoding
comment was used.  So your costumer might check his Python version and
maybe he should update.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to initialize a table of months.

2007-04-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Steven W. Orr
wrote:

 I want to call datetime.datetim() whose arg2 is a number between 1-12 so I 
 have to convert the month to an integer.
 I wrote this, but I have a sneaky suspicion there's a better way to do it.
 
 mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6,
  'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 }
 
 def mon2int( mon ):
  global mons
  return mons[mon]

You've already got some answers, I just want to point out that the
``global`` is unnecessary here and that `mons` as a constant should be
spelled in capital letters by convention.  And maybe it's better to write
`MONTHS` instead the abbreviation.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 question

2007-04-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Gabriel
Genellina wrote:

 En Thu, 12 Apr 2007 08:43:49 -0300, Marc 'BlackJack' Rintsch  
 [EMAIL PROTECTED] escribió:
 
 In [EMAIL PROTECTED], Jorgen Bodde
 wrote:

 r = c.execute('select * from song where id = 1')
 for s in r:
 ... print s
 ... 
 (1, u'Spikedrivers Blues', u'Mississippi John Hurt')
 
 This should not work because `r` should not be a `Cursor` object.  The
 `execute()`-Method returns an integer with the number of affected rows.
 
 Actually DBAPI 2.0 says the return value is undefined.

I just remembered the number of affected rows, but that's just for data
manipulation statements like ``UPDATE`` or ``INSERT``.  For ``SELECT`` the
method should return `None`.  My bad.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pyparsing Catch-22

2007-04-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], 7stud wrote:

 However, all of the beginning examples use a Word() in the parse
 expression, but I couldn't find an adequate explanation of what the
 arguments to Word() are and what they mean.  I finally found the
 information buried in one of the  many documents--the one called
 Using the Pyparsing Module.  If that seems like an obvious place to
 look, I did start there, but I didn't find it at first.

An obvious place should be the docstring of the `Word` class which says:

Token for matching words composed of allowed character sets.
Defined with string containing all allowed initial characters,
an optional string containing allowed body characters (if omitted,
defaults to the initial character set), and an optional minimum,
maximum, and/or exact length.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate a continuous string

2007-04-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
人言落日是天涯,望极天涯不见家 wrote:

 How to generate a continuous string, like this
 aaa
 the number of characters is dynamic. Is there a module or function
 implement this string ?
 such as: duplicate_string(char, num)

Even easier: multiply the string by a number.

In [12]: 'a' * 5
Out[12]: 'a'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: file resume

2007-04-16 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], luca72 wrote:

 if i have one file written in binary mode, how can i append others
 binary data to this file after the its closure.
 ex
 my_file = open('blabal', 'wb')
 then i write something and then
 my_file.close()
 now if i need to open it again and append other binary data how can i
 proceed?

Just open it in append mode: ``open('blablal', 'ab')``

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: Python editor/IDE on Linux?

2007-04-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Dotan Cohen
wrote:

 Has anyone any experience with Python in Kate or Kdevelop?

I'm using Kate/KWrite quite often.  Syntax highlighting and an auto
indention for Python are standard features.  The only extra I'm using is
the word completion plug-in to spare myself too much typing and limit
typing errors in long names.

Along with the editor there's always a terminal with IPython running to
test and explore my own code and libraries.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to strip the domain name in python?

2007-04-15 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Marko.Cain.23
wrote:

 On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
 On Apr 14, 12:02 am, Michael Bentley [EMAIL PROTECTED]
 wrote:



  On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:

   Hi,

   I have a list of url names like this, and I am trying to strip out the
   domain name using the following code:

  http://www.cnn.com
  www.yahoo.com
  http://www.ebay.co.uk

   pattern = re.compile(http:(.*)\.(.*), re.S)
   match = re.findall(pattern, line)

   if (match):
   s1, s2 = match[0]

   print s2

   but none of the site matched, can you please tell me what am i
   missing?

  change re.compile(http:(.*)\.(.*), re.S) to re.compile(http:\/
  \/(.*)\.(.*), re.S)

 Thanks. I try this:

 but when the 'line' ishttp://www.cnn.com, I get 's2' com,
 but i want 'cnn.com' (everything after the first '.'), how can I do
 that?

 pattern = re.compile(http:\/\/(.*)\.(.*), re.S)

 match = re.findall(pattern, line)

 if (match):

 s1, s2 = match[0]

 print s2
 
 Can anyone please help me with my problem?  I still can't solve it.
 
 Basically, I want to strip out the text after the first '.' in url
 address:
 
 http://www.cnn.com - cnn.com

from urlparse import urlsplit

def get_domain(url):
net_location = urlsplit(url)[1]
return '.'.join(net_location.rsplit('.', 2)[-2:])

def main():
print get_domain('http://www.cnn.com')

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


<    5   6   7   8   9   10   11   12   13   14   >