Re: self.__dict__ tricks

2009-10-30 Thread Steven D'Aprano
On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:

> Steven D'Aprano  writes:
> 
>> On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
>> > class formLoader():
>>
>> Idiomatic Python is to use CamelCase for classes.
> 
> Or rather: Instead of camelCase names, idiomatic Python is to use
> TitleCase names.

Thank you for the correction. I always mix up those two.


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


Re: How to run a repeating timer every n minutes?

2009-10-30 Thread Frank Millman
Diez B. Roggisch wrote:
> mk wrote:
>
>>
>> I'm newbie at threading, so I'm actually asking: should not method like
>> stop() be surrounded with acquire() and release() of some threading.lock?
>>
>> I mean, is this safe to update running thread's data from the main
>> thread without lock?
>
> stop() is part of the Timer-interface, and tas it's not mentioned to be
> unsafe in the docs you can just call it. It might be that it internally
> calls some threadsafe means of communication (Event, Lock).
>

Thought I should jump in here to avoid any confusion.

mk is referring to the Timer class that I included in my reply to the OP. It 
is different from the Timer class in the threading module. I had not 
realised that I was duplicating an existing name - sorry about that.

The standard Timer class has a method called cancel(). I am sure that Diez's 
comments above will apply to this.

I included a method called stop() in my Timer class, and I think it is to 
this that mk is referring.

The method looks like this -

def stop(self):
self.event.set()

Is this threadsafe? I would have thought the answer is yes, but I am no 
expert. Perhaps someone else can confirm.

Thanks

Frank Millman



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


Re: Modify dict/set during iteration?

2009-10-30 Thread Steven D'Aprano
On Thu, 29 Oct 2009 21:14:22 -0700, metal wrote:

> Maybe my real goal is the following:
> 
> def miter(iterable):
>   for x in tuple(iterable):
>   if x in iterable:
>   yield x


I don't think that does what you think it does. For some iterables it 
doesn't do anything at all:

>>> it = iter([1,2,3])
>>> for item in miter(it):
... print item
...
>>>

and for others it is redundant:

>>> it = [1,2,3]
>>> for item in miter(it):  # same as `for item in it:`
... print item
...
1
2
3
>>> 


Could you explain what you are trying to accomplish?



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


spring effect in Python

2009-10-30 Thread pochis40
I'm trying to write in Python something similar to this:
(Java)
http://java.sun.com/applets/jdk/1.4/demo/applets/GraphLayout/example1.html
or these:
(Proce55ing)
http://www.cricketschirping.com/processing/ExportAtlas/
or
http://www.cricketschirping.com/weblog/2005/12/11/force-directed-graph-layout-with-proce55ing/
or
http://www.cricketschirping.com/weblog/2007/02/26/force-directed-graph-layout-with-processing-take-2/

I've problem to find something that give that physical effect (like a
spring).

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


Re: ImportError: No module named _md5 - Please help

2009-10-30 Thread wadi wadi
Thanks Robert for defending me :)

On 10/29/09, Robert Kern  wrote:
> On 2009-10-29 11:28 AM, Sean DiZazzo wrote:
>> On Oct 29, 8:49 am, wadi wadi  wrote:
>>> I can't alter the import statement as the error log is pointing to one
>>> of the installed python files 'hashlib.py'
>>>
>>> /python/2.6.2/lib/python2.6/hashlib.py
>>>
>>> and I don't have the right permissions to alter the python installation.
>>> Any idea?
>
>> You are being vague and confusing.  There is no default "_md5" python
>> library in the standard library.  You should be either using "import
>> md5" (deprecated) or "import hashlib".  Unless perhaps the code you
>> show is from inside one of those libraries, and there is a _md5.so
>> that it uses but cant find.  Not sure about that.
>>
>> Did you write the code above?  Or did you find it inside another
>> file?  If you found it inside another file what is the file?
>
> He's saying that he found that import in hashlib.py . He tried "import
> hashlib"
> (or something that tried "import hashlib"), and it gave him a traceback
> showing
> that the statement "import _md5" was the one that actually the root cause of
> the
> failure.
>
>> If you still have questions, I have another approach.  Please cover
>> your palm and fingers with a thick layer of black ink (making sure to
>> cover your entire hand).  Press your hand down firmly on a piece of
>> bright white paper.  Allow the ink to dry.  Finally, scan the page and
>> post it here.  I will attempt to read your palm to find the answer.
>
> That's uncalled for. He's been reasonably clear. The error in understanding
> is
> all on your end.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it
> had
>   an underlying truth."
>-- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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


Re: ftpilb.FTP.stor...() freeze mystery

2009-10-30 Thread Anthra Norell

Gabriel Genellina wrote:
En Thu, 29 Oct 2009 13:18:30 -0300, Anthra Norell 
 escribió:



Gabriel Genellina wrote:
En Wed, 28 Oct 2009 08:05:22 -0300, Anthra Norell 
 escribió:

Gabriel Genellina wrote:

En Tue, 27 Oct 2009 07:53:36 -0300, Anthra Norell
 escribió:

I am trying to upload a bunch of web pages to a hosting 
service.[...]  I wrote a loop that iterates through the file 
names and calls either of the stor... () methods as appropriate. 
The loop successfully uploads eight of some twenty files and then 
freezes. Ctrl-C doesn't unlock the freeze. I have to kill the 
IDLE window


freezes are less predictable than it seemed in the beginning. On 
one occasion it occurred after the transfer of a single file from 
the IDLE command line (my_ftp_object.storlines ("STOR file_name", 
f). The file did upload. So the freezes seem to occur after a 
successful transfer.


In this thread from last month, Sean DiZazzo shows how to add a 
timeout parameter to storbinary:

http://comments.gmane.org/gmane.comp.python.general/639258
Do the same with storlines and see whether it helps.

Thanks a million! Here's a way out by the look of it. As the devil is 
in the details I get an error that indicates an inconsistency in my 
ftplib library (2.4) (*** marks my comments):


Traceback (most recent call last):
 File "", line 1, in -toplevel-
   d2jm = upload.run (1)
 File "I:/DOK/projects/WEB/JM\upload.py", line 369, in run
   D2JM.copy_1_2 (do)
 File "I:/DOK/projects/WEB/JM\upload.py", line 342, in copy_1_2
   try: self.FS2.storbinary ('STOR %s' % name, f, timeout = 
timeout)   *** Here's the call to the overwritten method with the 
timeout.

 File "I:/DOK/projects/WEB/JM\upload.py", line 440, in storbinary
   self.connection = self.transfercmd (command)   *** command is 
'STOR (target file name)'. Control passes to ftplib

 File "C:\PYTHON24\lib\ftplib.py", line 345, in transfercmd
   return self.ntransfercmd(cmd, rest)[0]
 File "C:\PYTHON24\lib\ftplib.py", line 321, in ntransfercmd
   host, port = self.makepasv()
 File "C:\PYTHON24\lib\ftplib.py", line 299, in makepasv
   host, port = parse227(self.sendcmd('PASV'))
 File "C:\PYTHON24\lib\ftplib.py", line 566, in parse227
   raise error_reply, resp
error_reply: 200 TYPE is now 8-bit binary   <*** 'is now' indicates 
something has changed resulting in an inconsistency


Is 'resp' supposed to be an int (227) rather than a string ('227')? 
Probably a wrong conclusion. In version 2.5 it is still a string. 
Anyway, I can't start editing the library trial-and-error style. So, 
I do thank you for the push. Mores pushes will be greatly 
appreciated, but I hesitate to invite travel companions for a stroll 
into this wilderness.


resp is a string, but not the response that PASV expected; apparently 
the server is sending some unexpected responses.  r52739 seems to fix 
that. Perhaps you should upgrade to a newer Python version.


http://svn.python.org/view?view=rev&revision=52739



I know I should upgrade.That I shall do next. Not today, though. First I 
need a new computer, because my OS (Windows ME) is so outdated that 
installations fail with the recommendation to upgrade to a newer 
installer. Anyway, I do thank you very much for your assistance. With 
the r52739 fix I should be okay.


Regards

Frederic

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


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-30 Thread Bruno Desthuilliers

metal a écrit :

The actual situation is I'm coding with a immuable set-like datatype
XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax']


I assume it was '==', not '='


if I
declare ax is consists of al and ah

"That" means I can't explian it very well 'cause my english...

Now I try to make some mess like this...I know it's not good to wrap
all methods...I just try to make code looks good

class MyMeta(type):
def __init__(cls, name, bases, namespace):
type.__init__(cls, name, bases, namespace) # needed?
cls.wrap_methods()
def methods(cls):
return [k for k, v in cls.__dict__.items() if callable(v)]


All callables are not functions or methods... The inspect module might 
help you here.



def wrap_methods(cls):
for k in cls.methods():
f = cls.__dict__[k]



Just for the record, you wouldn't have to do this lookup if .methods 
returned the actual objects instead of their names) if callable(v)).




def g(self, *v, **k):
rv = f(self, *v, **k)
if rv.__class__ is cls:
rv = self.__class__()
rv.__dict__.update(self.__dict__)
return rv
setattr(cls, k, g)




If you do have control over the whole class hierarchy, just write the 
base class so the alternate constructors return instances of the 
appropriate class. Else, manually wrapping the relevant methods would be 
a better solution IMHO. I'm not for premature optimization, but remember 
that method lookup and function call are two costly operations in 
Python, so better not adding too much overhead.

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


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-30 Thread Bruno Desthuilliers

metal a écrit :

Consider the following:


(snip)

class Parent:
def some_method(self):
return Parent(...)
class Child:
pass

Child().some_method() returns a Parent instance.


It actually raises an AttributeError. You forgot to make Child inherit 
from Parent.




We can rewrite Parent like this to avoid that


class Parent:
def some_method(self):
return self.__class__(...)
class Child:
def some_method(self):
...
return Parent.some_method(self)


But this style makes code full with ugly  self.__class__

Any standard/pythonic way out there?


Others already gave you the appropriate answer (if appliable, of 
course), which is to make some_method a classmethod, or, if some_method 
needs to stay an instancemethod, to factor out the creation of a new 
instance to a classmethod.


Now if it's the self.__class__ that hurts you, you can as well replace 
it with type(self) - assuming you make Parent a new-style class (which 
FWIW is the sensible thing to do anyway).

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-30 Thread Bruno Desthuilliers

Robert Kern a écrit :

On 2009-10-29 16:52 PM, Aahz wrote:

(snip)

Coincidentally, I tried PyFlakes yesterday and was unimpressed with the
way it doesn't work with "import *".


I consider "import *" the first error to be fixed, so it doesn't bother 
me much. :-)



+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-30 Thread metal
On 10月30日, 上午8时03分, metal  wrote:
> The actual situation is I'm coding with a immuable set-like datatype
> XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax'] if I
> declare ax is consists of al and ah
>

