Peter Hansen wrote:
> Kent Johnson wrote:
>
>> The simplest fix is to use raw strings for all your Windows path needs:
>> os.path.isfile(r'c:\bookmarks.html')
>> os.path.isfile(r'c:\wumpus.c')
>
>
> Simpler still is almost always t
ec per loop
You need a lot of imports before 1 usec becomes "appreciable". And your
proposal is doing the import anyway, just under the hood. How will you
avoid the same penalty?
Kent
--
http://mail.python.org/mailman/listinfo/python-list
27;Peters', 'Thomas', 'Liesner']
>
> I think it is theoretically faster (and more pythonic) than using regexes.
Unfortunately it gives the wrong result.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
(PyLint, PyChecker, pyflakes) work with Jython? To
do so they would have to work with Python 2.1, primarily...
Thanks,
Kent
--
http://mail.python.org/mailman/listinfo/python-list
ow to do
that the right way -- with __setattr__ -- rather than with __slots__ .
The recipe is here (it took me a few minutes to find it, I found the title
misleading):
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
Kent
--
http://mail.python.org/mailman/listinfo/python-list
command=lambda: callback('New'))
filemenu.add_command(label="Open...", command=lambda: callback('Open'))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=lambda: callback('Exit'))
mainloop()
Of course you could do this with named forwarding
x27;command' is bound to the function object
again.
OK, what about lambda? lambda is a way to create a simple anonymous function. One simple use of
lambda is to make a new function that binds a parameter to another function.
lambda: handleMenu('New')
defines a function that does the same thing as handleNew. The value of the lambda expression is the
function object. So
filemenu.add_command(label="New", command=lambda: handleMenu('New')) # OK
is another way to get the result you want.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
uence was going to have
basically a negligible cost for normal access (given the
overhead that is already present in python).
This was added to Python 2.4 as collections.deque
Kent
--
http://mail.python.org/mailman/listinfo/python-list
get by clicking on
the link at the bottom of every page.
Kent
(This has been the official policy for some time, but you're right that
it wasn't earlier documented. So I filed a bug report. ;-) If you
think this still isn't enough, file another.)
--
http://mail.python.org/mailman/listinfo/python-list
ain letters a-z and A-Z, digits 0-9
and underscore.
http://docs.python.org/ref/identifiers.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list
er = csv.writer(file("Test.csv", "wb"))
Kent
OS: W2k
Someone has an idea ?
thanks in advance
the source code is the following:
-->
import csv
class CsvDumper:
def __init__(self):
self.object =
[['la&
[EMAIL PROTECTED] wrote:
Kent:
I don't think so. You have hacked an attribute with latin-1
characters in it, but you
haven't actually created an identifier.
No, I really created an identifier. For instance
I can create a global name in this way:
globals()["è"]=1
global
Where can I download python-itools?
I found it in the python packages index but the site
is not contactable.
Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
ngle tag, , whose content is text containing
entity-escaped XML.
This is *not* an XML document containing tags , , ,
etc.
All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the
tag to be able to treat it as structured XML.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Irmen de Jong wrote:
Kent Johnson wrote:
[...]
This is an XML document containing a single tag, , whose
content is text containing entity-escaped XML.
This is *not* an XML document containing tags , ,
, etc.
All the behaviour you are seeing is a consequence of this. You need to
unescape the
to time.__init__? What happens to the 2001, 10, 31 arguments
to datetime.__init__?
I would expect the output to be
2001-10-31 01:02:03.04
2001-10-31 00:00:00.00
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Paul McGuire wrote:
"Kent Johnson" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
Martin Häcker wrote:
Hi there,
I just tried to run this code and failed miserably - though I dunno
why. Could any of you please enlighten me why this doesn't work?
Here is a s
http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group_id=5470&atid=105470
However its been fixed in a recent Python 2.3.
My example was developed in Python 2.4. The problem was the immutability of
datetime.
Kent
(I was bitten by the same thing which used to fail but
ang, fp)
fp.close()
def loadgame(path_to_name):
fp = open(path_to_name, "r")
the_whole_shebang = pickle.load(fp)
world_data, globalstate.all_fruit, globalstate.all_items =
the_whole_shebang
for attr, value in world_data.items():
setattr(world, attr, value)
fp.close()
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Klaus Neuner wrote:
Hello,
what is the fastest way to determine whether list l (with
len(l)>3) contains a certain element?
If you can use a set or dict instead of a list this test will be much
faster.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
ine for line in open("y.sql") if not
s_ora.search(line))
;)
Kent
except IndexError:
open("z.sql","w").writelines(lines)
but output is:
SET2_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;
It should delete every, not every other!
thx,
RasDJ
--
http://mail.python.org/mailman/listinfo/python-list
Thomas Guettler wrote:
# No comma at the end:
mylist=[]
for i in range(511):
mylist.append("Spam")
or just
mylist = ["Spam"] * 511
Kent
print ", ".join(mylist)
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
might do what you want:
http://www.crummy.com/software/BeautifulSoup/
Kent
--
http://mail.python.org/mailman/listinfo/python-list
lf,stuff):
def foo(self,b):
print b + stuff
self.bazz = new.instancemethod(foo, self, quux)
Of course for this simple example you can just remember stuff as an
attribute:
class quux(object):
def __init__(self,stuff):
self.stuff = stuff
def bazz(self, b):
Daniel Bickett wrote:
|def reverse( self ):
|"""
|Return a reversed copy of string.
|"""
|string = [ x for x in self.__str__() ]
|string.reverse()
|return ''.join( string )
def reverse(self):
return s
;x':1, 'y':2}
>>> b = {'x':3, 'y':3}
>>>
>>> f(a, **a)
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> f(b, **b)
>>> b
{'y': 3, 'x': 3, 'z': 6}
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Bo Peng wrote:
Yes. I thought of using exec or eval. If there are a dozen statements,
def fun(d):
exec 'z = x + y' in globals(), d
seems to be more readable than
def fun(d):
d['z'] = d['x'] + d['y']
But how severe will the performance penalty be?
You can precompile the string using compile(), y
tion of myfun out of fun2:
myfun = makeFunction('z = x + y', 'myfun')
def fun2(d):
for i in xrange(0,N):
myfun(d)
del d['__builtins__']
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Bo Peng wrote:
Kent Johnson wrote:
You are still including the compile overhead in fun2. If you want to
see how fast the compiled code is you should take the definition of
myfun out of fun2:
I assumed that most of the time will be spent on N times execution of
myfunc.
Doh! Right.
Kent
--
http
est in evaluating new tools and trying to pick
the best; they just use what is popular.
"I don't have time to sharpen my saw, I'm too busy cutting down this tree!"
Sigh.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
(who received the PSF grant) with help from several volunteers.
They are planning an alpha release soon.
I think the current released Jython will run on Java 1.1 but the new one will
require Java 1.2.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
t to the namespace:
import _bright as bright
Kent
--
http://mail.python.org/mailman/listinfo/python-list
hers how can I read (or convert) the binary file to am
> ascii file?
Use an instance of pstats.Stats to interpret the results:
from pstats import Stats
s = Stats('file')
s.print_stats()
etc.
http://docs.python.org/lib/profile-stats.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list
the browser directly (try View / Encoding in IE).
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Nader Emami wrote:
> Kent Johnson wrote:
>
>> Nader Emami wrote:
>>
>>> L.S.,
>>>
>>> I have used the profile module to measure some thing as the next
>>> command:
>>>
>>> profile.run('command', 'file')
Joost Jacob wrote:
> I am looking for a function that takes an input string
> and a pattern, and outputs a dictionary.
Here is one way. I won't say it's pretty but it is fairly straightforward and
it passes all your tests.
Kent
def fill(s, p):
"""
>
nably current:
http://www.pythonware.com/library/tkinter/introduction/index.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/
Kent
--
http://mail.python.org/mailman/listinfo/python-list
lib/python2.4/site-packages/Numeric/FFT/__init__.pyc'
No need for the detour through sys:
>>> import FFT
>>> FFT.__file__
'C:\\Python24\\lib\\site-packages\\Numeric\\FFT\\__init__.pyc'
Kent
--
http://mail.python.org/mailman/listinfo/python-list
Robert Kern wrote:
>
> And floating point is about nothing if not being usefully wrong.
>
+1 QOTW and maybe it could be worked into the FAQ about floats as well :-)
http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate
Kent
--
http://mail.p
-a",
> I don't see how you could really be sure of the point.
Try this article for an explanation of is-a:
http://www.objectmentor.com/resources/articles/lsp.pdf
IMO Robert Martin explains what good OO design is better than anyone else. His
book "Agile Software Development"
ng new elements.
ElementTree is preserving the whitespace of the original.
>
> Is their a function to 'pretty print' an element?
AFAIK this is not supported in ElementTree. I hacked my own by modifying
ElementTree._write(); it wasn't too hard to make a version that
t_exe especially, since I don't want to print to stdout, I
> want to provide the traceback in a popup dialog.
Use format_exception() or pass a StringIO object as the file parameter to
print_exc().
Kent
--
http://mail.python.org/mailman/listinfo/python-list
r 'htmlentitydefs' gives quite a few solutions.
Here is one way:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46
Kent
--
http://mail.python.org/mailman/listinfo/python-list
t re
>>> r=re.compile(r'(?P.{4,}).*(?P=seq)')
>>> r.match('abcaoeaeoudabc')
>>> r.match('abcdaeaeuabcd')
<_sre.SRE_Match object at 0x008D67E0>
>>> _.group(1)
'abcd'
>>> r.match('abcdefgaeae
brute force. Here is a regex that
matches a string containing a four-character substring and its reverse:
(?P.)(?P.)(?P.)(?P.).*(?P=s4)(?P=s3)(?P=s2)(?P=s1)
You might want to look at the Regular Expression HOW-TO document:
http://www.amk.ca/python/howto/regex/
Kent
--
http://mail.python.org/mailman/listinfo/python-list
assed to __new__() contains the methods and class
variables defined by the class statement.
See http://www.python.org/2.2/descrintro.html#metaclasses
Kent
--
http://mail.python.org/mailman/listinfo/python-list
yaffa wrote:
> does anyone have sample code for parsting an html file to get contents
> of a td field to write to a mysql db? even if you have everything but
> the mysql db part ill take it.
http://www.crummy.com/software/BeautifulSoup/examples.html
--
http://mail.python.org/mailman/listinfo/pyt
Yes, the compiled code makes heavy use of the Jython runtime to get anything
done.
*But* most of the hard work will probably be done by Java code in libraries you
call. For example a Swing UI, XML parsing, database calls, etc all will happen
in Java code. So in practice the performance penalty i
a in anchors[:10]:
... print a['href'], a.string
...
?N=D Name
?M=A Last modified
?S=A Size
?D=A Description
/immagini/riviste/covers/ Parent Directory
cp100.jpg cp100.jpg
cp100sm.jpg cp100sm.jpg
cp101.jpg cp101.jpg
cp101sm.jpg cp101sm.jpg
cp102.jpg cp102.jpg
http://www.crummy.com/software/BeautifulSoup/
Kent
--
http://mail.python.org/mailman/listinfo/python-list
27;\n', '"', '[' and ']'. I finally went with a few of
> these:
> string.replace('\n', '\\n')
> string.replace('"', '\\"')
You might like this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
Kent
--
http://mail.python.org/mailman/listinfo/python-list
;-lglut -lGLU -lGL -lm')
> env.Append(CPPPATH=['include', 'include/trackball'])
> libs = ['glut',
> 'GLU',
> 'GL',
> 'm',]
>>> LDFLAGS = '-lglut -lGLU -
gene tani wrote:
> Yes, there's a bunch. Google for "query parser" + python, "porter
> stemming" "stopwords" "text indexer". Maybe lucene has some python
> bindings, hmm?
At least two Python versions of Lucene:
http://pylucene.os
ator
class A:
a = 1
b = 2
getA = operator.attrgetter("a")
getB = operator.attrgetter("b")
def get2(x):
return getA(x), getB(x)
def get1(x):
return x.a, x.b
F:\>python -m timeit -s"from attr_tuple import A, get1, get2" "get1(A)"
100 loops, best of 3: 0.658 usec per loop
F:\>python -m timeit -s"from attr_tuple import A, get1, get2" "get2(A)"
100 loops, best of 3: 1.04 usec per loop
Kent
--
http://mail.python.org/mailman/listinfo/python-list
7;] = 42
... def __getitem__(self, item):
... # this doesn't get called from the eval statement
... print "*", item
... return dict.__getitem__(self, item)
...
>>> a = Foo()
>>>
>>> print a['val']
* val
42
>>> print eval('val*2+6', a)
* val
90
Kent
--
http://mail.python.org/mailman/listinfo/python-list
tin_function_or_method' instances
I want to create a tree where I can navigate from a node to its parent. The
standard Element class
doesn't seem to support this so I am trying to make a subclass that does. The
XML files in question
are large so the speed of cElementTree is very he
-
tains a couple of other famous stupidity quotes, including:
"Never underestimate the power of human stupidity"
"Search inside the book" finds this *twice* in "Time Enough For Love".
Kent
--
http://mail.python.org/mailman/listinfo/python-list
quot;: " + str(e) )
Have you looked at the traceback module? If you want to print the same kind of trace you get from
Python, just use traceback.print_exc().
import traceback
try:
# whatever
except:
traceback.print_exc()
Kent
But that works only if the exception happens to be derived from
files
to disambiguate UTF-8, big-endian UTF-16 and little-endian UTF-16.
See http://www.unicode.org/faq/utf_bom.html#BOM
Kent
--
http://mail.python.org/mailman/listinfo/python-list
f.__call__ = self.__call1
... def __call1(self):
...print 1
... def __call__(self):
...print 2
...
>>> t=test()
>>> t()
1
Kent
--
http://mail.python.org/mailman/listinfo/python-list
eforge.net/projects/adodbapi
Kent
--
http://mail.python.org/mailman/listinfo/python-list
e. So there is
something to look forward to...
http://tinyurl.com/4fbkb
Kent
--
http://mail.python.org/mailman/listinfo/python-list
t the unicode string to utf-8 before the write?
Where should I start?
Best rgs,
Kent Sin
--
http://mail.python.org/mailman/listinfo/python-list
Chad Everett wrote:
Nope, I am trying to learn it on my own. I am using the book by Michael
Dawson.
You might be interested in the Python tutor mailing list which is
specifically intended for beginners.
http://mail.python.org/mailman/listinfo/tutor
Kent
--
http://mail.python.org/mailman
Kent Johnson wrote:
You might be interested in the Python tutor mailing list which is
specifically intended for beginners.
http://mail.python.org/mailman/listinfo/tutor
Ah, I don't mean to imply that this list is unfriendly to beginners, or that you are not welcome
here! Just pointin
fs[1].remove(d)
Add this here:
yield fs
and take out the return. This turns build_clean_list() into a generator function and you will be
able to iterate the result.
Kent
return fs_objects
Just to clarify, it's wrong of me to say that 'nothing is returned&
"
So changes to the dir list affect the iteration; changes to the file list directly affect the value
you return to the caller.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
James Stroud wrote:
It seems I need constructs like this all of the time
i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1
There has to be a better way...
somelist[:] = [ item for item in somelist if not oughta_pop_it(item) ]
Kent
--
h
uot;my", "sample", "list"]
for item in mylist:
setattr(myclass, item, make_f(item))
Kent
--
http://mail.python.org/mailman/listinfo/python-list
;> class Mrw:
... books = []
...
>>> __m_rw = Mrw()
>>> __m_rw.books.append(1)
>>> __m_rw.books
[1]
but __m_rw.books will not be pickled with __m_rw because it belongs to the
class, not the instance.
The fix is to declare books as an instance attribute:
class Mrw
ore detailed information than just a list of names, see the
inspect module.
Or use 'help' (which is build on top of inspect):
>>> from smtplib import SMTP
>>> help(SMTP)
Help on class SMTP in module smtplib:
class SMTP
| This class manages a connection to an SMTP or ESMTP server.
| SMTP Objects:
| SMTP objects have the following attributes:
| helo_resp
| This is the message given by the server in response to the
| most recent HELO command.
etc.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
paration of content and presentation
IMO templating systems are a much better solution. They let you express HTML in HTML directly; you
communicate with a designer in a language the designer understands; you can separate content and
presentation.
Kent
Michele Simionato
--
http://mail.python.org/mailman/listinfo/python-list
und is to implement z() using eval() again, this forces f1() to use the same globals passed
to z():
>>> def z(): return eval(f1.func_code)
...
>>> eval(z.func_code,dict(A=1,B=2, f1=f1))
True
Kent
I should add that f1 is given as-is. I can modify z,
and f1 is just one of many functio
[EMAIL PROTECTED] wrote:
p.s. the reason I'm not sticking to reversed or even reverse : suppose
the size of the list is huge.
reversed() returns an iterator so list size shouldn't be an issue.
What problem are you actually trying to solve?
Kent
--
http://mail.python.org/mailman/listi
rt it in 'strict' mode. You should either
define __unicode__ or call str() manually on the object.
Not a bug, I guess, since it is documented, but it seems a bit bizarre that the encoding and errors
parameters are ignored when object does not have a __unicode__ method.
Kent
STeVe
[1]
ed throughout the
application.
It seems more correct to assume that the
str() result in in the system default encoding.
To assume that in absence of any guidance, sure, that is consistent. But to ignore the guidance the
programmer attempts to provide?
One thing that hasn't been pointed out in this thread yet is that the OP could just define
__unicode__() on his class to do what he wants...
Kent
--
http://mail.python.org/mailman/listinfo/python-list
s has sockets.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
John M. Gabriele wrote:
I know that Python doesn't do method overloading like
C++ and Java do, but how am I supposed to do something
like this:
This was just discussed. See
http://tinyurl.com/6zo3g
Kent
- incorrect
#!/usr/bin/python
class Po
supported in Python 2.4.
GB2312 support can be added to Python 2.3 with the CJKCodecs package:
http://cjkpython.i18n.org/
Kent
-
narke
--
http://mail.python.org/mailman/listinfo/python-list
>> '/foo/bar/beer/sex/cigarettes/drugs/alcohol/'.strip('/').split('/')
['foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol']
Kent
I was looking at the os.path.split command, but it only s
gf gf wrote:
Hi. I'm looking for a Python lib to convert HTML to
ASCII.
You might find these threads on comp.lang.python interesting:
http://tinyurl.com/5zmpn
http://tinyurl.com/6mxmb
Kent
--
http://mail.python.org/mailman/listinfo/python-list
super(MetaFoo, cls).__init__(cls, name, bases, d)
for u in ['sqrt', 'cos', 'tan']:
setattr(cls, u, lambda self, uf=getattr(Numeric, u): uf(self.value
+ 42.0))
class Foo(object):
__metaclass__ = MetaFoo
def __init__(self, value):
self.v
ords = [ word for word in some_string.split() if word in known_words ]
Kent
André
--
http://mail.python.org/mailman/listinfo/python-list
using? re was changed in Python 2.4 to avoid
recursion, so if you are getting a stack overflow in Python 2.3 you should try 2.4.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
>> print _nl
[4, 3, 2, 1]
Kent
--
http://mail.python.org/mailman/listinfo/python-list
#x27;s pretty much a universal truth.
GIYF
http://www.sprex.com/else/sidman/boite.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list
data.append([key, value])
print data
Score[RelevantInfo1][RelevantInfo3] = 22 # The value from RelevantInfo2
I'm not sure what you mean by this. Do you want to build a Score dictionary
as well?
Kent
Collected from all of the files.
So, there would be several of these "scores"
t element.
No, Raw_packet_queue[0] is [pcap packet header, pcap packet body] so Raw_packet_queue[0][1] is pcap
packet body. Raw_packet_queue[0][0][1] is (pcap packet header)[1] which doesn't work.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
27;strings' is a bit more work.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
ot; does what you want.
>>> import re
>>> re.search(r'com|com\.to', 'kuku.com.to').group()
'com'
>>> re.search(r'com\.to|com', 'kuku.com.to').group()
'com.to'
Kent
--
http://mail.python.org/mailman/listinfo/python-list
dir(f):
res.append(ele)
ele = join(f,ele)
if isdir(ele):
res.append(rec(ele))
return res
print rec(dirpath)
Kent
--
http://mail.python.org/mailman/listinfo/python-list
d Relevant2='60'.
The parser is a simple-minded state machine that will misbehave if the input does not have entries
in the order Relevant1, Relevant2, Relevant3 (with as many intervening lines as you like).
All three values are available when Relevant3 is detected so you could do some
Steven Bethard wrote:
Kent Johnson wrote:
for line in raw_data:
if line.startswith('RelevantInfo1'):
info1 = raw_data.next().strip()
elif line.startswith('RelevantInfo2'):
info2 = raw_data.next().strip()
elif line.startswith('Relev
different name than 'object', which is the base class of all
new-style classes.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
o PythonInterpreters wrap a single PySystemState which is where the
modules are cached. So they share the same modules. If you want different behaviour you should give
them each their own PySystemState.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
z^5(17l8(%,5.Z*(93-965$l7+-'])"
Kent
--
http://mail.python.org/mailman/listinfo/python-list
-s "floats = map(float, range(1000))" "ints=
map(int, floats)"
1000 loops, best of 3: 572 usec per loop
Kent
I used Numeric module to create a 1000 floats matrix of ones, and it seems
to me that is a lot faster than other solutions... but probably I am doing
something wrong in my call to the timeit function...
Thank you a lot.
Andrea.
--
http://mail.python.org/mailman/listinfo/python-list
make the cut. I've posted
a bug report.
Kent
--
http://mail.python.org/mailman/listinfo/python-list
t you want? What is it you really need
to do?
def foo(kwds): print kwds
foo(MyDict(a = 1, b = 2, c = 3))
Kent
--
http://mail.python.org/mailman/listinfo/python-list
keep doing what you have been doing and ignore the warnings from PyLint
- keep doing what you have been doing and turn off the warnings from PyLint
- rewrite your imports to be absolute imports
Kent
--
http://mail.python.org/mailman/listinfo/python-list
101 - 200 of 792 matches
Mail list logo