Request for useful functions on dicts

2012-07-14 Thread Leif
Hi, everybody. I am trying to collect all the functions I've found useful for 
working with dicts into a library:

https://github.com/leifp/dictutil

If you have a favorite dict-related func / class, or know of similar projects, 
please let me know (or open an issue on github). Bear in mind that the 
functions don't even have to come from python; if you have a favorite PHP / APL 
/ COBOL / etc associative array function, that's fair game.

Thanks,
Leif

P. S.  I'm participating in Julython [ http://www.julython.org/ ], and it's 
fun.  You should all join and show everyone that your city has the most open 
source python activity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for useful functions on dicts

2012-07-15 Thread Leif
Thanks for the suggestions, Ian!  I implemented most of them and pushed the 
code.

> That's because the Pythonic way is to either create a new object and
> return it, or mutate the existing object and return None.

You're saying what I was already thinking.

> In Python 2.7+, intersection and difference could be written using
> dictviews, which act like sets.

I'm debating with myself right now whether to support 2.5 and 2.6.

> def partition(f, d):

Good idea, thanks.

> issubdict could be implemented as a subset operation.  I haven't timed

The current implementation is a bit faster, and it's quite a bit faster on the 
common (for me) case, where one argument is much smaller than the other.  I 
wrote it that way because if m=len(first), n=len(second), the amount of work is 
O(min(m,n)).  Your implementation is O(m + n).  Not really a big deal, unless 
e.g. m << n. 

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


spyder v5: invalid file name when selecting interpreter in preferences

2022-07-23 Thread Leif Svalgaard
error message: invalid file path: C:/Users/leifs/anaconda3/python3105.exe
what is wrong with that?

-- 
Leif
l...@leif.org
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 227, Issue 3

2022-08-03 Thread Leif Svalgaard
 subatomic particle, consisting of four quarks and one antiquark bound
> together; they are not known to occur naturally or exist outside of
> experiments to create them. As quarks have a baryon number of (+1/3), and
> antiquarks of (−1/3), the pentaquark would have a total baryon number of 1
> and thus would be a baryon. Further, because it has five quarks instead of
> the usual three found in regular baryons (a.k.a.
> 'triquarks'), it is classified as an exotic baryon. The name pentaquark
> was coined by Claude Gignoux et al. (1987) and Harry J. Lipkin in 1987;
> however, the possibility of five-quark particles was identified as early as
> 1964 when Murray Gell-Mann first postulated the existence of quarks.
> Although predicted for decades, pentaquarks proved surprisingly tricky to
> discover and some physicists were beginning to suspect that an unknown law
> of nature prevented their production.
>
>
> # We hope you enjoy the new releases!
>
> Thanks to all of the many volunteers who help make Python Development and
> these releases possible! Please consider supporting our efforts by
> volunteering yourself or through organization contributions to the Python
> Software Foundation.
>
> https://www.python.org/psf/
>
> Your friendly release team,
>
> Ned Deily @nad https://discuss.python.org/u/nad Steve Dower @steve.dower
> https://discuss.python.org/u/steve.dower
> Pablo Galindo Salgado @pablogsal https://discuss.python.org/u/pablogsal
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
>
>
>
> -- Forwarded message --
> From: Axy 
> To: Python List 
> Cc:
> Bcc:
> Date: Mon, 1 Aug 2022 22:44:53 -0700
> Subject: Clabate: minimalistic class-based templates for Python
> Hi all,
>
> this is a test message after tweaking my self-hosted mail server and the
> subject is just in case if you receive it
>
> https://declassed.art/en/blog/2022/06/29/clabate-class-based-templates
>
> Previously I tried to reply to someone here but the message was
> rejected. Did not post to mail lists from my own mail server before, and
> this is the only problem left to dig in.
>
> Sorry for bothering.
>
> Axy
>
>
>
>
> -- Forwarded message --
> From: Stefan Ram 
> To: python-list@python.org
> Cc:
> Bcc:
> Date: 2 Aug 2022 10:16:50 GMT
> Subject: Re: Dictionary order?
> Dan Stromberg  writes:
> >What am I missing?
>
>   Modern Python Dictionaries A confluence of a dozen great ideas
>   - Raymond Hettinger (2017)
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Leif
l...@leif.org
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: replacments for stdio?

2005-09-23 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
>i was wondering if anyone have written a GUI module that can
> function as a replacment for stdin/stdout? ie. has a file like
> interface, by which one could just assaign it to sys.stdout or
> sys.stdin and have all your prints and raw_inputs and other such things
> shown in a GUI window?

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


Re: __call__ in module?

2005-09-27 Thread Leif K-Brooks
ncf wrote:
> I have a feeling that this is highly unlikely, but does anyone in here
> know if it's possible to directly call a module, or will I have to wrap
> it up in a class?

You could use trickery with sys.modules to automatically wrap it in a class:

import sys
from types import ModuleType

class CallableModule(ModuleType):
def __call__(self):
print "You called me!"

mod = FooModule(__name__, __doc__)
mod.__dict__.update(globals())
sys.modules[__name__] = mod
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with syntax warnings

2005-09-29 Thread Leif K-Brooks
Ivan Shevanski wrote:
> is there a way to turn off syntax warnings or just make them not
> visible?

import warnings
warnings.filterwarnings('ignore', category=SyntaxWarning)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Info] PEP 308 accepted - new conditional expressions

2005-10-01 Thread Leif K-Brooks
Sam wrote:
> And "foo if bar" is Perl-ish; yet, even Perl has the ? : operators.

What _isn't_ Perl-ish?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing programs

2005-10-02 Thread Leif K-Brooks
Jeff Schwab wrote:
> Sorta, but not really.  Typically, you might distribute the source (.py)
>  files, but if you don't want to do that, you can distribute the
> compiled .pyc files instead.  Python creates these files automatically
> when your modules are imported.

But remember that Python bytecode can be easily decompiled with a
publicly-available program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 class with same name in different module

2005-10-05 Thread Leif K-Brooks
Iyer, Prasad C wrote:
> I have a class in a module which is getting imported in main module. 
> How do you differentiate between the 2 class

import foo
import bar

foo.TheClass().dostuff()
bar.TheClass().dostuff()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python eats gator.

2005-10-05 Thread Leif K-Brooks
Sam wrote:
> http://www.wnbc.com/family/5060215/detail.html
> 
> I know there's an on-topic joke in here somewhere, but I'm having some
> problem finding it, at the moment.
> 
> You may take a crack at it, if you'd like…

Hmm... has anyone ever written a spyware removal tool in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.access with wildcards

2005-10-06 Thread Leif K-Brooks
mike wrote:
> i'd like to use
> 
>os.access(path,mode)
> 
> where path may contain linux style wildcards.