A typo,  XSet(['al']) | XSet(['ah'] = XSet(['ax']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: '11' + '1' is '111'?

2009-10-30 Thread Ben Finney
metal  writes:

> '11' + '1' == '111' is well known.
>
> but it suprises me '11'+'1' IS '111'.

Don't be surprised. Rather, don't depend on implementation-dependent
behaviour, such as whether two objects that compare equal will or will
not have the same identity.

That behaviour is permitted to differ based on which Python
implementation, which specific value, or even which phase the moon is
currently in.

Use ‘is’ when you want to compare identity. Use ‘==’ when you want to
compare equality. Use more thinking time when you don't yet know which
one you want.

-- 
 \  “The fact that I have no remedy for all the sorrows of the |
  `\ world is no reason for my accepting yours. It simply supports |
_o__)  the strong probability that yours is a fake.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension problem

2009-10-30 Thread Ben Finney
(Please preserve attribution lines when you quote someone, so we can
keep track of who said what in the developing discussion.)

Nick Stinemates  writes:

> > Some objects are singletons, ie there's only ever one of them. The
> > most common singleton is None. In virtually every other case you
> > should be using "==" and "!=".
>
> Please correct me if I am wrong, but I believe you meant to say some
> objects are immutable, in which case you would be correct.

No, I believe the person to whom you are responding meant specifically
to talk about singletons; what they said is correct.

Objects can be equal but not identical. This is true whether or not
those objects are of an immutable type.

-- 
 \   “Prediction is very difficult, especially of the future.” |
  `\   —Niels Bohr |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: self.__dict__ tricks

2009-10-30 Thread Ben Finney
Steven D'Aprano  writes:

> On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
> > class formLoader():
>
> Idiomatic Python is to use CamelCase for classes.

Or rather: Instead of camelCase names, idiomatic Python is to use
TitleCase names.

-- 
 \ “We are not gonna be great; we are not gonna be amazing; we are |
  `\   gonna be *amazingly* amazing!” —Zaphod Beeblebrox, _The |
_o__)Hitch-Hiker's Guide To The Galaxy_, Douglas Adams |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


import problem in tkinter

2009-10-30 Thread Jebegnana das
import _tkinter # If this fails your Python may not be configured for Tk

I'm using python3 in linux. In windows tkinter is working fine but in
mandriva linux spring 2009 it fails to import. Can you please tell me
step-by-step on how to fix this issue? In python3.1 home page the
description is not clear or it can't be understood by the beginner. As
i'm a beginner for programming python in linux please help me out. I
want to know what is the thing i missed during installation. I've done
the things correctly as mentioned in the python readme text inside the
python3.1 tarball file. While searching the net i found out that if i
want to fix this issue i've to uninstall and install it again. what
should i do now?

With Regards,
Jebagnana Das.A,
Mob : +91-9843828383





  Now, send attachments up to 25MB with Yahoo! India Mail. Learn how. 
http://in.overview.mail.yahoo.com/photos-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-30 Thread metal
On 10月30日, 下午4时44分, Bruno Desthuilliers  wrote:
> metal a écrit :
>
> > The actual situation is I'm coding with a immuable set-like datatype
> > XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax']
>
> I assume it was '==', not '='
>
> > if I
> > declare ax is consists of al and ah
>
> > "That" means I can't explian it very well 'cause my english...
>
> > Now I try to make some mess like this...I know it's not good to wrap
> > all methods...I just try to make code looks good
>
> > class MyMeta(type):
> >     def __init__(cls, name, bases, namespace):
> >         type.__init__(cls, name, bases, namespace) # needed?
> >         cls.wrap_methods()
> >     def methods(cls):
> >         return [k for k, v in cls.__dict__.items() if callable(v)]
>
> All callables are not functions or methods... The inspect module might
> help you here.
>
> >     def wrap_methods(cls):
> >         for k in cls.methods():
> >             f = cls.__dict__[k]
>
> Just for the record, you wouldn't have to do this lookup if .methods
> returned the actual objects instead of their names) if callable(v)).
>
> >             def g(self, *v, **k):
> >                 rv = f(self, *v, **k)
> >                 if rv.__class__ is cls:
> >                     rv = self.__class__()
> >                     rv.__dict__.update(self.__dict__)
> >                 return rv
> >             setattr(cls, k, g)
>
> If you do have control over the whole class hierarchy, just write the
> base class so the alternate constructors return instances of the
> appropriate class. Else, manually wrapping the relevant methods would be
> a better solution IMHO. I'm not for premature optimization, but remember
> that method lookup and function call are two costly operations in
> Python, so better not adding too much overhead.

All code are just POCs. == or = doesn't matter :)

Sure I know .methods() can return actual objects if ONLY iteration,
but how to overwrite it?

type(self) in new-style class looks a little better, thanks for the
idea
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-30 Thread Bruno Desthuilliers

metal a écrit :

On 10月30日, 下午4时44分, Bruno Desthuilliers  wrote:

metal a écrit :

(snip)

def methods(cls):
return [k for k, v in cls.__dict__.items() if callable(v)]

All callables are not functions or methods... The inspect module might
help you here.


def wrap_methods(cls):
for k in cls.methods():
f = cls.__dict__[k]

Just for the record, you wouldn't have to do this lookup if .methods
returned the actual objects instead of their names) 




Sure I know .methods() can return actual objects if ONLY iteration,
but how to overwrite it?


Ahem...  yes, right, you do need the key too. But you still can 
avoid the extra dict lookup : just return both the key and object !-)



type(self) in new-style class looks a little better, thanks for the
idea


FWIW and as a general rule, __special_names__ are mostly implementation 
support for operator or operator-like generic functions, and not 
intented for direct access (except when you really need it of course).

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


Re: Python 2.6 Global Variables

2009-10-30 Thread Bruno Desthuilliers

AK Eric a écrit :

2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.


Isn't that __main__?


Nope



import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.


This won't make 'foo' available to other imported modules. Still a 
module-level name, and still no "true" global namespace - which FWIW is 
a VeryGoodThing(tm).

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


Re: Python 2.6 Global Variables

2009-10-30 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :

AK Eric a écrit :

2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.


Isn't that __main__?


Nope



import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.


This won't make 'foo' available to other imported modules.


Err, reading Steven and Gabriel's posts, it looks like I'm wrong and 
your right. Duh :(


You really shouldn't show this to childrens.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread bartc


"Alf P. Steinbach"  wrote in message 
news:hcdlsp$9a...@news.eternal-september.org...

* bartc:


"Alf P. Steinbach"  wrote in message 
news:hc8pn3$dd...@news.eternal-september.org...

[Cross-posted comp.programming and comp.lang.python]


You use the highly commercial-looking activatestate website; what's wrong 
with www.python.org?


I guess "commercial looking" is something negative.

Please note regarding the question: I'm not a telepath. I don't know what 
you think is wrong with [www.python.org].


python.org seems to be the main site. Google "python download" and that is 
the first hit.


Their windows download seems to be 13MB against the 32MB of activestate, and 
the IDE provided seems more advanced that the 'console window' you have in 
your tutorial. I'm just asking why your chose one over the other...


And I have no interest in evaluating the site for you, at least not unless 
you pay me for that job.


...but if that answer is going to cost me money, then forget it. I think 
that statement just answered it.


You say elsewhere that you're not specifically teaching Python, but the 
text is full of technical details specific to both Python


Yes. A programming language is required to do programming. Can't do 
without it, sorry.


You make it sound complicated however.

--
bartc 


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


Re: Are *.pyd's universal?

2009-10-30 Thread Carl Banks
On Oct 29, 9:10 pm, Lawrence D'Oliveiro  wrote:
> In message , Christian
>
> Heimes wrote:
> > Lawrence D'Oliveiro schrieb:
>
> >> In message ,
> >> Christian Heimes wrote:
>
> >>> On Linux and several other Unices the suffix is .so and not .pyd.
>
> >> Why is that? Or conversely, why isn't it .dll under Windows?
>
> > On Windows it used to be .dll, too.
> > The suffix was changed to avoid issues with other dlls and name clashes.
>
> What clashes? How come other OSes don't seem prone to the same problems?

Yeah, because who ever heard of one OS having a problem that another
OS didn't?

Windows searches for DLLs on the executable path, which always
includes the current directory.  So if you have a module called
system32.dll in your currently directory, you could be in big trouble.

Unix doesn't automatically search the current dir, doesn't use the
executable search path (libraries have their own search path, which is
not used when loading shared libs by hand), and system libraries on
Unix conventionally are prefixed by lib.  So name collisions are rare,
but even if if you have a module called libc.so in your current
directory it will not conflict with /lib/libc.so.


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


Re: What IDE has good git and python support?

2009-10-30 Thread Bruno Desthuilliers

Aweks a écrit :

what do you use?


bash + emacs
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Bruno Desthuilliers

Alf P. Steinbach a écrit :
(snip)

Microsoft's 
own Windows Explorer, the main GUI shell for Windows, which presumably 
was made by the best programmers available


Mouarf !!!

+1 JOFY (=> Joke Of The Year)



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


Sqlite3. Substitution of names in query.

2009-10-30 Thread Lacrima
Hello!

I use sqlite3 module for my sqlite database. I am trying to substitute
table name in sql query.

>>> import sqlite3
>>> con = sqlite3.connect('mydb')
>>> cur = con.execute("select * from table where name='Joe'")
That's ok

>>> cur = con.execute("select * from table where name=?", ('Joe',))
That's ok too

>>> cur = con.execute("select * from ? where name=?", ('table', 'Joe'))
Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near "?": syntax error

So what's wrong now?
Is it impossible to substitute table names, using DB API?
If so, what is a way to make table name substitutions? Are string
operations like
'select * from %s where...' % tablename
ok in this case?

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


Re: What IDE has good git and python support?

2009-10-30 Thread Ben Finney
Bruno Desthuilliers  writes:

> Aweks a écrit :
> > what do you use?
>
> bash + emacs

Yes, Bash and the toolkit provided by the GNU operating system are an
excellent integrated development environment (IDE).

Emacs has a ‘vc’ mode, and Git provides an Emacs module to support Git
in ‘vc’. It will then work the same as any other VCS supported by Emacs.

Learn to use the GNU operating system, and a powerful free-software
mature programmable text editor (Emacs or Vim), and you have an IDE that
works for any popular programming language.

-- 
 \ “Oh, I realize it's a penny here and a penny there, but look at |
  `\  me: I've worked myself up from nothing to a state of extreme |
_o__)  poverty.” —Groucho Marx |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sqlite3. Substitution of names in query.

2009-10-30 Thread Diez B. Roggisch

Lacrima schrieb:

Hello!

I use sqlite3 module for my sqlite database. I am trying to substitute
table name in sql query.


import sqlite3
con = sqlite3.connect('mydb')
cur = con.execute("select * from table where name='Joe'")

That's ok


cur = con.execute("select * from table where name=?", ('Joe',))

That's ok too


cur = con.execute("select * from ? where name=?", ('table', 'Joe'))

Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near "?": syntax error

So what's wrong now?
Is it impossible to substitute table names, using DB API?


Yes, it is. How should the api discern that you meant the tabe-name 
(which gets passed without quotes, or if so with double-quotes) instead 
of a string-literal? There *could* be means to do so, but in the end all 
this boils down to crossing a border that better is left alone - because 
there are many problems of sql injection lurking if you are basing your 
tablenames/columns on *input*.



If so, what is a way to make table name substitutions? Are string
operations like
'select * from %s where...' % tablename
ok in this case?


By substituting it with simple string-interpolation. Or even better, by 
not doing it at all - because usually, your datamodel is tied to your 
program, so the need for this kind of dynamicity shouldn't arise in the 
first place.


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


Re: spring effect in Python

2009-10-30 Thread Lie Ryan

pochis40 wrote:

I'm trying to write in Python something similar to this:
(Java)
http://java.sun.com/applets/jdk/1.4/demo/applets/GraphLayout/example1.html
or these:
(Proce55ing)
http://www.cricketschirping.com/processing/ExportAtlas/
or
http://www.cricketschirping.com/weblog/2005/12/11/force-directed-graph-layout-with-proce55ing/
or
http://www.cricketschirping.com/weblog/2007/02/26/force-directed-graph-layout-with-processing-take-2/

I've problem to find something that give that physical effect (like a
spring).

Any idea?


Use pygame (http://www.pygame.org) for drawing the graphs, lines, and 
circles.


Roll your own physics engine. The site you give described how it made 
the physics and you can also look at their java source code (below some 
of the applet there is a download source code link).

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


Python library "support" propaganda lists?

2009-10-30 Thread Aaron Watters
Let me vent my annoyance.

In the last couple months on a few occasions
I've tried various Python libraries (and I'm not going to
name names) and run into some problem.

Following the documented procedure I eventually
post the problem to the "support" list trying to politely
explain everything, including the admission that
it may all be my stupidity causing the problem.

Then I'm told automatically that my post will
be moderated.

Then nothing happens.  The post just disappears.
No offline reply.  Nothing.

I don't know why this happens, but if people
are using their "support" forums as propaganda
lists for only happy news I consider this a serious
violation of the spirit of open source.  There
is nothing wrong with filtering spam, of course,
but silently filtering non-spam, even inane non-spam,
is not acceptable.  At least there should be an
offline RTFM reply to the poster.

There, I feel better now.
-- Aaron Watters
   http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts

===
If you think you are smart enough
to write multi-threaded programs,
then you're not.-- Jim Ahlstrom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Xavier Ho
Alf, I kindly urge you to re-read bartc's comments. He does have a good
point and you seem to be avoiding direct answers.

On Fri, Oct 30, 2009 at 1:17 PM, Alf P. Steinbach  wrote:

> * bartc:
>
>> You say elsewhere that you're not specifically teaching Python, but the
>> text is full of technical details specific to both Python
>>
>
> Yes. A programming language is required to do programming. Can't do without
> it, sorry.
>
>
As an author of a programming textbook, you have to make the reader
comfortable in coding before he/she can do something useful, or play around
with. When I read through yours, my impression was a lot of terms, and the
examples don't seem to be particular interesting. They do what they do -
practical feedbacks such as what type a literal is, but they don't "teach
the student how to self-teach." Try to grant imaginations. I think you can
use a lot more examples that are actual programs, maybe 4-10 lines long, and
actually does something interesting. It'll allow the reader more familiar
seeing a code snippet that works, and in turn having them used to the syntax
and so on. Complete examples are one of the best ways to teach.


 not much actual programming!
>

Hm. There's /only/ programming in there and nothing else so far.
>

I think bartc means you don't have "actual examples". Sure you have a lot of
"examples", but they don't do anything. As a self-taught Python programmer,
I only read /interesting/ tutorials and/or examples. I find your text filled
with terms I didn't need to know until later, which I simply googled about.

That reminds me a good point: allow the student to explore. Don't try to
tell them everything, but show them the way. Once they start walking,
they'll see new things for themselves.

 Python has a lot of baggage which is OK if that's what's going to be used,
> but otherwise is unnecessary confusion: where to put the program code (typed
> in live or in a file, or some combination); whether to call the file .py or
> .pyw; the difference between console and graphical programs and so on.
>

Well.
>

Again here you're avoiding giving him answers. I just wanted to chime in and
resonate with bartc's comment here: you do have a lot of "unnecessary
confusion" in your first chapter. Why go through all the trouble to explain
how to compile a program, or what's the difference between python and
pythonw? You even went into try-except blocks and error-handling in the
second chapter! That's a little... fast, don't you think? The reader/student
hasn't done anything practical or interesting yet, and you're putting all
these weight on him/her ... that's something for you to think about.

I believe teaching needs to be interesting. While I appreciate your humour
in the writing style, I was not thrilled by the examples you're using. Could
you make your book more interesting to read by providing examples that do
things, please?

Also, last thing, could you use "and" instead of ampersand (&) in your book?
That would be so awesome. It just irks me. I really don't know why. But heh,
I suppose you can do that when you finish the book, with a quick
find-and-replace.

Best of luck and continue with your good efforts,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library "support" propaganda lists?

2009-10-30 Thread Frank Millman

"Aaron Watters"  wrote in message 
news:69f74b6c-e996-4e5c-a9f2-b5173e33a...@d21g2000yqn.googlegroups.com...
> Let me vent my annoyance.
>
> In the last couple months on a few occasions
> I've tried various Python libraries (and I'm not going to
> name names) and run into some problem.
>
> Following the documented procedure I eventually
> post the problem to the "support" list trying to politely
> explain everything, including the admission that
> it may all be my stupidity causing the problem.
>
> Then I'm told automatically that my post will
> be moderated.
>
> Then nothing happens.  The post just disappears.
> No offline reply.  Nothing.
>
> I don't know why this happens, but if people
> are using their "support" forums as propaganda
> lists for only happy news I consider this a serious
> violation of the spirit of open source.  There
> is nothing wrong with filtering spam, of course,
> but silently filtering non-spam, even inane non-spam,
> is not acceptable.  At least there should be an
> offline RTFM reply to the poster.
>
> There, I feel better now.
>-- Aaron Watters
>   http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts
>
> ===
> If you think you are smart enough
> to write multi-threaded programs,
> then you're not.-- Jim Ahlstrom
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Frank Millman

"Aaron Watters"  wrote in message 
news:69f74b6c-e996-4e5c-a9f2-b5173e33a...@d21g2000yqn.googlegroups.com...
> Let me vent my annoyance.
>
> In the last couple months on a few occasions
> I've tried various Python libraries (and I'm not going to
> name names) and run into some problem.
>
> Following the documented procedure I eventually
> post the problem to the "support" list trying to politely
> explain everything, including the admission that
> it may all be my stupidity causing the problem.
>
> Then I'm told automatically that my post will
> be moderated.
>
> Then nothing happens.  The post just disappears.
> No offline reply.  Nothing.
>
> I don't know why this happens, but if people
> are using their "support" forums as propaganda
> lists for only happy news I consider this a serious
> violation of the spirit of open source.  There
> is nothing wrong with filtering spam, of course,
> but silently filtering non-spam, even inane non-spam,
> is not acceptable.  At least there should be an
> offline RTFM reply to the poster.
>
> There, I feel better now.
>-- Aaron Watters
>   http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts
>
> ===
> If you think you are smart enough
> to write multi-threaded programs,
> then you're not.-- Jim Ahlstrom
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Xavier Ho
On Fri, Oct 30, 2009 at 1:48 PM, Alf P. Steinbach  wrote:

> Does that mean that 'print' is still subject to change as of 3.1.1?


Funny that. They removed reduce() when Python moved from 2.6.x to 3.0. They
even removed __cmp__(). Makes me a sad panda.

Is print() subject to change as of 3.1.1? I'd say so. Nothing drastic, as
others have pointed out, but anything is subject to change.

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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Frank Millman
Aaron Watters wrote:

>
> Following the documented procedure I eventually
> post the problem to the "support" list trying to politely
> explain everything, including the admission that
> it may all be my stupidity causing the problem.
>
> Then I'm told automatically that my post will
> be moderated.
>
> Then nothing happens.  The post just disappears.
> No offline reply.  Nothing.
>

Humble apologies for the idiotic blank replies - not once, but twice!!

Question - do you 'subscribe' to the lists first?

Exactly what you describe has happened to me before. The instructions 
typically do not make it clear that you have to subscribe first, so I just 
posted. After getting no response, I tried subscribing and then posting, and 
it worked.

Instructions could be clearer, I agree.

Frank Millman



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


Re: Web development with Python 3.1

2009-10-30 Thread Dotan Cohen
>> Look at this "templating code":
>> {% for entry in blog_entries %}
>>    {{ entry.title }}
>>    {{ entry.body }}
>> {% endfor %}
>
> What's the problem ? Simple, clear and obvious.
>

It is clear and obvious. But it has the "template engine" duplicating
a function that Python has built in. My goal is to learn reusable
Python (reusable for non-web projects). My goal is not to find the
quickest way to a website.


>> Why would I want to learn that when Python already has a real for
>> loop ?
>
> If you know even 101 Python, understanding the above code shouldn't be such
> a great challenge !-)
>

It is not a great challenge, but it is redundant. Learning Django
language won't help me learn Python any more than learning PHP would.
So going from PHP to Django is pointless.


>> I know HTML, and I have a goal of learning Python for it's
>> reusability (desktop apps, for instance).
>
> Using templates instead of harcoding HTML in the applicative code actually
> plays a big part when it comes to reusability.

I meant reusable knowledge, not reusable code.


> Telling Django's template
> loader where to look for templates is just a matter of configuration, so
> using templates you can segment your whole project in small, possibly
> reusable apps - then in another project where you need the same features but
> with a totally different presentation, it's just a matter of writing
> project-specific templates. Quite a few django apps work that way, and they
> really save you a LOT of time. This wouldn't be possible using your beloved
> antipattern...
>

I think that the time that I invest codng in Python as opposed to
Django Template Language is time well spent.


>> I don't want to learn some
>> "templating language" that duplicates what Python already has built
>> in!
>
> Then use Mako - it uses plain Python to manage the presentation logic. And
> if you go for Mako, then you might as well switch to Pylons. Great framework
> too (better than Django on some parts FWIW), but you'll probably need much
> more time to be fully productive with it (power and flexibility come with a
> price...).
>

Now we're talking! I will look further into Pylons and Mako.


> Now wrt/ "why having a distinct templating language", there are pros and
> cons. On the pros side, having a language that is clearly restricted to
> presentation logic prevents you (and anyone else working on the project -
> and sometimes you have to deal with well-below-average guys in your team) to
> put anything else than presentation logic in the templates.
>

I don't expect to ever have a "team", but as a hobbiest and not a
coder I myself am "below average". I promise you that _will_improve_,
though.


> Bless me for I have sinned - sometimes, when you're tired and under pressure
> to deliver in time, it's tempting to add a Q&D hack in the presentation part
> instead of DoingTheRightThing(tm). This can save you some "precious" minutes
> now. The problem is that usually your boss won't give you the resources to
> clean up this mess once you delivered, and next time you have to work on
> this project - fix or evolution - you have to deal with this hack. Then with
> another, yet another, until your code is nothing more than an unmaintainable
> heap of junk. Been here, done that, bought the T-shirt :(
>
> Also remember that most of the time, a web app is a team effort, and even if
> *you* don't fail to temptation, others may do so. And finally, the team
> usually involve "HTML coders" - who, despite what the name seems to imply,
> are usually skilled enough to handle the presentation logic by themselves,
> so you the application programmer can concentrate on applicative code. From
> experience, they usually prefer a simple straightforward - even if somehow
> restricted - templating language.
>
> Now, as far as I'm concerned, having Mako instead of Django's templates
> wouldn't bother me at all. But Django has it's own template system, which
> from experience get the job done (believe me, there are way worse
> alternatives), and the overall qualities and features of the whole framework
> are IMHO enough to justify learning it's templating language.
>

I see. I will have to spend some time with each to decide, though.


>> I think that I will use the HTTP-abstraction features of Django, but
>> disregard the templates. My code might be uglier, but the knowledge
>> will be transferable to other projects. My ultimate goal is not to
>> make the latest greatest website. My ultimate goal is to port my
>> perfectly functional website to a language that will benefit me by
>> knowing it.
>
> Given the restricted and rather unintersting nature of pure presentation
> logic, you won't learn much from this part of the project anyway. You'd
> probably learn way more using Django's templates and learning how to write
> your own template tags. Or if you prefer Mako / Pylons, learning to make
> proper use of Mako's advanced features. But one thing is clear - if you
> persist on a

Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-30 Thread Lie Ryan

Aahz wrote:

In article ,
Robert Kern   wrote:
I like using pyflakes. It catches most of these kinds of typo errors, but is 
much faster than pylint or pychecker. 


Coincidentally, I tried PyFlakes yesterday and was unimpressed with the
way it doesn't work with "import *".


If only IDLE's Intellisense worked without having to run the code first, 
perhaps I wouldn't have abandoned using IDE altogether to write codes 
and used vim/gedit/notepad/whateverpad instead. I've felt liberlized 
since going plaintext.

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


Re: Problem embedding Python.

2009-10-30 Thread Dave Angel

Dave Angel wrote:
Brandon 
Keown wrote:

On Oct 27, 7:48 pm, "Gabriel Genellina" 
wrote:
 


Now that you've solved your problem, revise your conclusion. A file
without a path *is* searched in the current working directory - but 
that

directory may not be the one you think it is.

--
Gabriel Genellina



I'm not sure what you mean.  I executed the program from the directory
the file was in, they were in the same directory.  And when a program
executes from a path in CMD in windows, that is supposed to be the
CWD.  I'm not sure what it would be set to if not that...

  
Gabriel is right.  But if you care to get our diagnosis, you need to 
state your working conditions more clearly.  Or perhaps do a bit of 
debugging on it.  For a start, you might do aprint os.curdir   
right before the open() function to see what the current directory is.


Or you could remove the several ambiguities in your paragraph above 
that starts "I'm not sure..."  Maybe show a transcript of your CMD 
session.  And if the python.* that's on your PATH is a batch file, 
show us the contents of that as well.


And if you're running from CMD, or from an interpreter, or from IDLE, 
or from an IDE, or from Explorer, each one may have its own idea of 
what to give you for current directory.


If you're running the script from a CMD prompt, by just entering the 
script name and letting Windows find the executable (which is not the 
script), then you're correct, CWD should be the same as it was in the 
CMD shell.


DaveA


OK, I blew it.  Instead of re-reading the thread, I relied on memory.  
So please cancel my last paragraph, and let me try again.


The big differences between your working code and the non-working code 
are three:
  The non-working code uses relative file name, while the working code 
uses absolute path.
  The non-working code uses C's open() call, while the working code 
changed that to  PyFile_FromString(filename, "r")
  The non-working code uses "w" mode on the open, trashing the file, 
while the working code uses "r"


I'd claim that #3 is your real problem.  I doubt that a file open in "w" 
mode is acceptable to the interpreter, since the first thing that does 
is truncate the file.


Anyway, Gabriel's point (which I poorly elaborated on) about the current 
directory is still valid.  But you should use C calls to see what it is, 
rather than Python calls.  And I'd still like to know how you're 
launching this executable, this compiled C program.  If you're running 
it from a CMD window, a DOS box, then the current directory is obvious 
from the prompt.


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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Ulrich Eckhardt
Aaron Watters wrote:
> In the last couple months on a few occasions
> I've tried various Python libraries (and I'm not going to
> name names) and run into some problem.
> 
> Following the documented procedure [...]

Documented where?

> [...] I eventually post the problem to the "support" list

Which support list?

> Then I'm told automatically that my post will be moderated.
> 
> Then nothing happens.  The post just disappears.
> No offline reply.  Nothing.

Are you talking about a single mailinglist maintained by Python or
are you talking about various lists of projects using Python?

> I don't know why this happens, but if people
> are using their "support" forums

And now it's a forum, not a mailinglist, and more than one of them?

Yes, I had people all over ignore requests, suggestions, bug reports etc. I
also had people take them up, comment sensibly, thank me or be up front and
reject my proposals for various reasons. Both categories came from
both "open" projects of volunteers and commercially run projects.

Maybe if they don't care about you, you shouldn't care about them?

I hope you have a happy weekend!

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Publishing new release on PyPI: How?

2009-10-30 Thread Michael Ströder
HI!

Well, maybe I'm completely blind but I can't find a way to add a new release
to PyPI index for python-ldap, not just a new file to an existing release
version. I'm the project owner and I did it several times in the past. But I
simply can't find the button where to add another release. Was there a change
in the UI recently?

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


Re: Web development with Python 3.1

2009-10-30 Thread Bruno Desthuilliers

Dotan Cohen a écrit :

Look at this "templating code":
{% for entry in blog_entries %}
   {{ entry.title }}
   {{ entry.body }}
{% endfor %}

What's the problem ? Simple, clear and obvious.



It is clear and obvious. But it has the "template engine" duplicating
a function that Python has built in. My goal is to learn reusable
Python (reusable for non-web projects). My goal is not to find the
quickest way to a website.


Please correct me if I'm wrong, but you did learn HTML, CSS and SQL, 
didn't you ? How do any of these languages relates to Python ?-)






Why would I want to learn that when Python already has a real for
loop ?

If you know even 101 Python, understanding the above code shouldn't be such
a great challenge !-)



It is not a great challenge, but it is redundant. Learning Django
language



Django's templating language, actually



won't help me learn Python any more than learning PHP would.
So going from PHP to Django is pointless.


Please get out of the "server page" mindset. Templates are just that : 
templates. Period. You don't use templates to write your *applicative* code.





I know HTML, and I have a goal of learning Python for it's
reusability (desktop apps, for instance).

Using templates instead of harcoding HTML in the applicative code actually
plays a big part when it comes to reusability.


I meant reusable knowledge, not reusable code.


There's very few "reusable knowledge" to be gained from templating code 
anyway- even if using a "python-based" template system like Mako. Unless 
you think doing a loop or a conditional are things you need to learn ?-)





Telling Django's template
loader where to look for templates is just a matter of configuration, so
using templates you can segment your whole project in small, possibly
reusable apps - then in another project where you need the same features but
with a totally different presentation, it's just a matter of writing
project-specific templates. Quite a few django apps work that way, and they
really save you a LOT of time. This wouldn't be possible using your beloved
antipattern...



I think that the time that I invest codng in Python as opposed to
Django Template Language is time well spent.


Then write your own templating system - and your own framework FWIW !-)




I don't want to learn some
"templating language" that duplicates what Python already has built
in!
Then use Mako - it uses plain Python to manage the presentation logic. 



Now we're talking! I will look further into Pylons and Mako.


Beware that the above comments about how less there's to learn from the 
templates code still apply - basically, the "programming" part of a 
template is restricted to simple branching, iterations, and variable 
substitution.





Now wrt/ "why having a distinct templating language", there are pros and
cons. On the pros side, having a language that is clearly restricted to
presentation logic prevents you (and anyone else working on the project -
and sometimes you have to deal with well-below-average guys in your team) to
put anything else than presentation logic in the templates.



I don't expect to ever have a "team",


Possibly not. But as strange as it migh be, there are other peoples that 
do, and most of these frameworks are written by professional web 
programmers.



Now, as far as I'm concerned, having Mako instead of Django's templates
wouldn't bother me at all. But Django has it's own template system, which
from experience get the job done (believe me, there are way worse
alternatives), and the overall qualities and features of the whole framework
are IMHO enough to justify learning it's templating language.



I see. I will have to spend some time with each to decide, though.


That's usually the best thing to do - take a couple days doing the 
tutorials, and choose the one that fits your brain.



Given the restricted and rather unintersting nature of pure presentation
logic, you won't learn much from this part of the project anyway. You'd
probably learn way more using Django's templates and learning how to write
your own template tags. Or if you prefer Mako / Pylons, learning to make
proper use of Mako's advanced features. But one thing is clear - if you
persist on applying your favorite antipattern, you'll just waste more of
your time. Your choice, as usual...



The point is that I want to use only _Python_ features, not
Django/Mako/whatever features.


If so, you shouldn't use *any* third-part libs, and possibly not even 
the stdlib.


More seriously : reinventing the wheel - unless for educational purposes 
- is not really pythonic. If what you want is to learn, write your own 
framework, template system, form handling etc... You'll very certainly 
find out that they suck big time compared to existing projects, but 
you'll learn _at least_ one thing: that writing a sensible non-trivial 
framework or lib is *hard*.


Once again, been here, done that...


However I am aware that some things I
should not touc

Re: Modify dict/set during iteration?

2009-10-30 Thread Dave Angel

metal wrote:

Steven D'Aprano wrote:
  

On Thu, 29 Oct 2009 19:02:01 -0700, metal wrote:


I used this quickndirty way, any good idea to solve this problem?
  

It's not a problem that wants solving, it's a feature that wants paying
attention to.

As a general rule, you shouldn't modify data structures while you're
iterating over them, unless the data structure is advertised as safe to
modify while being iterated over, or you can do so in a way that is
guaranteed to be safe. When it comes to dicts and sets, neither of those
conditions hold.

Why do you want to do this? It seems like a lot of effort to avoid a
simple, straight-forward idiom:

make a copy of the dict or set
iterate over the copy, making changes to the original

What are you trying to accomplish by modifying objects while iterating
over them?





def miter(iterable):
  

[...]


except RuntimeError, e:
# Not sure if there were any other RuntimeError
if 'changed size during iteration' in e.message:
continue
  

That is not safe. There's no guarantee that the error message won't
change, even between one minor version to another, or between one Python
implementation and another. If you insist on making such an unsafe test,
at the very least be as conservative in what you expect as possible:

if 'changed' in e.message and 'size' in e.message:

and hope that nobody runs your code with internationalised error messages.

--
Steven



Yes the idoim rulz. I confused my self.

Maybe my real goal is the following:

def miter(iterable):
for x in tuple(iterable):
if x in iterable:
yield x


  
That works, though I'd change the parameter name to something to 
indicate that it's a set or dictionary, not a general iterable.


As someone else pointed out, you can't use 'in' on a generator, for example.

Assuming a dict, what happens if a new item created in the dictionary, 
but reusing an old key?  It won't cause an exception, but you run the 
risk of either processing some data twice, or some not-at-all.  Whether 
that matters or not depends on your use-case.  Sometimes you need to 
copy the keys, and sometimes you need to copy the keys and their values.


DaveA

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


Re: spring effect in Python

2009-10-30 Thread Riccardo Lemmi
pochis40 wrote:

> I'm trying to write in Python something similar to this:
> (Java)
> http://java.sun.com/applets/jdk/1.4/demo/applets/GraphLayout/example1.html
> or these:
> (Proce55ing)
> http://www.cricketschirping.com/processing/ExportAtlas/
> or
>
http://www.cricketschirping.com/weblog/2005/12/11/force-directed-graph-layout-with-proce55ing/
> or
>
http://www.cricketschirping.com/weblog/2007/02/26/force-directed-graph-layout-with-processing-take-2/
> 
> I've problem to find something that give that physical effect (like a
> spring).
> 
> Any idea?

For the physics engine you can try these libraries:
  http://code.google.com/p/pybox2d
  http://code.google.com/p/pymunk/

-- 
Riccardo Lemmi

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


Re: Python 2.6 Global Variables

2009-10-30 Thread Dave Angel

Gabriel Genellina wrote:
En Fri, 
30 Oct 2009 00:29:27 -0300, Steven D'Aprano 
 escribió:

On Thu, 29 Oct 2009 10:31:03 -0700, AK Eric wrote:



2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.


It isn't a neat trick anymore once you realize the name '__main__' 
isn't special.


Replace __main__ with foo, or config, or whatever, and you get the 
same results. Ok, there is a catch: a file with that name must exist, 
at least an empty one...


You're just importing the same module from two places; changes done in 
one place are reflected in the second place, like with any other object.



Thanks for saying that.

There are two interrelated advantages to using a separate module for the 
purpose.

1) it avoids circular dependency
2) it makes it clear who gets to initialize these "globals";  if this 
module doesn't import anything else (other than stdlib stuff), it'll run 
to completion before anyone who tries to use these values.  So it can 
give them all their initial value, and avoid anyone else needing to do 
any "existence check" nonsense.


When I've done it, I've called the module globals.py, or  flags.py
depending on the primary intent.


DaveA

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


Re: How to avoid certain directories when using os.walk?

2009-10-30 Thread Dave Angel

Chris Rebert wrote:

On Thu, Oct 29, 2009 at 9:53 PM, Peng Yu  wrote:
  

I don't see a way to avoid walking over directories of certain names
with os.walk. For example, I don't want os.walk return files whose
path include '/backup/'. Is there a way to do so? Otherwise, maybe I
will have to make my own program. Thank you!



Read the docs! (http://docs.python.org/library/os.html#os.walk):

"""
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Generate the file names in a directory tree by walking the tree
either top-down or bottom-up. For each directory in the tree rooted at
directory top (including top itself), it yields a 3-tuple (dirpath,
dirnames, filenames).
[...]
When topdown is True, the caller can modify the dirnames list
in-place (perhaps using del or slice assignment), and walk() will only
recurse into the subdirectories whose names remain in dirnames; this
can be used to prune the search, impose a specific order of visiting,
or even to inform walk() about directories the caller creates or
renames before it resumes walk() again.
"""

They even include a specific code example of how to skip unwanted
subdirectories.

Cheers,
Chris
--
http://blog.rebertia.com

  
The other thing to note is that it's easy to build a generator from 
os.walk() with whatever customization you like.  Then the program can 
use the generator the same way as he would use walk, just adding a list 
of directories to skip.


For example (untested)

def mywalk(top, skipdirs=[]):
   for root, dirs, files in os.walk(top):
   for skipdir in skipdirs:
   dirs.remove(skipdir)  # don't visit this directory
   yield root, dirs, files


DaveA 



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


Re: import problem in tkinter

2009-10-30 Thread Dave Angel

Jebegnana das wrote:

import _tkinter # If this fails your Python may not be configured for Tk

I'm using python3 in linux. In windows tkinter is working fine but in
mandriva linux spring 2009 it fails to import. Can you please tell me
step-by-step on how to fix this issue? In python3.1 home page the
description is not clear or it can't be understood by the beginner. As
i'm a beginner for programming python in linux please help me out. I
want to know what is the thing i missed during installation. I've done
the things correctly as mentioned in the python readme text inside the
python3.1 tarball file. While searching the net i found out that if i
want to fix this issue i've to uninstall and install it again. what
should i do now?

With Regards,
Jebagnana Das.A,
Mob : +91-9843828383





  Now, send attachments up to 25MB with Yahoo! India Mail. Learn how. 
http://in.overview.mail.yahoo.com/photos
  
Is the working Windows version the same, or is it 2.x ?  The import name 
for tkinter changed from Tkinter in 2.x to tkinter in 3.x.  I don't 
think you ever need to import _tkinter directly.



If you've tried
 import tkinter

and it fails in Python 3.x, then the next thing to do is look in the 
install directory.  For 3.x, in the Lib directory, look for a 
subdirectory called tkinter.  If it's there, and if it contains the file 
__init__.py, then tkinter is supposedly installed.


If it's really a Linux problem, I can't help further.

DaveA

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


Tutorial Forum

2009-10-30 Thread TheTutorialSpot Webmaster
Come check out http://www.thetutorialspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: self.__dict__ tricks

2009-10-30 Thread MRAB

Steven D'Aprano wrote:

On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:


Steven D'Aprano  writes:


On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:

class formLoader():

Idiomatic Python is to use CamelCase for classes.

Or rather: Instead of camelCase names, idiomatic Python is to use
TitleCase names.


Thank you for the correction. I always mix up those two.


Wouldn't it be clearer if they were called dromedaryCase and
BactrianCase? :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: self.__dict__ tricks

2009-10-30 Thread Tim Golden

MRAB wrote:

Steven D'Aprano wrote:

On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:


Steven D'Aprano  writes:


On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:

class formLoader():

Idiomatic Python is to use CamelCase for classes.

Or rather: Instead of camelCase names, idiomatic Python is to use
TitleCase names.

Thank you for the correction. I always mix up those two.


Wouldn't it be clearer if they were called dromedaryCase and
BactrianCase? :-)


It's not often I really get a laugh out of this
mailing list, but that really made me chuckle.

Thanks :)

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


Re: Are *.pyd's universal?

2009-10-30 Thread Dave Angel

Carl Banks wrote:

On Oct 29, 9:10 pm, Lawrence D'Oliveiro  wrote:
  

In message , Christian

Heimes wrote:


Lawrence D'Oliveiro schrieb:
  

In message ,
Christian Heimes wrote:


On Linux and several other Unices the suffix is .so and not .pyd.
  

Why is that? Or conversely, why isn't it .dll under Windows?


On Windows it used to be .dll, too.
The suffix was changed to avoid issues with other dlls and name clashes.
  

What clashes? How come other OSes don't seem prone to the same problems?



Yeah, because who ever heard of one OS having a problem that another
OS didn't?

Windows searches for DLLs on the executable path, which always
includes the current directory.  So if you have a module called
system32.dll in your currently directory, you could be in big trouble.

Unix doesn't automatically search the current dir, doesn't use the
executable search path (libraries have their own search path, which is
not used when loading shared libs by hand), and system libraries on
Unix conventionally are prefixed by lib.  So name collisions are rare,
but even if if you have a module called libc.so in your current
directory it will not conflict with /lib/libc.so.


Carl Banks

  
I don't believe changing the extension modifies the search order for 
LoadLibrary().  However, it does make a name collision much less likely, 
which is a "goodthing."  And I'd bet that more than 50% of DLL's on a 
typical machine have some other extension.


As for search order, I believe it's a bit different than the one used by 
CMD to search for an executable.  I do not think it includes the current 
directory, but instead includes the executable directory (which is 
frequently where Python.exe is located).


And I'm guessing that CPython searches down sys.path, and when it finds 
the module, gives a full path to LoadLibrary(), in which case the DLL 
search path is moot.


DaveA


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


Re: Python 2.6 Global Variables

2009-10-30 Thread AK Eric
> > It isn't a neat trick anymore once you realize the name '__main__'
> > isn't special.
>
> > Replace __main__ with foo, or config, or whatever, and you get the
> > same results. Ok, there is a catch: a file with that name must exist,
> > at least an empty one...

True.  I do feel a bit less special now :-P  And again, I think there
is a difference from saying you *can* work a certain way, and you
*should* work a certain way.  Making a 'global module' you import and
muck with = good.  Other ways discussed = bad (for the most part).
But I think it's important to understand the underlying system
especially when one is first learning:  I hand a heck of a time having
someone explain this stuff to me when I was learning the basics (and
I'm still figuring it out, even from this thread) and now that I get
how it works (I uh... think) it makes me a stronger scripter.  The
common thought seemed to be "you shouldn't do it that way, so I'm not
going to explain it to you" which I've always found quite
frustrating.  And along those lines...

Should we start talking about how you can add stuff to __builtin__ and
then it really is exposed to everything? (right, unless I'm missing
some other Python idiom?)  Again, *not advocating* in standard
practice, but I think it's important to understand how it works.
(ducks incoming flak)

#-
# moduleA.py
import __builtin__
__builtin__.spam = 42
__builtins__["ham"] = 24

#-
# moduleB.py
# This will fail if moduleA isn't executed first
print spam, ham

>>> import moduleA
>>> import moduleB
42 24

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


Re: self.__dict__ tricks

2009-10-30 Thread Tim Johnson
On 2009-10-30, Steven D'Aprano  wrote:
>
> Could you explain what problem you are trying to solve?
>
>
>> class formLoader():
 
  Hi Steve 
  In a nutshell:
  The 'problem' is to parse a form in such a way that tags which are to
  be modified are represented as dictionaries. The 'grunt' work is
  done.  This class will probably grow with time.

> Idiomatic Python is to use CamelCase for classes.
  Can you point me to a discussion on Idiomatic Python, CamelCase and
  other matters?

> Is your intention to ensure that the only keyword arguments allowed are 
> fileName, record and string?
 Correct.

> Perhaps the easiest way to do that is:
>
> for k in kw:
> if k not in ('filename', 'record', 'string'):
> raise Exception()  # whatever...
> setattr(self, k) = kw[k]
  Understood. A better 'trick'

>>  else:
>>  raise AttributeError(
>
> In my opinion, AttributeError is not appropriate here. Passing an invalid 
> parameter shouldn't raise the same error as failing an attribute look-up. 
> That's misleading and confusing.
  What error class or other approach do you recommend?

> [Aside: eight space tabs are *WAY* too big for Usenet and email. You 
> should use four spaces, or even two, when posting here.]
  Yikes! I just starting using vim with slrn again. Will take care of 
  that.

> It is idiomatic Python to use "instance attributes" to refer to 
> attributes attached to instances, and "class attributes" to refer to 
> those attached to classes. Talking about "class members" will confuse 
> Python developers who aren't also familiar with Java or C++. (I know it 
> confuses *me* -- are class members shared by all instances in a class, as 
> the name implies, or are they individual to the instance, as your code 
> implies?)
 Thanks for that. C++ corrupted me.

> I also should point out that your trick will fail if you are using 
> __slots__.
  ??. Will research that. Elaborate if you wish.

>>  self.tokens = 
> ["form","input","textarea","select","option","form"]
<>
>
> Is any of that relevant to the trick you are asking for comments for? If 
> not, why is it here?
 It was there to illustrate my edification of the usage of self.__dict__

>> I'd welcome comments - such as any other applications.
>
> Personally, I don't like it. The method signature makes it impossible to 
> tell what arguments are excepted, and it forces me to use keywords even 
> if I'd prefer to use positional arguments. I prefer to let the 
> interpreter check the arguments for me:

  Using your tuple example would clarify things. The method signature
  then becomes the tuple. I.E 

  # 
  if k not in ('filename', 'record', 'string'): 
   # handle here 

  If the class grows - and I expect it will - I'd prefer to stick with
  the keywords approach. That approach also allows me to use a
  dictionary to initialize the object.

  Thanks for the input. Very helpful.
  - and always a newbie -
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library "support" propaganda lists?

2009-10-30 Thread Robert Kern

On 2009-10-30 07:30 AM, Aaron Watters wrote:

Let me vent my annoyance.

In the last couple months on a few occasions
I've tried various Python libraries (and I'm not going to
name names) and run into some problem.

Following the documented procedure I eventually
post the problem to the "support" list trying to politely
explain everything, including the admission that
it may all be my stupidity causing the problem.

Then I'm told automatically that my post will
be moderated.

Then nothing happens.  The post just disappears.
No offline reply.  Nothing.

I don't know why this happens, but if people
are using their "support" forums as propaganda
lists for only happy news I consider this a serious
violation of the spirit of open source.  There
is nothing wrong with filtering spam, of course,
but silently filtering non-spam, even inane non-spam,
is not acceptable.  At least there should be an
offline RTFM reply to the poster.


You almost certainly ran into technical misconfiguration or lazy moderators. 
Both are distressingly common with mailing lists. Hanlon's Razor: "Never 
attribute to malice that which can be adequately explained by stupidity." You 
may also want to check to see if your mail host is on any spam block lists like 
Spamhaus.


So go ahead and name names. This may be the one chance the list owners will be 
able to learn about their misconfiguration. Just don't accuse them of censoring 
negative posts without actual evidence; you don't have any to support that 
conclusion.


In any case, it is accepted (or so I assert) that if you are having problems 
with a Python project, you can post your questions here until you are able to 
post to the project's mailing list.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


How to keep permission bits when including package data in distutils

2009-10-30 Thread Olli Wang
Hi, I want to include some binary package data into my distribution
and I define these binary in MANIFEST.in. However, all binary lose the
`x` permissions so they can't be executed in my program. Is there any
way to remedy this situation? Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library "support" propaganda lists?

2009-10-30 Thread Aaron Watters
[note: if this shows up twice, it's because my internet connection
flaked out]

On Oct 30, 12:23 pm, Robert Kern  wrote:
> You almost certainly ran into technical misconfiguration or lazy moderators.

It's suspicious, however, when other posts
which seem to be from new posters get through
in a timely fashion.

On Oct 30, 8:53 am, "Frank Millman"  wrote:
> Question - do you 'subscribe' to the lists first?

Yes I do, or at least I try.  Sometimes the request to
join gets silently moderated into the bit bucket also.

Ulrich: I'm not talking about the python.org lists
where I've *never* had problems.  I'm talking about
other lists.

I know this may be due to simple laziness and negligence,
but in that case they should turn moderation off.

I don't want to say where I've had this problem,
because I don't want to offend anyone in particular
-- I'm just making a general observation.  Maybe
as Robert suggests I will try comp.lang.python as
a fall back after a few days of nonresponsiveness
in the future...

   -- Aaron Watters
  http://aaron.oirt.rutgers.edu/myapp/docs/W1100_2200.TreeView

===
"I'm practicing monogamy
(but I'm not very good at it yet)."  -- Steven Tyler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode again ... default codec ...

2009-10-30 Thread zooko
On Oct 20, 9:50 pm, "Gabriel Genellina" 
wrote:

> DON'T do that. Really. Changing the default encoding is a horrible,
> horrible hack and causes a lot of problems.

I'm not convinced.  I've read all of the posts and web pages and blog
entries decrying this practice over the last several years, but as far
as I can tell the actual harm that can result is limited (as long as
you set it to utf-8) and the practical benefits are substantial.  This
is a pattern that I have no problem using:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

The reason this doesn't cause too much harm is that anything that
would have worked with the original default encoding ('ascii') will
also work with the new utf-8 default encoding.  As far as I've seen
from the aforementioned mailing list threads and blog posts and so on,
the worst thing that has ever happened as a result of this technique
is that something works for you but fails for someone else who doesn't
have this stanza.  (http://tarekziade.wordpress.com/2008/01/08/
syssetdefaultencoding-is-evil/ .)  That's bad, but probably just
including this stanza at the top of the file that you are sharing with
that other person instead of doing it in a sitecustomize.py file will
avoid that problem.

Regards,

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


Re: Python 2.6 Global Variables

2009-10-30 Thread Stephen Hansen
On Fri, Oct 30, 2009 at 9:01 AM, AK Eric  wrote:

> Should we start talking about how you can add stuff to __builtin__ and
> then it really is exposed to everything? (right, unless I'm missing
> some other Python idiom?)  Again, *not advocating* in standard
> practice, but I think it's important to understand how it works.
> (ducks incoming flak)
>

It is important to understand how it works-- but only really in that it's
important that people understand how Python handles 'finding' an object when
you specify a name... not understanding this leads lots of people to various
sorts of confusion, especially as they come from other languages. Python
doesn't really have true nested scopes*, it doesn't search up from where you
are to go 'higher' and 'higher' and then check some universal-shared global
scope, etc.

Python has namespaces-- at any given time, there's only three that are
accessible. The local namespace, the global namespace, and the builtin
namespace.

When you reference 'x' in your code, say, as "y = x", Python first looks in
the local namespace. Failing to find it there, it looks in the global
namespace-- which is really the module-level namespace. And, finally,
failing that... it looks in the builtin namespace. For, y'know, builtins.

* Okay, in Python 2.1/2.2 there was added a limited level of nested scoping
to Python for functions embedded in other functions; if a name isn't found
in the local scope and the local scope is a nested function, it checks the
locals of the containing function too. This is a great addition, but
actually seems to have inspired people to think Python has a more pervasive
support of dynamic nested scoping going on-- in particular the mythical
'class scope', which it doesn't have.

Now, all that said... one should NOT mess around with __builtin__. You may
break third-party code you use that way, or at least introduce
maintainability nightmares.

In Python things don't live off in the ether, everything lives in an
explicit place. This is a good thing. Messing with __builtin__ and adding
stuff violates this principle. It makes code harder to comprehend by just
looking at a single file-- you can't know where everything is defined that
way, you can't keep your mind local and 'get' what you're working on. 'from
x import *' is a similar problem here, but at least there you have a flag
somewhere in the file saying 'hey, go look over here to maybe find that
var'.

You CAN do it, sure... and there are a some (very, very, very limited!)
use-cases where its even good and the right-thing to do, which is why its
exposed to you to be ABLE to do it, and doesn't have this giant 'DO NOT DO
THIS!' warning in the official docs.  But unless you know you must do it to
get the result you need-- then the answer to, 'Should I use this feature?'
in this case is a resounding no. Use something else instead, even if it
doesn't seem as 'nice' to you (such as import settings; settings.blah
instead of just blah) IMHO. :)

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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Robert Kern

On 2009-10-30 11:31 AM, Aaron Watters wrote:


I know this may be due to simple laziness and negligence,
but in that case they should turn moderation off.


That's the funny thing about mailing list problems. If a misconfiguration means 
people can't post to your, you don't hear from the people having problems. Try 
emailing one of the project leaders directly (and politely!) to ask them to 
check their moderation queue for your post. And check Spamhaus to see if your 
mail host is on their list!



I don't want to say where I've had this problem,
because I don't want to offend anyone in particular
-- I'm just making a general observation.


No, you're not. You're making unsupported accusations of malfeasance.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Sqlite3. Substitution of names in query.

2009-10-30 Thread Matteo
On Oct 30, 7:10 am, Lacrima  wrote:
> Hello!
>
> I use sqlite3 module for my sqlite database. I am trying to substitute
> table name in sql query.
>
> >>> import sqlite3
> >>> con = sqlite3.connect('mydb')
> >>> cur = con.execute("select * from table where name='Joe'")
>
> That's ok
>
> >>> cur = con.execute("select * from table where name=?", ('Joe',))
>
> That's ok too
>
> >>> cur = con.execute("select * from ? where name=?", ('table', 'Joe'))
>
> Traceback (most recent call last):
>   File "", line 1, in 
> sqlite3.OperationalError: near "?": syntax error
>
> So what's wrong now?
> Is it impossible to substitute table names, using DB API?
> If so, what is a way to make table name substitutions? Are string
> operations like
> 'select * from %s where...' % tablename
> ok in this case?
>
> Thanks in advance!

I've found myself wanting this ability too, but alas, it is not
possible. SQLite statements are compiled into an intermediate bytecode
so that they can execute very quickly. This bytecode allows for
placeholders to be used for values, so that the same compiled bytecode
can be run for a multitude of values (handy for large INSERTS, of
course) without recompilation.

As I understand it, the bytecode is specific to the table(s) and
columns used in the statement. I don't know the specific mechanism,
but I would suspect that a column name gets converted to an offset
into a row, or to a pointer to a table's column array, or somesuch. In
particular, the code generated is probably drastically different
depending on whether or not a column in a table is indexed or not.
Thus, if a placeholder was used for a column, then the whole statement
would have to be recompiled each time it was run, which would do very
nasty things to efficiency.

So, if you really need that ability, you must use normal python string
interpolation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.6 + win32com crashes with unicode bug

2009-10-30 Thread GerritM

Terry Reedy schreef:

GerritM wrote:
I have automated image generation with Python, win32com and Visio5.0. 
This works well upto Python2.5 but fails with Python 2.6.

Short term solution is to return to 2.5 :-(.

I have reproduced the bug below with a minimum of Python lines. Below 
the problem the working example from 2.5


kind regards, Gerrit

---minimal session reproducing the bug---


<..snip..>

d = v.Documents.OpenEx("D:/temp/test.vsd",8)

<...snip...>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 
52: ordinal not in range(128)


I suspect that 2.6 fixed the bug of allowing non-ascii chars when using 
the ascii codec.  I would check to see if there is an 0x83 in 
D:/temp/test.vsd



<...snip...>
the string "D:/temp/test.vsd" itself does not contain any 
charactervalue>128:

>>> for c in "D:/temp/test.vsd":
print ord(c), " ",

68   58   47   116   101   109   112   47   116   101   115   116   46 
 118   115   100

(on my current Python 2.5 configuration)

The presumably binary file itself may contain any value, but I don't 
expect Python or win32com to do anything with the file content...


There are explanations on internet that Windows uses internally 2 
(incompatible) API's that cause poblems with Unicode based filenames. I 
do something like that to be the problem in Python 2.6


kind regards, Gerrit

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


Re: Sqlite3. Substitution of names in query.

2009-10-30 Thread Matteo
On Oct 30, 7:27 am, "Diez B. Roggisch"  wrote:
[snip]
> Or even better, by
> not doing it at all - because usually, your datamodel is tied to your
> program, so the need for this kind of dynamicity shouldn't arise in the
> first place.
>
> Die

Perhaps that is true in the majority of cases, but there are
exceptions. I can think of a couple of instances where one might need
to do it:
1) A general database exploration or visualization application, or

2) Where one needs to perform a similar operation on several different
tables. In a current case of mine, I'm converting from several
externally provided tab-delimited tables to an in-memory sqlite
database. Most of my app is tied closely to the model, and needs no
such dynamicity. However, I want to automate the conversion, so I
don't have to write 20 or so similar functions.
-- 
http://mail.python.org/mailman/listinfo/python-list


How can module determine its own path?

2009-10-30 Thread kj


How can a module determine the path of the file that defines it?
(Note that this is, in the general case, different from sys.argv[0].)

TIA!

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


Re: transpose array

2009-10-30 Thread Aahz
In article ,
Rhodri James  wrote:
>
>Surely more Pythonic would be:
>
>for t in zip(xVec, yVec, zVec):
> print >>f, ", ".join(t)

Except that you *really* want itertools.izip() if these vectors are
likely to be any significant size.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can module determine its own path?

2009-10-30 Thread Robert Kern

On 2009-10-30 12:19 PM, kj wrote:

How can a module determine the path of the file that defines it?
(Note that this is, in the general case, different from sys.argv[0].)


__file__

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Socket MUD client script

2009-10-30 Thread Zamnedix
I'm having trouble with this script I'm writing. I want it to connect
to a MUD, which it does fine, but afterwards it displays the greeting
and login prompt, and when I type in username the loop to receive and
then send seems to stop.


Here's my code:

#!/usr/bin/python
import socket
import sys
a = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = str(raw_input("HOST:PORT > "))
address = address.split(":")
a.connect((address[0], int(address[1])))
print "CONNECTED"
while 1:
   print a.recv(4079)
   print a.recv(4079)
   msg = str(raw_input("MSG > "))
   a.sendall(msg)

Here's what happens:
$ python connect.py
HOST:PORT > lofe.org:8000
CONNECTED


 ._
((big ascii art greeting, staff info and stuff))

Enter your character's name, or type new:
MSG > Xeythos

la la la la la la

^CTraceback (most recent call last):
  File "connect.py", line 18, in ?
print a.recv(4079)
KeyboardInterrupt
$



Also, I have to receive twice to get the whole greeting, and it comes
really slowly in two pieces.
I've looked around the internet for a good tutorial on python and
sockets but haven't really found anything. Am I using the wrong type
of socket, or what? Someone please help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Alf P. Steinbach

* bartc:


python.org seems to be the main site. Google "python download" and that 
is the first hit.


Their windows download seems to be 13MB against the 32MB of activestate, 
and the IDE provided seems more advanced that the 'console window' you 
have in your tutorial. I'm just asking why your chose one over the other...


I've changed that choice, so it's not something very important, but an 
ActiveState installation of some language generally Just Works, while other 
installations of non-Windows-specific programming stuff generally doesn't, 
requiring manual fixups.


For example, the mainstream Python 2.6 distribution failed to install when asked 
to pre-compile (advanced option).


Regarding the "IDE" I'm not sure what you're referring to because there's no 
such thing AFAICS. There's IDLE, which is referred to as an IDE but is (1) also 
present in the ActiveState distribution and is (2) not really an IDE in any but 
perhaps a formal sense. It's just a primitive editor with a primitive debugger 
that, in Windows, has an annoying bug regarding highlighting of code.



[snippety]

Cheers & hth.,

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


Re: How to avoid certain directories when using os.walk?

2009-10-30 Thread Sean DiZazzo
On Oct 29, 10:17 pm, Chris Rebert  wrote:
> On Thu, Oct 29, 2009 at 9:53 PM, Peng Yu  wrote:
> > I don't see a way to avoid walking over directories of certain names
> > with os.walk. For example, I don't want os.walk return files whose
> > path include '/backup/'. Is there a way to do so? Otherwise, maybe I
> > will have to make my own program. Thank you!
>
> Read the docs! (http://docs.python.org/library/os.html#os.walk):
>
> """
> os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
>
>     Generate the file names in a directory tree by walking the tree
> either top-down or bottom-up. For each directory in the tree rooted at
> directory top (including top itself), it yields a 3-tuple (dirpath,
> dirnames, filenames).
> [...]
>     When topdown is True, the caller can modify the dirnames list
> in-place (perhaps using del or slice assignment), and walk() will only
> recurse into the subdirectories whose names remain in dirnames; this
> can be used to prune the search, impose a specific order of visiting,
> or even to inform walk() about directories the caller creates or
> renames before it resumes walk() again.
> """
>
> They even include a specific code example of how to skip unwanted
> subdirectories.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

You will run into problems however if you want to delete from a tree
while ignoring certain named directories.  Directories must be empty
before they can be deleted, so you must use "topdown=False", but to
prune a search you must use "topdown=True".  At least I think that was
the problem I had with my deletion script a while back.

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Alf P. Steinbach

* Alf P. Steinbach:

* bartc:


python.org seems to be the main site. Google "python download" and 
that is the first hit.


Their windows download seems to be 13MB against the 32MB of 
activestate, and the IDE provided seems more advanced that the 
'console window' you have in your tutorial. I'm just asking why your 
chose one over the other...


I've changed that choice, so it's not something very important, but an 
ActiveState installation of some language generally Just Works, while 
other installations of non-Windows-specific programming stuff generally 
doesn't, requiring manual fixups.


For example, the mainstream Python 2.6 distribution failed to install 
when asked to pre-compile (advanced option).


Sorry, I meant 3.1.1. I posted links to screenshots else-thread. Earlier.



Regarding the "IDE" I'm not sure what you're referring to because 
there's no such thing AFAICS. There's IDLE, which is referred to as an 
IDE but is (1) also present in the ActiveState distribution and is (2) 
not really an IDE in any but perhaps a formal sense. It's just a 
primitive editor with a primitive debugger that, in Windows, has an 
annoying bug regarding highlighting of code.



[snippety]

Cheers & hth.,

- Alf

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Dann Corbit
In article , 
r...@see.sig.invalid says...
> 
> In , Dann 
> Corbit wrote:
> 
> 
> > 
> > You can read PDF with the ghostscript stuff or the free Adobe stuff.
> 
> Agreed. But why should you have to?

As opposed to...?
PDF and PS are no more or less proprietary than any other format.  And 
Ghostscript is open source.

> > A man who cannot read .pdf or .ps in today's computer science world
> > is a crippled man (IMO-YMMV).
> 
> A man who doesn't particularly enjoy relying on proprietary non-text 
> formats, however, is not crippled, just cautious.

Since Ghostscript is an open source project, this is a non-sequitor.
 
> A man who cannot express what he needs to express /without/ resorting 
> to .pdf format is computer-illiterate.

You have two choices at citeseer:
PDF, PS.

All college papers are also posed in one of those two formats.

It takes me about 7 seconds to download the latest reader from 
Ghostscript/Ghostgum or Adobe.  If I need to know the guts of these 
formats, I can simply examine the Ghostscript guts.  Quite frankly, I 
don't care at all, since I am interested in the information content and 
find the method of delivery utterly irrelevant.

To me, the argument is like objecting to money because it is either 
paper or metal and you would prefer stone.

Everyone uses paper or metal and either is superior to stone anyway.
> 


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


Re: import problem in tkinter

2009-10-30 Thread Peter Otten
Dave Angel wrote:

> Jebegnana das wrote:
>> import _tkinter # If this fails your Python may not be configured for Tk
>>
>> I'm using python3 in linux. In windows tkinter is working fine but in
>> mandriva linux spring 2009 it fails to import. Can you please tell me
>> step-by-step on how to fix this issue? In python3.1 home page the
>> description is not clear or it can't be understood by the beginner. As
>> i'm a beginner for programming python in linux please help me out. I
>> want to know what is the thing i missed during installation. I've done
>> the things correctly as mentioned in the python readme text inside the
>> python3.1 tarball file. While searching the net i found out that if i
>> want to fix this issue i've to uninstall and install it again. what
>> should i do now?
>>
>> With Regards,
>> Jebagnana Das.A,
>> Mob : +91-9843828383
>>
>>
>>
>>
>>
>>   Now, send attachments up to 25MB with Yahoo! India Mail. Learn how.
>>   http://in.overview.mail.yahoo.com/photos
>>   
> Is the working Windows version the same, or is it 2.x ?  The import name
> for tkinter changed from Tkinter in 2.x to tkinter in 3.x.  I don't
> think you ever need to import _tkinter directly.
> 
> 
> If you've tried
>   import tkinter
> 
> and it fails in Python 3.x, then the next thing to do is look in the
> install directory.  For 3.x, in the Lib directory, look for a
> subdirectory called tkinter.  If it's there, and if it contains the file
> __init__.py, then tkinter is supposedly installed.
> 
> If it's really a Linux problem, I can't help further.

The necessary include files for tcl/tk are probably not found during the 
build process. These are in packages called tk-dev, tk-devel or similar, and 
can be installed using the distribution's package manager. After that Python 
can be built with Tkinter support. Note that you have to repeat all steps 
starting with 

$ ./configure

Peter


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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Alf P. Steinbach

* bartc:


Python has a lot of baggage which is OK if that's what's going to be 
used, but otherwise is unnecessary confusion: where to put the program 
code (typed in live or in a file, or some combination); whether to call 
the file .py or .pyw; the difference between console and graphical 
programs and so on.


Hi.

I forgot or decided not to really answer this part earlier, so...

First of all, note that nothing of this is specific to Python.


(1)
"Where to put the program (typed in live or in a file)".

This is common to all languages that offer interpreted execution.

It is a feature, not a problem: in *addition* to putting your statements in a 
file for later execution, i.e. in addition to creating ordinary programs, you 
can explore the effects of statements by typing them at the interpreter.


Storing the statements in a file is to create a "program" in the usual sense.

Typing statements at the interpreter is just interactive use of the interpreter. 
Depending on the phase of the moon, one's shoe size and other factors , 
what's typed may be called a "program". But it's not a program in the usual 
sense, it's not a stored program: it's just interactive use of the interpreter.


Which is very convenient. :-)


(2)
"the difference between console and graphical programs"

This is a Windows issue.

Windows makes this differentiation.

Thus, it's there *regardless* of programming language. And for example, it 
doesn't matter whether the language offers an interpreter. With C or C++ you 
tell the linker which subsystem you want. With Java you use 'java' or 'javaw' to 
run the program as respectively console or GUI subsystem. With JScript and 
VBScript (script languages bundled with Windows) you use 'cscript' or 'wscript' 
to run the program as respectively console or GUI subsystem. With Ruby you use 
'ruby' or 'rubyw' to run the program. And so on  --  in the end it's always the 
bottom level executing machine code program that is console or GUI subsystem.


Do you think I should mention this in the text?

It will make the text longer, and I worked hard to make ch 1 as *short* as 
possible! :-)



(3)
"Whether to call the file .py or .pyw"

This is a feature, that you can relieve the user from the burden of choosing the 
most sensible way to execute the file (the user doesn't have to choose whether 
to use a console or GUI subsystem version of the interpreter, and the user 
doesn't even have to know that there is an interpreter involved).


It's a common convention for many languages (using those languages' filename 
extensions, of course), but it's not universal.



Cheers & hth.,

- Alf


PS: and yes, programming *is* a bit complex! That's what also makes it fun. 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Socket MUD client script

2009-10-30 Thread MRAB

Zamnedix wrote:

I'm having trouble with this script I'm writing. I want it to connect
to a MUD, which it does fine, but afterwards it displays the greeting
and login prompt, and when I type in username the loop to receive and
then send seems to stop.


Here's my code:

#!/usr/bin/python
import socket
import sys
a = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = str(raw_input("HOST:PORT > "))


'raw_input' returns a string, so there's no need to use 'str'.


address = address.split(":")
a.connect((address[0], int(address[1])))
print "CONNECTED"
while 1:
   print a.recv(4079)
   print a.recv(4079)
   msg = str(raw_input("MSG > "))
   a.sendall(msg)

[snip]

It might be expecting the string to end with '\n' or '\r\n'.

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


Re: Web development with Python 3.1

2009-10-30 Thread Terry Reedy

Dotan Cohen wrote:



It is clear and obvious. But it has the "template engine" duplicating
a function that Python has built in.


...


Then use Mako - it uses plain Python to manage the presentation logic. And
if you go for Mako, then you might as well switch to Pylons. Great framework
too (better than Django on some parts FWIW), but you'll probably need much
more time to be fully productive with it (power and flexibility come with a
price...).



Now we're talking! I will look further into Pylons and Mako.


I took a look a both yesterday. They are both generic text templating 
systems that seem to pretty much do the same thing. I suspect you will 
prefer Mako since it avoids duplicating Python's comtrol structures. But 
I think it worthwhile to look at both anyway since doing so will help to 
separate the concepts from the particular implementations.


My take on them is this: when text mixes code that is meant to be 
interpreted and text data meant to be taken literally, some means must 
be devised to distinguish the two. In programs files, the code is left 
unquoted and the text data is quoted. In template files, the marking is 
reversed: the literal text is left unquoted and the code *is* quoted. In 
Mako, expressions are quoted with braces ({...}), single statements with 
'%' prefix, and multiple statements as well as Mako tags with <% ...>.


Terry Jan Reedy

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


Re: How can module determine its own path?

2009-10-30 Thread AK Eric

> > How can a module determine the path of the file that defines it?
> > (Note that this is, in the general case, different from sys.argv[0].)
>
> __file__

Also:

import inspect
print inspect.getsourcefile(lambda:None)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library "support" propaganda lists?

2009-10-30 Thread Aaron Watters
On Oct 30, 12:51 pm, Robert Kern  wrote:
> On 2009-10-30 11:31 AM, Aaron Watters wrote:
>
> > I know this may be due to simple laziness and negligence,
> > but in that case they should turn moderation off.
>
> That's the funny thing about mailing list problems. If a misconfiguration 
> means
> people can't post to your, you don't hear from the people having problems. Try
> emailing one of the project leaders directly (and politely!) to ask them to
> check their moderation queue for your post. And check Spamhaus to see if your
> mail host is on their list!
>
> > I don't want to say where I've had this problem,
> > because I don't want to offend anyone in particular
> > -- I'm just making a general observation.
>
> No, you're not. You're making unsupported accusations of malfeasance.

I don't mean to accuse anyone of anything.
I just want to note that any manipulation of
list content, *if* it ever occurs, is not
acceptable (aside from spam filtering).
Of course I can never prove anything along
these lines and any naming will only result
in creating life long enemies, and no benefit
to me of any kind.

You are right that misconfigurations and incompetence
could be confused with mailing list content
manipulation.  I have tried "directly contact the owner" too in
at least one case that I can think of and received no
response -- maybe the fellow was too busy, or sick
or dead or something (but still active on the same
mailing list, somehow).
   -- Aaron Watters

===
He's a humble man, with good reason.
   - Churchill, on a colleague
-- 
http://mail.python.org/mailman/listinfo/python-list


Firebird DBs use Kinterbasdb or sqlalchemy?

2009-10-30 Thread Jorge
Hi,
to access firebird data bases which shall I use kinterbasdb or sqlalchemy.

Yes I'm a newbie.

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


Re: Socket MUD client script

2009-10-30 Thread Terry Reedy

Zamnedix wrote:

I'm having trouble with this script I'm writing. I want it to connect
to a MUD, which it does fine, but afterwards it displays the greeting
and login prompt, and when I type in username the loop to receive and
then send seems to stop.


Here's my code:

#!/usr/bin/python
import socket
import sys
a = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = str(raw_input("HOST:PORT > "))
address = address.split(":")
a.connect((address[0], int(address[1])))
print "CONNECTED"
while 1:
   print a.recv(4079)
   print a.recv(4079)
   msg = str(raw_input("MSG > "))
   a.sendall(msg)

Here's what happens:
$ python connect.py
HOST:PORT > lofe.org:8000
CONNECTED


 ._
((big ascii art greeting, staff info and stuff))

Enter your character's name, or type new:
MSG > Xeythos

la la la la la la

^CTraceback (most recent call last):
  File "connect.py", line 18, in ?
print a.recv(4079)
KeyboardInterrupt
$



Also, I have to receive twice to get the whole greeting, and it comes
really slowly in two pieces.
I've looked around the internet for a good tutorial on python and
sockets but haven't really found anything. Am I using the wrong type
of socket, or what? Someone please help.


I suspect you are humg in the second a.recv since the response to the 
username is completely swallowed by the first one. That said, a mud 
client is basically a telnet client. So I recommend you use the 
telnetlib module. Telnet objects have a .read_until method, so your 
initial code wold mostly be replaced with


tn = telnetlib.Telnet(address[0], int(address[1], 30)
tn.real_until(b"or type new: ") #remove b prefix for 2.x

I recommend entering the loop until logged in. After that, you should 
get a consistent prompt to read up to.


Terry Jan Reedy



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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Richard Heathfield
In , Dann Corbit 
wrote:

> In article ,
> r...@see.sig.invalid says...
>> 
>> In , Dann
>> Corbit wrote:
>> 
>> 
>> > 
>> > You can read PDF with the ghostscript stuff or the free Adobe
>> > stuff.
>> 
>> Agreed. But why should you have to?
> 
> As opposed to...?

Something you can grep.



-- 
Richard Heathfield 
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Firebird DBs use Kinterbasdb or sqlalchemy?

2009-10-30 Thread Christian Heimes
Jorge wrote:
> Hi,
> to access firebird data bases which shall I use kinterbasdb or sqlalchemy.

You have to use kinterbasdb. SQLAlchemy is not a DBA but an ORM.

Christian

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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Robert Kern

On 2009-10-30 14:37 PM, Aaron Watters wrote:

On Oct 30, 12:51 pm, Robert Kern  wrote:

On 2009-10-30 11:31 AM, Aaron Watters wrote:


I know this may be due to simple laziness and negligence,
but in that case they should turn moderation off.


That's the funny thing about mailing list problems. If a misconfiguration means
people can't post to your, you don't hear from the people having problems. Try
emailing one of the project leaders directly (and politely!) to ask them to
check their moderation queue for your post. And check Spamhaus to see if your
mail host is on their list!


I don't want to say where I've had this problem,
because I don't want to offend anyone in particular
-- I'm just making a general observation.


No, you're not. You're making unsupported accusations of malfeasance.


I don't mean to accuse anyone of anything.


Attaching a question mark to the end doesn't make it any less of an accusation. 
Language is funny that way. C.f. the "Cavuto mark".



I just want to note that any manipulation of
list content, *if* it ever occurs, is not
acceptable (aside from spam filtering).


You need to have at least some evidence that it is occurring at all before 
moralizing about the hypothetical. When you do either of these things, it gives 
the rhetorical impression that you do have some support to believe that these 
things are actually happening when, in fact, you don't.



Of course I can never prove anything along
these lines and any naming will only result
in creating life long enemies, and no benefit
to me of any kind.


You know, if you hadn't leapt to paranoid conclusions in the first place, you 
could have named the lists that you were having problems with right here, and 
probably other people would be able to help you. No acrimony. No enemies. All 
benefit. This is why it is both irresponsible and entirely unhelpful to 
pontificate about malfeasance before collecting sufficient evidence.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-30 Thread Fabio Zadrozny
On Thu, Oct 29, 2009 at 6:48 PM, kj  wrote:
>
> How can one check that a Python script is lexically correct?
>
> As my Python apps grow in complexity and execution, I'm finding it
> more often the situation in which a program dies after a lengthy
> (i.e. expensive) run because the execution reaches, say, a typo.
> Of course, this typo needs to be fixed, but I'd like to find out
> about it before I waste hours on a run that is bound to fail.  Is
> there any way to do this?  I imagine the answer is no, because
> given Python's scoping rules, the interpreter can't know about
> these things at compile time, but I thought I'd ask.
>

Pydev has a code-analysis feature which works analyzing the code while
you're typing. See: http://pydev.org/manual_adv_code_analysis.html

Cheers,

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


datetime question

2009-10-30 Thread Victor Subervi
Hi;
I have this code:

today = datetime.date.today()
day = today.day
mo = today.month
yr = today.year

Works great. What I need to calculate is the length of days in the
given month. How do I do that?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Mensanator
On Oct 30, 2:07 pm, "Alf P. Steinbach"  wrote:
> * bartc:
>
>
>
> > Python has a lot of baggage which is OK if that's what's going to be
> > used, but otherwise is unnecessary confusion: where to put the program
> > code (typed in live or in a file, or some combination); whether to call
> > the file .py or .pyw; the difference between console and graphical
> > programs and so on.
>
> Hi.
>
> I forgot or decided not to really answer this part earlier, so...
>
> First of all, note that nothing of this is specific to Python.
>
> (1)
> "Where to put the program (typed in live or in a file)".
>
> This is common to all languages that offer interpreted execution.
>
> It is a feature, not a problem: in *addition* to putting your statements in a
> file for later execution, i.e. in addition to creating ordinary programs, you
> can explore the effects of statements by typing them at the interpreter.
>
> Storing the statements in a file is to create a "program" in the usual sense.
>
> Typing statements at the interpreter is just interactive use of the 
> interpreter.
> Depending on the phase of the moon, one's shoe size and other factors ,
> what's typed may be called a "program". But it's not a program in the usual
> sense, it's not a stored program: it's just interactive use of the 
> interpreter.

Unless you type something like:

>>> def Collatz(n):
while n>1:
if n%2 == 0:
n //= 2
else:
n = 3*n + 1
print(n)

which *IS* a stored program. It's just stored in RAM and will
be lost on shutdown if not specifically saved.

Even a single line is a "stored" program in the sense that you
can put your cursor on the line and hit return to repeat the
execution, so obviously, it's stored somewhere.

>
> Which is very convenient. :-)
>
> (2)
> "the difference between console and graphical programs"
>
> This is a Windows issue.
>
> Windows makes this differentiation.
>
> Thus, it's there *regardless* of programming language. And for example, it
> doesn't matter whether the language offers an interpreter. With C or C++ you
> tell the linker which subsystem you want. With Java you use 'java' or 'javaw' 
> to
> run the program as respectively console or GUI subsystem. With JScript and
> VBScript (script languages bundled with Windows) you use 'cscript' or 
> 'wscript'
> to run the program as respectively console or GUI subsystem. With Ruby you use
> 'ruby' or 'rubyw' to run the program. And so on  --  in the end it's always 
> the
> bottom level executing machine code program that is console or GUI subsystem.
>
> Do you think I should mention this in the text?
>
> It will make the text longer, and I worked hard to make ch 1 as *short* as
> possible! :-)
>
> (3)
> "Whether to call the file .py or .pyw"
>
> This is a feature, that you can relieve the user from the burden of choosing 
> the
> most sensible way to execute the file (the user doesn't have to choose whether
> to use a console or GUI subsystem version of the interpreter, and the user
> doesn't even have to know that there is an interpreter involved).
>
> It's a common convention for many languages (using those languages' filename
> extensions, of course), but it's not universal.
>
> Cheers & hth.,
>
> - Alf
>
> PS: and yes, programming *is* a bit complex! That's what also makes it fun. 
> 

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


Re: Strange behavior related to value / reference

2009-10-30 Thread Aahz
In article <626f24e5-4d8e-416c-b3ed-dc56a88dc...@s21g2000prm.googlegroups.com>,
Lambda   wrote:
>
>def matrix_power(m, n):
>  result = m[:]
>  print result is m

Use copy.deepcopy()
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library "support" propaganda lists?

2009-10-30 Thread Aahz
In article ,
Robert Kern   wrote:
>
>You know, if you hadn't leapt to paranoid conclusions in the first
>place, you could have named the lists that you were having problems
>with right here, and probably other people would be able to help
>you. No acrimony. No enemies. All benefit. This is why it is both
>irresponsible and entirely unhelpful to pontificate about malfeasance
>before collecting sufficient evidence.

Robert speaks for me
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can module determine its own path?

2009-10-30 Thread kj
In <7e456639-9dbb-41ba-ae36-042a034fa...@y32g2000prd.googlegroups.com> AK Eric 
 writes:


>> > How can a module determine the path of the file that defines it?
>> > (Note that this is, in the general case, different from sys.argv[0].)
>>
>> __file__

>Also:

>import inspect
>print inspect.getsourcefile(lambda:None)

Thank you both!

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-30 Thread Alf P. Steinbach

* Mensanator:

On Oct 30, 2:07 pm, "Alf P. Steinbach"  wrote:

* bartc:




Python has a lot of baggage which is OK if that's what's going to be
used, but otherwise is unnecessary confusion: where to put the program
code (typed in live or in a file, or some combination); whether to call
the file .py or .pyw; the difference between console and graphical
programs and so on.

Hi.

I forgot or decided not to really answer this part earlier, so...

First of all, note that nothing of this is specific to Python.

(1)
"Where to put the program (typed in live or in a file)".

This is common to all languages that offer interpreted execution.

It is a feature, not a problem: in *addition* to putting your statements in a
file for later execution, i.e. in addition to creating ordinary programs, you
can explore the effects of statements by typing them at the interpreter.

Storing the statements in a file is to create a "program" in the usual sense.

Typing statements at the interpreter is just interactive use of the interpreter.
Depending on the phase of the moon, one's shoe size and other factors ,
what's typed may be called a "program". But it's not a program in the usual
sense, it's not a stored program: it's just interactive use of the interpreter.


Unless you type something like:


def Collatz(n):

while n>1:
if n%2 == 0:
n //= 2
else:
n = 3*n + 1
print(n)

which *IS* a stored program. It's just stored in RAM and will
be lost on shutdown if not specifically saved.

Even a single line is a "stored" program in the sense that you
can put your cursor on the line and hit return to repeat the
execution, so obviously, it's stored somewhere.


Yes.

As you quoted me on:

Depending on the phase of the moon, one's shoe size and other factors , 
what's typed may be called a "program". But it's not a program in the usual 
sense, it's not a stored program: it's just interactive use of the interpreter.


However, at least for [comp.programming] the term "stored program" has a 
different often used meaning, the one that you employ above (which, by the way, 
was not von Neumann's invention, he was falsely credited with that idea).


And perhaps that needs to be pointed out when or if I discuss stored programs, 
like some kind of Wikipedia disambiguation page, so, thanks! :-)


But geneally getting into that kind of terminological fine distinction, such as 
here, what can be regarded as "stored", isn't really useful, though. It assumes 
an adversarial reading, which is not a useful assumption. And the only possible 
way out with that assumption is to define all relevant terms in a very technical 
way, which (1) leads to qualifications that end up being umpteen times longer 
than a simple statement of whatever one attempts to communicate (like, 
replicating all thousand+ pages of a technical language standard just to define 
the concept of "variable", which is silly), (2) leads to ungrokkable lawyereese 
language, absolutely not suitable for novices, and (3) in practice never 
actually accomplishes the purpose of ironclad definitions, as evidenced by e.g. 
"variable" in C++ still being subject to some disagreement over what it is...


I'm very very happy that most comments about perceived defects in the text and 
in my responses here, have only disagreements over terminology. I had expected a 
slew of errors being pointed out, since I'm new to Python.  Still, I'm fairly 
sure that there actually *is* such a slew of errors, because there is in any 
text of more than ten pages or so; any good book has a volumious errata list...



Cheers, & thanks,

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


Re: datetime question

2009-10-30 Thread Rami Chowdhury
On Fri, 30 Oct 2009 13:03:32 -0700, Victor Subervi  
 wrote:



Hi;
I have this code:

today = datetime.date.today()
day = today.day
mo = today.month
yr = today.year

Works great. What I need to calculate is the length of days in the
given month. How do I do that?
TIA,
Victor



Off the top of my head:
You could calculate it fairly easily by subtracting a datetime object  
representing the first of this month from a datetime object representing  
the first of next month; that'd give you a timedelta object with the  
number of days.


Alternatively, of course, you could look up the number of days in the  
current month using the calendar module ;-)




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-30 Thread Dotan Cohen
>> It is clear and obvious. But it has the "template engine" duplicating
>> a function that Python has built in. My goal is to learn reusable
>> Python (reusable for non-web projects). My goal is not to find the
>> quickest way to a website.
>
> Please correct me if I'm wrong, but you did learn HTML, CSS and SQL, didn't
> you ? How do any of these languages relates to Python ?-)
>

HTML and CSS yes, but just enough SQL to fake it. None of those
languages relate to Python, each language performs a different
function. However, the template language looks completely redundant as
it duplicates functionality of the language that I intend to learn.


>> won't help me learn Python any more than learning PHP would.
>> So going from PHP to Django is pointless.
>
> Please get out of the "server page" mindset. Templates are just that :
> templates. Period. You don't use templates to write your *applicative* code.
>

I understand that.


>> I meant reusable knowledge, not reusable code.
>
> There's very few "reusable knowledge" to be gained from templating code
> anyway- even if using a "python-based" template system like Mako. Unless you
> think doing a loop or a conditional are things you need to learn ?-)
>

I would say that one needs to know how to do a for loop in Python, in
order to program in Python!


>>> Then use Mako - it uses plain Python to manage the presentation logic.
>>
>> Now we're talking! I will look further into Pylons and Mako.
>
> Beware that the above comments about how less there's to learn from the
> templates code still apply - basically, the "programming" part of a template
> is restricted to simple branching, iterations, and variable substitution.
>

I see.


>> I don't expect to ever have a "team",
>
> Possibly not. But as strange as it migh be, there are other peoples that do,
> and most of these frameworks are written by professional web programmers.
>

I therefore counter that these frameworks were designed for people
unlike myself, which easily explains my resistance to them.


>> The point is that I want to use only _Python_ features, not
>> Django/Mako/whatever features.
>
> If so, you shouldn't use *any* third-part libs, and possibly not even the
> stdlib.
>

THat is going just a bit far!


> More seriously : reinventing the wheel - unless for educational purposes -
> is not really pythonic. If what you want is to learn, write your own
> framework, template system, form handling etc... You'll very certainly find
> out that they suck big time compared to existing projects, but you'll learn
> _at least_ one thing: that writing a sensible non-trivial framework or lib
> is *hard*.
>

Actually, I konw just how hard it is. PHP and some C in university.


>> However I am aware that some things I
>> should not touch for security reasons. That is why I want a framework:
>> to provide the security aspects of things like converting UTF-8,
>
> from what and to what ?-)
>

Into and out of the database.


> string / unicode encoding and decoding is a builtin Python feature.
>

I know, but I need to play with it a bit before I become comfortable
with how it is handled.


>> database escaping,
>
> Already provided by any DB-API compliant connector, at least if correctly
> used.
>
> Now there's *much* more in security (specially when doing web programming)
> than this...

Of course. But these are the relevant issues for Python.


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-30 Thread Dotan Cohen
> I took a look a both yesterday. They are both generic text templating
> systems that seem to pretty much do the same thing. I suspect you will
> prefer Mako since it avoids duplicating Python's comtrol structures. But I
> think it worthwhile to look at both anyway since doing so will help to
> separate the concepts from the particular implementations.
>
> My take on them is this: when text mixes code that is meant to be
> interpreted and text data meant to be taken literally, some means must be
> devised to distinguish the two. In programs files, the code is left unquoted
> and the text data is quoted. In template files, the marking is reversed: the
> literal text is left unquoted and the code *is* quoted. In Mako, expressions
> are quoted with braces ({...}), single statements with '%' prefix, and
> multiple statements as well as Mako tags with <% ...>.
>

Thanks, Terry, that should save me some time.


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __eq__() inconvenience when subclassing set

2009-10-30 Thread Jess Austin
On Oct 29, 10:41 pm, "Gabriel Genellina" 
wrote:
> We know the last test fails because the == logic fails to recognize mySet  
> (on the right side) as a "more specialized" object than frozenset (on the  
> left side), because set and frozenset don't have a common base type  
> (although they share a lot of implementation)
>
> I think the only way would require modifying tp_richcompare of  
> set/frozenset objects, so it is aware of subclasses on the right side.  
> Currently, frozenset() == mySet() effectively ignores the fact that mySet  
> is a subclass of set.

I don't think even that would work.  By the time set_richcompare() is
called (incidentally, it's used for both set and frozenset), it's too
late.  That function is not responsible for calling the subclass's
method.  It does call PyAnySet_Check(), but only to short-circuit
equality and inequality for non-set objects.  I believe that something
higher-level in the interpreter decides to call the right-side type's
method because it's a subclass of the left-side type, but I'm not
familiar enough with the code to know where that happens.  It may be
best not to sully such generalized code with a special case for
this.

I may do some experiments with bytes, str, and unicode, since that
seems to be an analogous case.  There is a basestring type, but at
this point I don't know that it really helps with anything.

cheers,
Jess
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-30 Thread Robert Kern

On 2009-10-30 15:55 PM, Dotan Cohen wrote:

It is clear and obvious. But it has the "template engine" duplicating
a function that Python has built in. My goal is to learn reusable
Python (reusable for non-web projects). My goal is not to find the
quickest way to a website.


Please correct me if I'm wrong, but you did learn HTML, CSS and SQL, didn't
you ? How do any of these languages relates to Python ?-)


HTML and CSS yes, but just enough SQL to fake it. None of those
languages relate to Python, each language performs a different
function. However, the template language looks completely redundant as
it duplicates functionality of the language that I intend to learn.


Templating languages serve a different, highly specialized purpose. They may 
have similar flow constructs, but the context and specializations matter a lot. 
Use the right language for the job. Sometimes the job is a weird mix of concerns 
and requires a weird mix of constructs to be convenient. If you're writing web 
apps, you should learn a templating language. If you're primarily concerned with 
learning Python and nothing else, you should find a different kind of project.


But if you insist, you may be interested in Breve:

  http://pypi.python.org/pypi/Breve/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Unicode again ... default codec ...

2009-10-30 Thread Gabriel Genellina

En Fri, 30 Oct 2009 13:40:14 -0300, zooko  escribió:

On Oct 20, 9:50 pm, "Gabriel Genellina" 
wrote:


DON'T do that. Really. Changing the default encoding is a horrible,
horrible hack and causes a lot of problems.


I'm not convinced.  I've read all of the posts and web pages and blog
entries decrying this practice over the last several years, but as far
as I can tell the actual harm that can result is limited (as long as
you set it to utf-8) and the practical benefits are substantial.  This
is a pattern that I have no problem using:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

The reason this doesn't cause too much harm is that anything that
would have worked with the original default encoding ('ascii') will
also work with the new utf-8 default encoding.


Wrong. Dictionaries may start behaving incorrectly, by example. Normally,  
two keys that compare equal cannot coexist in the same dictionary:


py> 1 == 1.0
True
py> d = {}
py> d[1] = '*'
py> d[1.0]
'*'
py> d[1.0] = '$'
py> d
{1: '$'}

1 and 1.0 are the same key, as far as the dictionary is concerned. For  
this to work, both keys must have the same hash:


py> hash(1) == hash(1.0)
True

Now, let's set the default encoding to utf-8:

py> import sys
py> reload(sys)

py> sys.setdefaultencoding('utf-8')
py> x = u'á'
py> y = u'á'.encode('utf-8')
py> x
u'\xe1'
py> y
'\xc3\xa1'

(same as y='á' if the source encoding is set to utf-8, but I don't want to  
depend on that). Just to be sure we're dealing with the right character:


py> import unicodedata
py> unicodedata.name(x)
'LATIN SMALL LETTER A WITH ACUTE'
py> unicodedata.name(y.decode('utf-8'))
'LATIN SMALL LETTER A WITH ACUTE'

Now, we can see that both x and y are equal:

py> x == y
True

x is an accented a, y is the same thing encoded using the default  
encoding, both are equal. Fine. Now create a dictionary:


py> d = {}
py> d[x] = '*'
py> d[x]
'*'
py> x in d
True
py> y in d
False# ???
py> d[y] = 2
py> d
{u'\xe1': '*', '\xc3\xa1': 2} # 

Since x==y, one should expect a single entry in the dictionary - but we  
got two. That's because:


py> x == y
True
py> hash(x) == hash(y)
False

and this must *not* happen according to  
http://docs.python.org/reference/datamodel.html#object.__hash__
"The only required property is that objects which compare equal have the  
same hash value"
Considering that dictionaries in Python are used almost everywhere,  
breaking this basic asumption is a really bad problem.


Of course, all of this applies to Python 2.x; in Python 3.0 the problem  
was solved differently; strings are unicode by default, and the default  
encoding IS utf-8.



As far as I've seen
from the aforementioned mailing list threads and blog posts and so on,
the worst thing that has ever happened as a result of this technique
is that something works for you but fails for someone else who doesn't
have this stanza.  (http://tarekziade.wordpress.com/2008/01/08/
syssetdefaultencoding-is-evil/ .)  That's bad, but probably just
including this stanza at the top of the file that you are sharing with
that other person instead of doing it in a sitecustomize.py file will
avoid that problem.


And then you break all other libraries that the program is using,  
including the Python standard library, because the default encoding is a  
global setting. What if another library decides to use latin-1 as the  
default encoding, using the same trick? Latest one wins...


You said "the practical benefits are substantial" but I, for myself,  
cannot see any benefit. Perhaps if you post your real problems, someone  
can find the solution.
The right way is to fix your program to do the right thing, not to hide  
the bugs under the rug.


--
Gabriel Genellina

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


Re: Python library "support" propaganda lists?

2009-10-30 Thread Ben Finney
Ulrich Eckhardt  writes:

> Aaron Watters wrote:
> > I don't know why this happens, but if people are using their
> > "support" forums
>
> And now it's a forum, not a mailinglist, and more than one of them?

I'm not impressed by the attempt to hijack the word “forum”. A mailing
list, a Usenet group, an IRC channel — all these are discussion forums,
now just as much as before crappy web messaging applications.

There's nothing wrong with using “discussion forum” or “support forum”
to mean whatever medium and location is used for discussion/support.

-- 
 \ “We are all agreed that your theory is crazy. The question that |
  `\  divides us is whether it is crazy enough to have a chance of |
_o__)being correct.” —Niels Bohr (to Wolfgang Pauli), 1958 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-30 Thread erob
On Oct 28, 5:16 am, "Diez B. Roggisch"  wrote:
> Dotan Cohen schrieb:
>
>
>
> >> While I know that to be true in the general sense, from what I've
> >> looked at Django and other frameworks it seems that the web frameworks
> >> push the coder to use templates, not letting him near the HTML.
>
> >> For instance, I was looking for a class / framework that provided a
> >> proven method of decoding cookies (setting them is no problem),
> >> decoding POST and GET variables, escaping variables for safe entry
> >> into MySQL, and other things. Django and the other frameworks seem to
> >> force the user to use templates. I just want the functions, and to
> >> print the HTML as stdout to the  browser making the request. I had to
> >> settle on PHP to do this, which admittedly is what PHP was invented to
> >> do. However, for obvious reasons, I would have prefered to code in
> >> Python. In fact, I still would.
>
> > I should probably expand on this:
>
> > How can I get an array with all the GET variables in Python?
> > How can I get an array with all the POST variables in Python?
> > How can I get an array with all the COOKIE variables in Python?
> > How can I get the request URI path (everything after
> >http://[www.?]example.com/)?
>
> > That's all I want: no templates and nothing between me and the HTML.
> > The HTTP headers I can output to stdout myself as well.
>
> Again: if you insist on doing everything yourself - then of course any
> library or framework isn't for you.
>
> But then do you deal with headers correctly? Do you respect character
> encodings? Form-encodings? Is your generated HTML valid? Are
> timestamp-formats generated according to RFCs for your cookies? Do you
> parse content negotiation headers?
>
> I think you underestimate the task it is to make a webapplication good.
> And even if not, what you will do is ... code your own webframework.
> Because there is a lot of boilerplate otherwis. If that's a
> learning-experience your after, fine.
>
> Besides, yes, you can get all these things nonetheless. You just don't
> need them most of the time.
>
> And at least pylons/TG2 lets you return whatever you want instead, as a
> string. Not via "print" though - which is simply only for CGI, and no
> other means (e.g. mod_wsgi) of python-web-programming.
>
> Diez

notmm uses Python 2.6 and will probably work just fine with Python
3000.


Cheers,

Etienne

P.S - We all don't think in the same box.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2009-10-30 Thread Ben Finney
Victor Subervi  writes:

> What I need to calculate is the length of days in the given month. How
> do I do that?

The ‘datetime’ module focusses on individual date+time values (and the
periods between them, with the ‘timedelta’ type).

For querying the properties of the calendar, use the ‘calendar’ module.

Yes, it would be nice if the ‘time’, ‘datetime’, and ‘calendar’ modules
were all much more unified and consumed a common set of primitive
date+time types. It's a wart, and fixing it would (unfortunately)
probably require backward-incompatible API changes.

-- 
 \“Simplicity is prerequisite for reliability.” —Edsger W. |
  `\  Dijkstra |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are *.pyd's universal?

2009-10-30 Thread Carl Banks
On Oct 30, 8:43 am, Dave Angel  wrote:
> And I'm guessing that CPython searches down sys.path, and when it finds
> the module, gives a full path to LoadLibrary(), in which case the DLL
> search path is moot.

It's not Python that's the issue.  The issue is that if you have a
module with a .dll extension, other programs could accidentally try to
load that module instead of the intended dll, if the module is in the
current directory or system path.  Modules will sometimes find
themselves on the path in Windows, so the fact that Windows performs a
library search on the path is quite significant.


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


Re: Web development with Python 3.1

2009-10-30 Thread erob
On Oct 30, 7:01 pm, erob  wrote:
> On Oct 28, 5:16 am, "Diez B. Roggisch"  wrote:
>
>
>
> > Dotan Cohen schrieb:
>
> > >> While I know that to be true in the general sense, from what I've
> > >> looked at Django and other frameworks it seems that the web frameworks
> > >> push the coder to use templates, not letting him near the HTML.
>
> > >> For instance, I was looking for a class / framework that provided a
> > >> proven method of decoding cookies (setting them is no problem),
> > >> decoding POST and GET variables, escaping variables for safe entry
> > >> into MySQL, and other things. Django and the other frameworks seem to
> > >> force the user to use templates. I just want the functions, and to
> > >> print the HTML as stdout to the  browser making the request. I had to
> > >> settle on PHP to do this, which admittedly is what PHP was invented to
> > >> do. However, for obvious reasons, I would have prefered to code in
> > >> Python. In fact, I still would.
>
> > > I should probably expand on this:
>
> > > How can I get an array with all the GET variables in Python?
> > > How can I get an array with all the POST variables in Python?
> > > How can I get an array with all the COOKIE variables in Python?
> > > How can I get the request URI path (everything after
> > >http://[www.?]example.com/)?
>
> > > That's all I want: no templates and nothing between me and the HTML.
> > > The HTTP headers I can output to stdout myself as well.
>
> > Again: if you insist on doing everything yourself - then of course any
> > library or framework isn't for you.
>
> > But then do you deal with headers correctly? Do you respect character
> > encodings? Form-encodings? Is your generated HTML valid? Are
> > timestamp-formats generated according to RFCs for your cookies? Do you
> > parse content negotiation headers?
>
> > I think you underestimate the task it is to make a webapplication good.
> > And even if not, what you will do is ... code your own webframework.
> > Because there is a lot of boilerplate otherwis. If that's a
> > learning-experience your after, fine.
>
> > Besides, yes, you can get all these things nonetheless. You just don't
> > need them most of the time.
>
> > And at least pylons/TG2 lets you return whatever you want instead, as a
> > string. Not via "print" though - which is simply only for CGI, and no
> > other means (e.g. mod_wsgi) of python-web-programming.
>
> > Diez
>
> notmm uses Python 2.6 and will probably work just fine with Python
> 3000.
>
> Cheers,
>
> Etienne
>
> P.S - We all don't think in the same box.

"I am free, no matter what rules surround me. If I find them
tolerable, I tolerate them; if I find them too obnoxious, I break
them. I am free because I know that I alone am morally responsible for
everything I do." -- Robert A. Heinlein
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Publishing new release on PyPI: How?

2009-10-30 Thread Martin v. Löwis
> Well, maybe I'm completely blind but I can't find a way to add a new release
> to PyPI index for python-ldap, not just a new file to an existing release
> version.

I recommend to run "python setup.py register", rather than using the
HTML UI.

> I'm the project owner and I did it several times in the past. But I
> simply can't find the button where to add another release. Was there a change
> in the UI recently?

No - just follow the link "Package submission".

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


Re: Python 2.6 Global Variables

2009-10-30 Thread Aahz
In article <888b5e8f-1be5-4040-bc7a-45c2e1695...@d9g2000prh.googlegroups.com>,
AK Eric   wrote:
>>
>> 2/ in Python, "global" really means "module-level" - there's nothing
>> like a "true" global namespace.
>
>Isn't that __main__?
>
>import __main__
>__main__.foo = "asdfasdf"
>
>print foo
># asdfasdf

Actually, you're almost right, but it's an even WORSE idea than you
thought:

import __builtin__
__builtin__.foo = 'bar'

Kids, do *NOT* do this at home!  The reasons why are left as an exercise
for the reader.  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can module determine its own path?

2009-10-30 Thread Stef Mientki

Robert Kern wrote:

On 2009-10-30 12:19 PM, kj wrote:

How can a module determine the path of the file that defines it?
(Note that this is, in the general case, different from sys.argv[0].)


__file__


but for modules launched with execfile, __file__ doesn't exists.

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


Re: OT: DARPA red balloon challenge

2009-10-30 Thread Albert Hopkins
On Thu, 2009-10-29 at 20:27 -0700, Adam N wrote:
[...]
> On December 5, DARPA will raise 10 red weather balloons somewhere in
> the US.  The first person to get the location of all 10 balloons and
> submit them will be given $40k. 

Hasn't the U.S. had enough weather balloon-related publicity stunts?

Well, hopefully this one won't turn into 10 "missing" little boys :-)

-a


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


Re: How can module determine its own path?

2009-10-30 Thread Robert Kern

On 2009-10-30 18:40 PM, Stef Mientki wrote:

Robert Kern wrote:

On 2009-10-30 12:19 PM, kj wrote:

How can a module determine the path of the file that defines it?
(Note that this is, in the general case, different from sys.argv[0].)


__file__


but for modules launched with execfile, __file__ doesn't exists.


Modules launched from execfile() using a properly initialized namespace dict do.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


  1   2   >