os.access(glob.glob(path), mode)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing an AST

2005-10-10 Thread Leif K-Brooks
beza1e1 wrote:
> Is it possible compiler.parse a statement, then change and then
> execute/resolve it?

This should work:


 >>> from compiler.pycodegen import ModuleCodeGenerator
 >>> from compiler.misc import set_filename
 >>> from compiler import parse
 >>>
 >>> tree = parse('foo = 42')
 >>> set_filename('', tree)
 >>> code = ModuleCodeGenerator(tree).getCode()
 >>> exec code
 >>> foo
 42

Also, if you need to turn an AST back into Python code, I have some ugly
code for doing that: .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie regex

2005-10-17 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> I want to filter some strings,but i don t know how to use compile
> method.

Why not?

> first character must be [a-zA-z] group and others can only be digits or
> letters.

if re.search('^[a-zA-Z][a-zA-Z0-9]*$', foo):
print "Valid string."
else:
print "Invalid string."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie regex

2005-10-17 Thread Leif K-Brooks
Leif K-Brooks wrote:
> [EMAIL PROTECTED] wrote:
> 
>>I want to filter some strings,but i don t know how to use compile
>>method.
> 
> Why not?


Sorry: I misread that as not _wanting_ to use the compile method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting 2bit hex representation to integer ?

2005-10-19 Thread Leif K-Brooks
Madhusudan Singh wrote:
> I am using binascii.b2a_hex to convert some binary data to hex. The
> result is a two bit hex representation (i. e., without the leading
> 0x).

Surely you mean two-byte?

> How do I convert the resulting two bit representation into an integer
> ?

int(foo, 16)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary that have functions with arguments

2005-11-02 Thread Leif K-Brooks
Alex Martelli wrote:
> execfunc = { 'key1' : (func1, ()),
>  'key2' : (func2, args) }
> 
> now, something like:
> 
> f, a = execfunc[k]
> f(**a)
> 
> will work for either key.

Shouldn't func1's args be a dictionary, not a tuple?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I Need Motivation Part 2

2005-11-04 Thread Leif K-Brooks
Sybren Stuvel wrote:
> There are over 2800 header files on my system in /usr/include. What do
> you mean "a limited number of header files"?

I assume he's saying that the number is < ∞. (Of course, the same is
true of Python modules unless you use a special __import__ hook or
something...)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I do this in Python?

2005-11-04 Thread Leif K-Brooks
Steve Holden wrote:
> Another alternative might be to serve a script that sent the browser
> back 2 pages in its history, as long as server state hasn't changed in
> the meantime.

What about users with JavaScript disabled?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a List into a String

2005-11-05 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> list = ['f', 'e', 'd', 'c', 'b', 'a']
> 
> How can i convert it into a string so the output is
> 
> fedcba

print ''.join(list)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: overloading *something

2005-11-07 Thread Leif K-Brooks
James Stroud wrote:
> Hello All,
> 
> How does one make an arbitrary class (e.g. class myclass(object)) behave like 
> a list in method calls with the "*something" operator? What I mean is:
> 
> myobj = myclass()
> 
> doit(*myobj)

Make it iterable:

 >>> class Foo(object):
 ... def __iter__(self):
 ... yield 1
 ... yield 2
 ... yield 3
 ...
 >>> def bar(*args):
 ... print args
 ...
 >>> bar(*Foo())
 (1, 2, 3)


> And, how about the "**something" operator?

Use a dictionary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to stop a loop with ESC key? [newbie]

2005-11-08 Thread Leif K-Brooks
mo wrote:
> Can somebody explain how to stop a WHILE loop in running program by pressing
> ESC key?

On Unix-like systems try:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

i = 0
try:
while 1:
print i
i += 1
try:
char = sys.stdin.read(1)
if char == '\x1b':
print "Bye!"
break
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ x for x in xrange(10) when p(x) ]

2005-11-10 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> George Sakkis wrote:
>
>list(takewhile(p, xrange(1000)))
>>
>>[0, 1]
> 
> thanks. that is what I am doing now, in a more generic form :
> 
> takewhile(p, (x for x in xrange(1)))

How does a useless generator expression make it more generic?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ x for x in xrange(10) when p(x) ]

2005-11-10 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> Leif K-Brooks wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>thanks. that is what I am doing now, in a more generic form :
>>>
>>>takewhile(p, (x for x in xrange(1)))
>>
>>How does a useless generator expression make it more generic?
> 
> xrange is only picked as an example. I may be newbie on python but not
> that dumb if all I want is a list of integer(sorted) that meets certain
> criteria.
> 
> takewhile(p, (x for x in
> some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs)))

Wrapping a function in a generator expression doesn't magically make it
  lazily evaluated. The whole list has to be generated and returned;
using a generator expression instead of a list comprehension just means
that it doesn't need to be copied in memory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion about __call__ and attribute lookup

2005-11-10 Thread Leif K-Brooks
Kent Johnson wrote:
> But why doesn't Foo.__call__ shadow type.__call__? Normally an instance
> attribute takes precedence over a class attribute. Is it something
> special about how function call syntax is handled internally, or do all
> special methods work this way, or is there something else going on?

New-style classes look up special methods on the class, not on the instance:

 >>> class Foo(object):
 ... def __invert__(self):
 ... return 'foo'
 ...
 >>> x = Foo()
 >>> ~x
 'foo'
 >>> x.__invert__ = 123
 >>> x.__invert__()
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: 'int' object is not callable
 >>> ~x # equivalent to type(x).__invert__()
 'foo'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recompile AST?

2005-11-10 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> Is it possible to recompile the AST generated by compiler.parse, back
> into code or an executable code object?

Into a bytecode object:

 >>> from compiler.pycodegen import ModuleCodeGenerator
 >>> from compiler.misc import set_filename
 >>> from compiler import parse
 >>>
 >>> tree = parse('foo = 42')
 >>> set_filename('', tree)
 >>> code = ModuleCodeGenerator(tree).getCode()
 >>> exec code
 >>> foo
 42

Into Python source code: .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list of lambda

2005-11-11 Thread Leif K-Brooks
jena wrote:
> hello,
> when i create list of lambdas:
> l=[lambda:x.upper() for x in ['a','b','c']]
> then l[0]() returns 'C', i think, it should be 'A'

Fredrik Lundh provided the general solution, but in this specific case,
the simplest solution is:

l = [x.upper for x in ['a', 'b', 'c']]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse file into array

2005-11-14 Thread Leif K-Brooks
amfr wrote:
> I was wondering how i could parse the contents of a file into an array.
>  the file would look something like this:
> 
> gif:image/gif
> html:text/html
> jpg:image/jpeg
> ...
> 
> As you can see, it contains the mime type and the file extension
> seperated by commas, 1 per line.  I was wondering if it was possible to
> create and array like this:
> 
> (Pseudocode)
> mimetypearray[gif] = "image/gif"
> mimetypearray[html] = "text/html"
> mimetypearray[jpg] = "image/jpeg"
> ...

You want a dictionary, not an array.

mimetypedict = {}
for line in mimetypefile:
line = line.rsplit('\r\n')
extension, mimetype = line.split(':')
mimetypedict[extension] = mimetype

Note that there's already a MIME type database in the standard mimtypes
module: .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse file into array

2005-11-14 Thread Leif K-Brooks
Leif K-Brooks wrote:
> line = line.rsplit('\r\n')
Er, that should be line.rstrip, not line.rsplit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Leif K-Brooks
Sion Arrowsmith wrote:
> Steven Bethard  <[EMAIL PROTECTED]> wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>s = long("0xL")
>>>ValueError: invalid literal for long(): 0xL
>>>
>int("0x", 0)
>>
>>4294967295L
> 
> So why does the base argument to int() (or long()) default to
> 10 and not 0?

Because it's designed for numbers normal people provide, not for numbers
programmers provide. Normal people see 0123 as being equal to 123, not 83.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python speed

2005-12-01 Thread Leif K-Brooks
Krystian wrote:
>>I would also like to see Half Life 2 in pure Python.
> 
> or even quake1, do you think it could have any chances to run
> smoothly?

If  can run at a
reasonably speed, yes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to execute an EXE via os.system() with spaces in the directory name?

2005-12-04 Thread Leif K-Brooks
Leif K-Brooks wrote:
> It's perfectly reasonable behavior, and it also applies to Linux. The
> shell uses spaces to separate arguments; how do you expect it to know
> that you want a space to be part of the program's name unless you escape it?

I'm sorry, disregard my message. I failed to read the OP properly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to execute an EXE via os.system() with spaces in the directory name?

2005-12-04 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> This comes up from time to time.  The brain damage is all Windows', 
> not Python's.

It's perfectly reasonable behavior, and it also applies to Linux. The
shell uses spaces to separate arguments; how do you expect it to know
that you want a space to be part of the program's name unless you escape it?

> Here's one thread which seems to suggest a bizarre doubling of the 
> initial quote of the commandline.

A better solution would be to use subprocess:
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python & unicode

2005-01-10 Thread Leif K-Brooks
John Roth wrote:
It doesn't work because Python scripts must be in ASCII except for
the contents of string literals. Having a function name in anything
but ASCII isn't supported.
To nit-pick a bit, identifiers can be in Unicode; they're simply 
confined to digits and plain Latin letters.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python & unicode

2005-01-11 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
So is the support of Unicode in virtually every computer language
because they don't support ... digits except 0..9.
Hex digits aren't 0..9.
Python 2.4 (#2, Dec  3 2004, 17:59:05)
[GCC 3.3.5 (Debian 1:3.3.5-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0xCF
207
>>> hex(123)
'0x7b'
--
http://mail.python.org/mailman/listinfo/python-list


Re: counting items

2005-01-12 Thread Leif K-Brooks
Paul McGuire wrote:
Considering how often this comes up, might there be a place for some sort of
flatten() routine in the std dist, perhaps itertools?
A problem I see is that itertools tries to work across all iterable 
types, but flattening can't always be a generalized operation. For 
instance, a naive flattening function might turn the list ['foo', 'bar'] 
into ['f', 'o', 'o', 'b', 'a', 'r'] -- or worse, fall into infinite 
recursion -- when the intended result would be to leave the list 
unchanged. Of course, a generalized flattening function could take an 
argument listing types to ignore, but that can get very complicated very 
fast.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Octal notation: severe deprecation

2005-01-13 Thread Leif K-Brooks
Tim Roberts wrote:
Stephen Thorne <[EMAIL PROTECTED]> wrote:
I would actually like to see pychecker pick up conceptual errors like this:
import datetime
datetime.datetime(2005, 04,04)

Why is that a conceptual error?  Syntactically, this could be a valid call
to a function.  Even if you have parsed and executed datetime, so that you
know datetime.datetime is a class, it's quite possible that the creation
and destruction of an object might have useful side effects.
I'm guessing that Stephen is saying that PyChecker should have special 
knowledge of the datetime module and of the fact that dates are often 
specified with a leading zero, and therefor complain that they shouldn't 
be used that way in Python source code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to control the mouse pointer with python?

2005-01-13 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
Anybody know a way to control the mouse pointer
(move it around and click on things) using python?
It depends on your operating system. For Windows, you'll want to use a 
Python module to access the Win32 API. The relevant API function is 
documented at http://tinyurl.com/jrxm>.
--
http://mail.python.org/mailman/listinfo/python-list


Re: One-Shot Property?

2005-01-18 Thread Leif K-Brooks
Kevin Smith wrote:
I have many cases in my code where I use a property for calculating a 
value on-demand.  Quite a few of these only need to be called once.  
After that the value is always the same.  In these properties, I set a 
variable in the instance as a cached value and return that value on 
subsequent calls.  It would be nice if there was a descriptor that would 
do this automatically.  Actually, what would be really nice is if I 
could replace the property altogether and put the calculated value in 
its place after the first call, but the property itself prevents me from 
doing that.
This should do it:
class CachingProperty(object):
def __init__(self, attr_name, calculate_function):
self._name = attr_name
self._calculate = calculate_function
def __get__(self, obj, type=None):
if obj is None:
return self
else:
value = self._calculate(obj)
setattr(obj, self._name, value)
return value
And example code:
>>> class Foo(object):
... def calculate_value(self):
... print 'Calculating...'
... return 42
... foo = CachingProperty('foo', calculate_value)
...
>>> bar = Foo()
>>> bar.__dict__
{}
>>> bar.foo
Calculating...
42
>>> bar.foo # Notice that the print statement doesn't run this time
42
>>> bar.__dict__
{'foo': 42}
--
http://mail.python.org/mailman/listinfo/python-list


Solutions for data storage?

2005-01-18 Thread Leif K-Brooks
I'm writing a relatively simple multi-user public Web application with 
Python. It's a rewrite of a similar application which used PHP+MySQL 
(not particularly clean code, either). My opinions on various Web 
frameworks tends to vary with the phase of the moon, but currently, I'm 
planning to use Quixote.

Needless to say, my application will need some kind of persistent data 
storage. The previous PHP+MySQL application uses around 1.1GB of 
storage, so something like PyPerSyst where everything is kept in memory 
is out.

I've looked at SQLObject, and it's very nice, but it doesn't provide 
certain features I really want, like the ability to store lists of 
strings or integers directly in the database (using commas in a varchar 
column or something).

ZODB is very nice, but IndexedCatalog doesn't seem to provide any 
automatic mechanisms for things like ensuring attribute uniqueness (for 
e.g. usernames). I suppose I could implement manual checking in every 
class that needs it, but it really seems like very error-prone code to 
be implementing at the application level.

My ideal solution would be an object database (or object-relational 
mapper, I guess) which provided total transparency in all but a few 
places, built-in indexing, built-in features for handling schema 
changes, the ability to create attributes which are required to be 
unique among other instances, and built-in querying with pretty syntax. 
Atop seems to come pretty close, but since it's meant to be used in the 
asynchronous Twisted environment, it doesn't provide any thread safety.

So basically, I'm wondering if there are any Python data storage 
solutions I haven't noticed that come a bit closer to what I'm looking 
for. I could live without built-in schema evolution; the querying is 
really the most important feature I want.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Solutions for data storage?

2005-01-19 Thread Leif K-Brooks
Robert Brewer wrote:
Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query
syntax. Wait a couple of days, and I'll have version 1.3 ready and
online at http://www.aminus.org/rbre/python -- lots of changes from
1.2.6 which is there now, but at least you can read old docs online now
without svn.
Thanks a lot for the reply. I've skimmed the documentation (very 
well-written, by the well), and I really like the looks of what I've 
seen so far. I'm a bit confused about where sandboxes get created, 
though; in a Web application, would I give each request a sandbox of its 
own, or create one for the entire application, or what?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unbinding multiple variables

2005-01-20 Thread Leif K-Brooks
John Hunter wrote:
>>>del locals()['x']
The locals() dictionary will only modify values in a module's top-level 
code (i.e. when the expression "locals() is globals()" is true).
--
http://mail.python.org/mailman/listinfo/python-list


Re: What YAML engine do you use?

2005-01-22 Thread Leif K-Brooks
Bengt Richter wrote:
I thought XML was a good idea, but IMO requiring quotes around
even integer attribute values was an unfortunate decision.
I think it helps guard against incompetent authors who wouldn't 
understand when they're required to use quotes and when they're not. I 
see HTML pages all of the time where the author's done something like:

http://example.com/foo/bar/baz/spam/>
Sometimes it even has spaces in it. At least with a proper XML parser, 
they would know where they went wrong right away.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Quoting sql queries with the DB-API

2005-01-23 Thread Leif K-Brooks
snacktime wrote:
I'm used to using the perl DBI and not very familiar with the python
DB-API.  I am using PyGreSQL.  My question is what is the standard way
to quote strings in sql queries?  I didn't see any quoting functions
in the DB-API docs.  Is quoting handled internally by the PyGreSQL
module?
Also, is this a good way to use variables in an insert/update
statement, or is there a better way?
sql = "insert into test(a,b) values('%s','%s')" % (a,b)
cursor.execute(sql)
If you do it like this:
sql = "INSERT INTO test(a, b) VALUES(%s, %s)" # no quotes around the %s
cursor.execute(sql, (a, b))
Then the quoting will be handled automatically for you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: set, dict and other structures

2005-01-31 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
I'm frequently using Py2.4 sets, I find them quite useful, and I like
them, even if they seem a little slower than dicts.
They look exactly the same speed-wise to me:
>>> t1 = Timer('randrange(100) in foo', 'from random import randrange; 
foo = set(xrange(1000))')
>>> t2 = Timer('randrange(100) in foo', 'from random import randrange; 
foo = dict.fromkeys(xrange(1000))')
>>> t1.timeit()
3.0573790073394775
>>> t2.timeit()
3.064924955368042
>>> t2.timeit()
3.0590860843658447
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-04 Thread Leif K-Brooks
Alan McIntyre wrote:
You could do something like this:
blah = type('Struct', (), {})()
blah.some_field = x
I think I'd only do this if I needed to construct objects at runtime 
based on information that I don't have at compile time, since the two 
lines of code for your empty class would probably be more recognizable 
to more people.
Actually, in Python, class definitions are runtime executable statements 
just like any other. You can do this:

>>> def make_class(with_spam=True):
...  if with_spam:
...   class TheClass(object):
...def dostuff(self):
... print 'Spam, spam, spam, spam!'
...  else:
...   class TheClass(object):
...def dostuff(self):
... print "I don't like spam!"
...  return TheClass
...
>>> make_class(True)().dostuff()
Spam, spam, spam, spam!
>>> make_class(False)().dostuff()
I don't like spam!
And this:
>>> class Foo(object):
...  num = 3
...  for _ in xrange(14):
...   num *= 1.22
...
>>> Foo.num
48.546607267977542
--
http://mail.python.org/mailman/listinfo/python-list


Word for a non-iterator iterable?

2005-02-05 Thread Leif K-Brooks
Is there a word for an iterable object which isn't also an iterator, and 
therefor can be iterated over multiple times without being exhausted? 
"Sequence" is close, but a non-iterator iterable could technically 
provide an __iter__ method without implementing the sequence protocol, 
so it's not quite right.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Leif K-Brooks
Philip Smith wrote:
I don't seem to be able to define multiple versions of __init__ in my matrix 
class (ie to initialise either from a list of values or from 2 dimensions 
(rows/columns)).
You could either use an if statement with *args:
class Matrix(object):
def __init__(self, *args):
if len(args) == 1:
# Initialize from list of values
elif len(args) == 2:
# Initialize from rows/columns
else:
raise TypeError("Constructor accepts 1 or 2 arguments.")
Or with two different functions:
class Matrix(object):
def __init__(self, values):
# Initialize from a list of values
@classmethod
def from_pair(self, rows, columns):
return Matrix([rows, columns]) # Or with the right argument
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Leif K-Brooks
Leif K-Brooks wrote:
@classmethod
def from_pair(self, rows, columns):
return Matrix([rows, columns]) # Or with the right argument
Er... I'm not sure why I named that argument "self", it should be "cls" 
if you don't want to  confuse anyone reading your code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shortcut to initialize variables

2005-06-19 Thread Leif K-Brooks
Kent Johnson wrote:
> letters = {}
> for letter in ascii_lowercase:
>  letters[letter] = 0

Or more simply:

letters = dict.fromkeys(ascii_lowercase, 0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can we pass some arguments to system("cmdline")?

2005-06-20 Thread Leif K-Brooks
Didier C wrote:
> E.g in Perl, we can do something like:
> 
> $dir="/home/cypher";
> 
> system("ls $dir");
> 
> Is there a way to reproduce the same thing in Python?

system("ls %s" % dir)

But you should really be using subprocess for security (so that if
dir=="/home/foo; rm -rf /" nothing bad will happen):

import subprocess
subprocess.Popen(['ls', dir])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.call(*args **kwargs) on Linux

2005-06-20 Thread Leif K-Brooks
McBooCzech wrote:
> This is easy. Subprocess function "call" looks:
> returncode = subprocess.call(["/root/dex/dex","/dev/ttyS0",
> "blabla.txt"])
> and it runs smoothly.
> 
> The problem starts when I am trying to add 1>/dev/null 2>/dev/null
> parameters to suppres output sendings.

from subprocess import call, STDOUT
call(["command", "arg", "arg"], stdout=open("/dev/null", "w"),
stderr=STDOUT)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a dictionary from a list

2005-06-24 Thread Leif K-Brooks
David Bear wrote:
> Is there an easy way to create a dictionary object with the members of
> 'alist' being the keys in the dictionary, and the value of the keys set to
> null?

adict = dict.fromkeys(alist)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute python code and save the stdout as a string

2005-06-25 Thread Leif K-Brooks
jwaixs wrote:
> I've a question. Can I execute a part of a python code and put it's
> output in a string?

 >>> import sys
 >>> from cStringIO import StringIO
 >>>
 >>> def exec_and_get_output(code):
 ... old_stdout = sys.stdout
 ... sys.stdout = StringIO()
 ... try:
 ... exec code in {}, {}
 ... return sys.stdout.getvalue()
 ... finally:
 ... sys.stdout = old_stdout
 ...
 >>> exec_and_get_output("print 'foo'")
 'foo\n'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there an equivalent of javascript's this["myMethod"] for the currently running script?

2005-07-05 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> I'd like to dynamically find and invoke a method in a Python CGI.

getattr(self, methodName)()

But make sure to validate user input first, of course.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditionally implementing __iter__ in new style classes

2005-07-06 Thread Leif K-Brooks
Thomas Heller wrote:
> I forgot to mention this: The Base class also implements a __getitem__
> method which should be used for iteration if the .Iterator method in the
> subclass is not available.  So it seems impossible to raise an exception
> in the __iter__ method if .Iterator is not found - __iter__ MUST return
> an iterator if present.

def Iterator(self):
for index in xrange(len(self)):
yield self[index]

def __iter__(self):
return self.Iterator()

...and then override Iterator in subclasses. But this raises the
question of why you need to use a specially-named method instead of
having subclasses override the __iter__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Leif K-Brooks
Grant Edwards wrote:
> 1) So I know whether an parameter was passed in or not. Perhaps
>it's not considered good Pythonic style, but I like to use a
>single method for both get and set operations.  With no
>parameters, it's a get.  With a parameter, it's a set:
> 
>class demo:
>   def foo(v=None):
>   if v is not None:
>   self.v = v
>   return self.v  

_NOVALUE = object()
class demo:
def foo(v=_NOVALUE):
if v is _NOVALUE:
return self.v
else:
self.v = v

But what's wrong with properties?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Leif K-Brooks
Grant Edwards wrote:
> On 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
>>_NOVALUE = object()
>>class demo:
>>def foo(v=_NOVALUE):
>>if v is _NOVALUE:
>>return self.v
>>else:
>>self.v = v
> 
> 
> Apart from the change in the logic such that the set operation
> doesn't return a value, how is that any different?  You're just
> creating your own non-integer-value "None" object instead of
> using the one built in to the language.

Sorry, my mistake: for some reason, I misunderstood your message as
complaining that you couldn't do the same thing if you needed None to be
usable as a value too.

>>But what's wrong with properties?
> 
> Huh?

Why not use a property
(http://www.python.org/2.2.1/descrintro.html#property) instead of a
special property-like method?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing list comprehensions in Python 3.0

2005-07-08 Thread Leif K-Brooks
Kay Schluehr wrote:
> Well, I want to offer a more radical proposal: why not free squared
> braces from the burden of representing lists at all? It should be
> sufficient to write
> 
list()
> 
> list()

So then what would the expression list('foo') mean? Would it be
equivalent to ['foo'] (if so, how would you convert a string or other
iterable to a list under Py3k?), or would it be equivalent to ['f', 'o',
'o'] as it is in now (and is so, what gives?)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing list comprehensions in Python 3.0

2005-07-08 Thread Leif K-Brooks
Kay Schluehr wrote:
list.from_str("abc")
> 
> list("a", "b", "c" )


I assume we'll also have list.from_list, list.from_tuple,
list.from_genexp, list.from_xrange, etc.?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto

2005-07-18 Thread Leif K-Brooks
rbt wrote:
> IMO, most of the people who deride goto do so because they heard or read
> where someone else did. 

1  GOTO 17
2  mean,GOTO 5
3  couldGOTO 6
4  with GOTO 7
5  what GOTO 3
6  possibly GOTO 24
7  you! GOTO 21
8  that GOTO 18
9  really,  GOTO 23
10 understandable?
11 neat.GOTO 16
12 and  GOTO 25
13 are  GOTO 9
14 IGOTO 26
15 wrongGOTO 20
16 IGOTO 2
17 Yes, GOTO 14
18 simple   GOTO 12
19 agreeGOTO 4
20 with GOTO 22
21 GotosGOTO 13
22 somethingGOTO 8
23 really   GOTO 11
24 be   GOTO 15
25 easily   GOTO 10
26 totally  GOTO 19
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a query to the browser from time to time?

2005-07-19 Thread Leif K-Brooks
Admin wrote:
> I am creating a chat application like Messenger for the web (using the 
> browser) and I'm wondering if there is a way to receive new messages
> from  time to time from the server other than refreshing the page each 5
> sec.

Here's a pretty basic example I wrote a while ago using Twisted:
. The server keeps the
connection open and sends messages when they occur, with the side effect
of keeping the browser's page-loading indicator alive indefinitely.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web Framework Reviews

2005-07-19 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
>>Templating engines like ZPT prefer to put some code in the template,
>>Nevow prefers to put code in python and allow you to write some xhtml in
>>python too.
> 
> Oh yeah, now I remeber, I think this is a controversial idea.

One important thing to realise about Nevow is that it doesn't forbid you
from putting logic in the template, it simply doesn't encourage it.
There's nothing stopping you from writing render_while and render_if
methods for Nevow -- in fact, it would be quite easy. But once you
really understand Nevow and how it works, you realize that you don't
need to put logic in the template, because there's a better way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retaining an object

2005-08-09 Thread Leif K-Brooks
sysfault wrote:
> I'm using os.popen() to open that program via the syntax:
> os.popen('pidof var_name', 'r'), but as you know var_name is not
> expanded within single quotes,

os.popen('pidof %s' % var_name, 'r')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre error from help()

2005-08-09 Thread Leif K-Brooks
Roy Smith wrote:
> No, that works fine. But, now I can't even reproduce the error I reported 
> earlier (when I try, I get the help message as expected).  And, yes, that 
> was with a brand new interpreter session.  Strange.

Perhaps you were running Python from a directory with a file called
string.py?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sandboxes

2005-08-20 Thread Leif K-Brooks
42 wrote:
> I was wondering if it would be effective to pre-parse incoming scripts 
> and reject those containing "import"?

getattr(__builtins__, '__imp' + 'ort__')('dangerousmodule')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sandboxes

2005-08-22 Thread Leif K-Brooks
42 wrote:
> FWIW I've already given up on making python secure. I agree that odds 
> are extremely high that I've missed something. I'm just curious to see 
> what one of the holes I left is, preferably without wading through 
> hundreds of pages :)

f = [x for x in [].__class__.__bases__[0].__subclasses__() if
x.__name__=='file'][0]
f('/path/to/important/file', 'w').close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argument matching question

2005-08-25 Thread Leif K-Brooks
Learning Python wrote:
> A code like this:
> 
> def adder(**varargs):
>   sum=varargs[varargs.keys()[0]]
>   for next in varargs.keys()[1:]:
> sum=sum+varargs[next]
>   return sum
> 
> print adder( "first","second",'third')
> 
> How to pass arguments to a functions that use dictionary collection?

Like adder(foo="bar", bar="baz"), but I think you really want a function
like this:

def adder(*args):
sum = args[0]
for value in args[1:]:
sum += value
return sum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any projects to provide Javascript-style client-side browser access via Python?

2005-08-26 Thread Leif K-Brooks
Kenneth McDonald wrote:
> I'm curious about this because, quite aside their function as web 
> browsers, it is now possible to build some very useable interfaces 
> using browsers with HTML, CSS, and JavaScript. (The biggest problem  is
> still the lack of a decent text widget.) However, JavaScript isn't 
> really a good language for building complex applications, and it  would
> be very cool if there were some way to use Python to replace 
> client-side JavaScript, in order to gain access the DOM.

You could try Livepage, which is a part of Nevow . It
doesn't cut JavaScript completely out of the picture, but you could put
all of your real code in Python and only use JavaScript as a simple
layer to access the DOM.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute commands independantly

2005-09-06 Thread Leif K-Brooks
Mike Tammerman wrote:
> Hi,
> 
> I am trying to execute an executable or a pyton script inside my
> program. I looked at the subprocess and os module. But all the
> functions in these modules blocks my application.

subprocess doesn't block unless you call .wait():

from subprocess import Popen
proc = Popen('sleep 2; echo "Hello, world!"', shell=True)
print "In two seconds, something will happen."
proc.wait()
print "Did you see that?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Leif K-Brooks
Sybren Stuvel wrote:
> It also allows for dynamic function creation in cases where a name
> would not be available.

What cases are those?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generators and Decorators doing my head in ..

2005-09-06 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> Im trying to create a decorator that counts the number of times a
> function is run.

Your code doesn't work because decorators are run at function creation
time, not at function run time. Try this instead:


from itertools import count

def logFunctionCalls(function):
times = count()
def newfunction(*args, **kwargs):
print "Entering function:", function.__name__, times.next()
return function(*args, **kwargs)
newfunction.__doc__ = function.__doc__
newfunction.__name__ = function.__name__
return newfunction

@logFunctionCalls
def doWork():
print "Doing work..."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading the last line of a file

2005-09-08 Thread Leif K-Brooks
Xah Lee wrote:
> i switched to system call with tail because originally i was using a
> pure Python solution
> 
>  inF = gzip.GzipFile(ff, 'rb');
>  s=inF.readlines()
>  inF.close()
>  last_line=s[-1]
> 
> and since the log file is 100 megabytes it takes a long time and hogs
> massive memory.

How about:

inF = gzip.GzipFile(ff, 'rb')
for line in inF:
pass
last_line = line

It's a bit slower than gzip and tail, but the memory usage is fine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to dynamicly define function and call the function?

2005-09-08 Thread Leif K-Brooks
FAN wrote:
> class test:
> def __init__(self):
> exec("def dfunc(msg):\n\tprint msg\nprint 'exec def function'")
> dfunc('Msg in init ...')   #  it work
>   
> def show(self, msg):
>  dfunc(msg) # doesn't work !
>  exec('dfunc(msg)')  # doesn't work too!

class Test(object):
def __init__(self):
exec "def dfunc(msg):\n print msg"
dfunc('Hello from __init__.')
self.dfunc = dfunc

def show(self, msg):
self.dfunc(msg)


(Of course, this is assuming your real function is more complicated than
the one you've posted; if it isn't, you don't need to use exec to define
it.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using % operator to print possibly unitialized data attributes

2005-09-09 Thread Leif K-Brooks
Adam Monsen wrote:
> class J:
> name = ''
> value = ''
> def __str__(self):
> vals = self.__class__.__dict__
> vals.update(self.__dict__)
> return 'name="%(name)s" value="%(value)s' % vals

This will update the class's attributes with instance attributes when
str() is called, which probably isn't what you want. For instance:

 >>> foo = J()
 >>> foo.name = "Joe Bloggs"
 >>> print foo
 name="Joe Bloggs" value="
 >>> bar = J()
 >>> print bar
 name="Joe Bloggs" value="

What's wrong with the obvious version:

class J(object):
name = ''
value = ''
def __str__(self):
return 'name=%r value=%r' % (self.name, self.value)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute commands and return output

2005-09-10 Thread Leif K-Brooks
billiejoex wrote:
> Hi all. I'm searching for a portable (working on *nix and win32) function 
> that executes a system command and encapsulate its output into a string.
> Searching for the web I found this:
> 
> os.popen('command').read()
> 
> It is perfect but when che command return an error the funciotn returns an 
> empy string.
> Does it is possible to return stdout and stderr too?

Use subprocess:

from subprocess import Popen, PIPE
proc = Popen(['command', 'arg', 'arg'], stdout=PIPE, stderr=PIPE)
return_code = proc.wait()
if return_code == 0:
print "Success:\n%s" % proc.stdout.read()
else:
print "Failure %s:\n%s" % (return_code, proc.stderr.read())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute commands and return output

2005-09-10 Thread Leif K-Brooks
billiejoex wrote:
> Thank you for your help but I'm searching a different way.
> Moreover it doesn't work always (for exaple: try a 'dir' command).
> Because of I'm implementing a remote shell  the 
> [[os.popen('command').read()]] rapresents the best for me because it can 
> also accepts arguments direclty  (for example: 
> os.popen('netstat -a -n -o').read() and this is a great advantage.

If you really need shell evaluation, try subprocess.Popen('foo',
shell=True) instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: why are LAMP sites slow?

2005-02-06 Thread Leif K-Brooks
Paul Rubin wrote:
I notice that lots of the medium-largish sites (from hobbyist BBS's to
sites like Slashdot, Wikipedia, etc.)  built using this approach are
painfully slow even using seriously powerful server hardware.  Yet
compared to a really large site like Ebay or Hotmail (to say nothing
of Google), the traffic levels on those sites is just chickenfeed.
To some extent, I would say it has to do with the servers being used. 
Slashdot has only 10 servers [1], while Wikipedia has only 39 [2]; 
Hotmail, on the other hand, has around 3500 [3].

A better comparison to Hotmail is the high-traffic Web site Neopets, 
which has around 200 servers [4] and uses Linux, Oracle, MySQL (for a 
few parts of the site), Apache, and PHP.

[1] 
[2] 
[3] 
[4] Estimated by counting the name of wwwXXX.neopets.com domain names 
(238). Neopets probably has at least 300 servers if you include non-Web 
servers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: trolltech comitment

2005-02-08 Thread Leif K-Brooks
Gabriel B. wrote:
What it they revoke this license [on Qt]?
They can't. It's the GPL.
what it windows
longhorn has a non-backwardcompatible GDI API and a newer version of
Qt must be used, and that newer version does not have a gpl version?
What if Wx does that? What if Tk does? What if GTK does?
If i'm going to commit to something, i like to know the lengths the
other side gona commit also.
They have: they're licensing Qt to you under an _irrevocable_ license, 
the GPL. If that's not a commitment, nothing is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with `is not None`?

2005-02-08 Thread Leif K-Brooks
Frans Englich wrote:
runner.py:587: Using is not None, may not always work
It's a PyChecker bug relating to None being a constant in 2.4: 
.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [NooB] a Variable in multiple quotes...

2005-02-13 Thread Leif K-Brooks
administrata wrote:
Is it possible? 

I tried...
I = "John"
print \
"""
I used to love pizza"""
Error occurs!!!
No error occurs; it prints "I used to love pizza", as would be expected.
Oh: from the subject line, I'm guessing that you want it to say "John 
used to love pizza" instead? In that case, try doing this:

I = "John"
print "%s used to love pizza" % I
--
http://mail.python.org/mailman/listinfo/python-list


Re: multi threading in multi processor (computer)

2005-02-14 Thread Leif K-Brooks
Irmen de Jong wrote:
the GIL must die.
I couldn't resist:
http://www.razorvine.net/img/GIL.jpg
Neither could I:
http://ecritters.biz/diegil.png
(In case it's not entirely obvious, the stick figure just slices the GIL 
into two pieces with his sword, causing its blood to splatter on the wall.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos?

2005-02-17 Thread Leif B. Kristensen
john san skrev:

> pure DOS, old pc, used for teaching . want show some "windows" under
> DOS (under Python).

curses is a text-based interface that will let you build windowed
applications like you could with the crt unit in Turbo Pascal of those
golden days. I've no idea if anyone's compiled it for the 16-bits DOS
platform, though.
-- 
Leif Biberg Kristensen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos?

2005-02-17 Thread Leif B. Kristensen
john san skrev:

> Actually the "windows" running very good under the xbox-NTOS via
> xboxmediacenter. its just limited functions(not easy to programming
> the "windows" prog.), if we can find WxPython-like can be ported (I
> can import *
> from it  to my xboxPython) )it will be a great great . You
> will have HD screen and web surfing on HDTV and computing on HDTV.
> think about it! That is a real thing the python-like lang. should to
> do otherwise just a garbage(toy).

You can run Linux with MythTV on an XBox. Does all the things you want,
and of course it will run WxPython.
-- 
Leif Biberg Kristensen

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


Re: Why doesn't join() call str() on its arguments?

2005-02-17 Thread Leif K-Brooks
Leo Breebaart wrote:
What I can't find an explanation for is why str.join() doesn't
automatically call str() on its arguments
I don't really like that idea for the reasons others have stated. But a 
related and (IMHO) more Pythonic idea would be to allow arbitrary 
objects to be str.join()ed if they use __radd__ to allow concatenation 
with strings. This would be consistent with how the + operator behaves:

Python 2.4 (#2, Jan  8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... def __radd__(self, other):
... if isinstance(other, basestring):
... return other + str(self)
... def __str__(self):
... return 'Foo()'
...
>>> 'foo:' + Foo()
'foo:Foo()'
>>> ''.join(['foo', Foo()])
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sequence item 1: expected string, Foo found
--
http://mail.python.org/mailman/listinfo/python-list


Curses and Terminal DEC

2005-02-17 Thread Leif B. Kristensen
I'm playing a little with curses (okay, call me a masochist) and have
found a small gotcha. When I do eg. a screen = stdscr.subwin(10,20,0,0)
and then a screen.border(), I end up with an ugly border where the
right side is seriously misaligned. 

I've figured out the reason: I love the Terminal DEC font in Linux, and
have set it as my preferred font in the KDE Konsole. When I switch to
the default font, everything looks dandy. But is there a way to get a
nice border with the Terminal DEC font?
-- 
Leif Biberg Kristensen

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


Re: Accessing files installed with distutils

2005-02-22 Thread Leif K-Brooks
Frans Englich wrote:
This is silly. How do I access data files I've installed with distutils? In a 
portable, generic way, I want to find out what is the following path on most 
systems:

/usr/local/lib/python2.4/lib/site-packages/foo/bar.txt
Assuming your module is also in site-packages/foo, I would use:
import os
filename = os.path.join(os.path.dirname(__file__), 'bar.txt')
--
http://mail.python.org/mailman/listinfo/python-list


Re: python tutorial/projects

2005-02-22 Thread Leif B. Kristensen
Danny skrev:

> Does anyone know of a good python tutorial?
> I was also looking for some non-trivial projects to do in python.
 
There's a lot of projects on Sourceforge that are written in Python,
where you're free to study the code and maybe participate, if you've
got what it takes.
 
> Basically I would like to claim on my resume, that I know python, with
> out bad karma.

Your stance is a difficult one, and one that is hard to conciliate with
the Zen of Hacking. Search for enlightenment first, my son, and the
rest will be given to you freely.
-- 
Leif Biberg Kristensen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a shell command from a python program

2005-02-23 Thread Leif B. Kristensen
Sandman wrote:

> How would I run a shell command in Python?
> 
> Here is what I want to do:
> I want to run a shell command that outputs some stuff, save it into a
> list and do stuff with the contents of that list.

There's a Python Cookbook example that should fit nicely with what
you're trying to do here:

<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296>
-- 
Leif Biberg Kristensen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On eval and its substitution of globals

2005-02-23 Thread Leif K-Brooks
Paddy wrote:
I had to do as you suggest but I was thinking either it was a kludge,
 and there should be a 'deep' substitution of globals, or that there
was a good reason for it to work as it does and some magician would
tell me.
If there was deep substitution of globals, how would functions imported 
from different modules behave? Consider this:

--- foo.py ---
from bar import func
data = 24
print func()
print eval('func()', globals(), locals())
--- bar.py ---
data = 42
def func():
return data

If globals were deeply substituted when using eval, the program would 
presumably print "42\n24", which would be far from intuitive. If you 
limit the deep substitution to functions in the same module, you're 
creating a confusing special case.
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-02-26 Thread Leif K-Brooks
Xah Lee wrote:
lambda x, y: x + y
that's what i was looking for.
... once i have a lambda expr, how to apply it to arguments?
http://python.org/doc/current/ref/calls.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help running external program

2005-02-27 Thread Leif B. Kristensen
I'm using wget from Python to get extactly one line from a reports page.
I made this function that works for me:

def wgetline(exp):  # see Python Cookbook p. 228
print "Getting result from server ..."
command = 'wget -q -O - \
http://www.foobar.com/report.pl\?UserID=xxx\&UserPW=xxx \
| grep ' + exp
child = os.popen(command)
data = child.read()
return data

I had to escape the ? and & in the url, or the CGI script at the other
end would refuse to cooperate with "Invalid UserID or UserPW".
-- 
Leif Biberg Kristensen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GOTO (was Re: Appeal for python developers)

2005-03-05 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
Goto is useful [...] when there is a clean-up section of a function
that should be executed for various error conditions.
Like this?
def foo():
f = open('foo.txt')
try:
# do stuff with f
finally:
f.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-03-06 Thread Leif K-Brooks
Xah Lee wrote:
if i understand correctly, forms such as
(lambda x,y:x+y)(a,b)
can only be gained thru experience? and not documented directly
anywhere in the official docs?
The official documentation can't list every possible permutation of the 
various syntactic constructs. It does explain parenthesis, the lambda 
expression, and calling syntax; the particular combination of the three 
that you're using can therefor be logically understood from the docs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IndexedCatalog and ZEO

2005-03-06 Thread Leif K-Brooks
Almad wrote:
Hello, 

I'm trying to use IndexedCatalog
[http://www.async.com.br/projects/IndexedCatalog/] in my CherryPy
[http://www.cherrypy.org] application. 
As Zodb support access just from one Python thread, I must either use just
one CherryPy thread (slow), or use ZEO. However, if I understand it good,
when I use 
from ZEO import ClientStorage

then ZEO is internally using FileStorage, so no IndexedCatalog is used. 
If you're using IndexedCatalog's Shelf class, just pass it a host/port 
tuple instead of a path:

from IndexedCatalog.Shelf import Shelf
shelf = Shelf(('localhost', 1234), [Class1, Class2])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wishlist item: itertools.flatten

2005-03-14 Thread Leif K-Brooks
Michael Spencer wrote:
if hasattr(item,"__iter__"): # Avoids iterating over strings
That's probably the cleanest way to avoid strings, but it's 
unfortunately not a good idea IMHO. Many objects (IndexedCatalog's 
Result objects are what I'm concerned about, but there are undoubtedly 
others) still rely entirely on the old-style sequence iteration protocol 
even though they're proper containers, so checking for __iter__ wouldn't 
work on them.  Explicitly doing isinstance(item, basestring) is probably 
the best option until older objects move to the new iteration protocol.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Licensing Python code under the Python license

2005-03-14 Thread Leif K-Brooks
Harlin Seritt wrote:
If this is for making money, make it either a proprietary license or
BSD.
If you're giving it away and expect nothing for it except maybe fame,
do GPL.
You're kidding, right? How does the BSD license possibly offer more 
protection for a commercial program than the GPL does?
--
http://mail.python.org/mailman/listinfo/python-list


Re: __getitem__ method on (meta)classes

2005-03-14 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
Why doesn't this work?

def foo(lst):
...   class baz(object):
... def __getitem__(cls, idx): return cls.lst[idx]
... __getitem__=classmethod(__getitem__)
...   baz.lst = lst
...   return baz
...
I thought x[y] and x.__getitem__(y) were supposed to always be
synonymous.
No, with new-style classes, x[y] and type(x).__getitem__(y) are 
synonymous. This works:

>>> def foo(lst):
...  class bar(type):
...   def __getitem__(self, index):
...return self.lst[index]
...  class baz(object):
...   __metaclass__ = bar
...  baz.lst = lst
...  return baz
...
>>> foo([1,2,3])[0]
1
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode converting

2005-03-15 Thread Leif K-Brooks
Maxim Kasimov wrote:
Diez B. Roggisch wrote:
Maxim Kasimov wrote:

there are a few questions i can find answer in manual:
1. how to define which is internal encoding of python unicode strings
(UTF-8, UTF-16 ...) 
It shouldn't be your concern - but you can specify it using " ./configure
--enable-unicode=ucs2" or --enable-unicode=ucs4. You can't set it to 
utf-8
or utf-16.
is that means that python internal unicode format is ucs2 or ucs4?
i'm concerning with the qustion because i need to send data to external
application in ucs2 encoding
The internal format Python stores Unicode strings in is an 
implementation detail; it has nothing to do with how you send data. To 
do that, you encode your string into a suitable encoding:

>>> s = u"Some Unicode text."
>>> s
u'Some Unicode text.'
>>> s.encode('utf-16')
'\xff\xfeS\x00o\x00m\x00e\x00 \x00U\x00n\x00i\x00c\x00o\x00d\x00e\x00 
\x00t\x00e\x00x\x00t\x00.\x00'
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterable terminology (for language lawyers)

2005-03-16 Thread Leif K-Brooks
Michele Simionato wrote:
According to the standand library 
(http://docs.python.org/lib/typeiter.html) an *iterable* is something
with an __iter__ method. This means that strings are *not* iterable.
In general, the definitions people in the Python community tend to use are:
Iterable: An object which doesn't raise TypeError when passed to iter().
Reiterable: An object which can be passed to iter() multiple times 
without returning itself.
Iterator: An object which defines a next() method and returns itself 
when passed to iter().
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >