Re: Simple audio library

2012-12-27 Thread Abhas Bhattacharya
On Wednesday, 26 December 2012 09:46:10 UTC+5:30, Xantipius  wrote:
> On Dec 26, 5:07 am, Abhas Bhattacharya 
> 
> wrote:
> 
> > Which simple python audio library will you suggest for low level audio 
> > creation (for eg I want to create tones of different intensities and 
> > frequency continously and then record the whole sequence)? (Although a 
> > minimal audio library is ok, it would be better if you can tell me about a 
> > full-fledged audio library along with low level access)
> 
> 
> 
> Check this list of packages: http://pypi.python.org/pypi

Yes, I have seen a lot of them, that's why I asked some suggestion from someone 
who has used them/ has knowledge about them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Abhas Bhattacharya
On Thursday, 27 December 2012 13:22:45 UTC+5:30, Chris Angelico  wrote:
> On Thu, Dec 27, 2012 at 6:46 PM, Abhas Bhattacharya
> 
>  wrote:
> 
> > [ a whole lot of double-spaced quoted text - please trim it ]
> 
> > If i call one() and two() respectively, i would like to see "one" and "two".
> 
> 
> 
> That completely goes against your idea of knowing at compile-time,
> 
> because the name "two" isn't anywhere around at that time.
> 
> 
> 
> There's no way to know what name was used to look something up. It
> 
> might not even have a name - the called function could well have been
> 
> returned from another function:
> 
> 
> 
> # foo.py
> 
> def indirection():
> 
>   return lambda: print
> 
> 
> 
> # bar.py
> 
> import foo
> 
> foo.indirection()()("Hello, world!")
> 
> 
> 
> What are the names of all the functions called here?
> 
> 
> 
> ChrisA

Yes, I get it that it may not be possible in complex cases (mostly using lambda 
functions). But in the simple case I mentioned, is it possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Chris Angelico
On Thu, Dec 27, 2012 at 6:46 PM, Abhas Bhattacharya
 wrote:
> [ a whole lot of double-spaced quoted text - please trim it ]
> If i call one() and two() respectively, i would like to see "one" and "two".

That completely goes against your idea of knowing at compile-time,
because the name "two" isn't anywhere around at that time.

There's no way to know what name was used to look something up. It
might not even have a name - the called function could well have been
returned from another function:

# foo.py
def indirection():
  return lambda: print

# bar.py
import foo
foo.indirection()()("Hello, world!")

What are the names of all the functions called here?

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Mitya Sirenef

On 12/27/2012 02:45 AM, Abhas Bhattacharya wrote:

On Thursday, 27 December 2012 10:22:15 UTC+5:30, Tim Roberts  wrote:

Abhas Bhattacharya  wrote:


While I am defining a function, how can I access the name (separately as
string as well as object) of the function without explicitly naming
it(hard-coding the name)?
For eg. I am writing like:
def abc():
#how do i access the function abc here without hard-coding the name?



Why?  Of what value would that be?



Note that I'm not merely being obstructionist here.  What you're asking

here is not something that a Python programmer would normally ask.  The

compiled code in a function, for example, exists as an object without a

name.  That unnamed object can be bound to one or more function names, but

the code doesn't know that.  Example:



def one():

 print( "Here's one" )



two = one



That creates one function object, bound to two names.  What name would you

expect to grab inside the function?



Even more obscure:



two = lamba : "one"

one = two



Which one of these is the "name" of the function?

--

Tim Roberts, [email protected]

Providenza & Boekelheide, Inc.

It is of quite value to me.
Because I have this situation:
I have used a dictionary with "function_name":value pair in the top of the 
code. Now when some function is called, I need to print the value assigned to its name in 
the dictionary (the functions are defined after the dictionary). Now there is only one 
bad way-around for me: I need to hard-code the name in the function like this:
def function_name():
 print(dict_name.get("function_name"))
but ofcourse it is a bad thing to do because I have a lot of this type of  
functions. It would be better if I can can use the same code for all of them, 
because they are all essentially doing the same thing.

Now, for your questions:
If i call one() and two() respectively, i would like to see "one" and "two".
I dont have much knowledge of lambda functions, neither am i going to use them, 
so that's something I cant answer.


How about defining a function that prints value and then calls a function?

def call(func_name):
  print(mydict[func_name])
  globals()[func_name]()


You could also define a custom class that does the same thing on attribute
lookup and do something like Call.func_name() .

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Abhas Bhattacharya
On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:
> 
> How about defining a function that prints value and then calls a function?
> 
> 
> 
> def call(func_name):
> 
>print(mydict[func_name])
> 
>globals()[func_name]()
> 
> 
> 
> 
> 
> You could also define a custom class that does the same thing on attribute
> 
> lookup and do something like Call.func_name() .
> 
> 
> 
>   -m
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/

Can you explain me what this means?
globals()[func_name]()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Chris Rebert
On Dec 25, 2012 6:06 PM, "Abhas Bhattacharya" 
wrote:
>
> While I am defining a function, how can I access the name (separately as
string as well as object) of the function without explicitly naming
it(hard-coding the name)?
> For eg. I am writing like:
> def abc():
> #how do i access the function abc here without hard-coding the name?

Not possible per se without resorting to sys._getframe() or similar hackery.
A simple+elegant way to do this would require PEP 3130 (
http://www.python.org/dev/peps/pep-3130/ ) or similar, but that particular
proposal got rejected.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Abhas Bhattacharya
On Thursday, 27 December 2012 13:56:24 UTC+5:30, Chris Rebert  wrote:
> On Dec 25, 2012 6:06 PM, "Abhas Bhattacharya"  wrote:
> 
> >
> 
> > While I am defining a function, how can I access the name (separately as 
> > string as well as object) of the function without explicitly naming 
> > it(hard-coding the name)?
> 
> > For eg. I am writing like:
> 
> > def abc():
> 
> >     #how do i access the function abc here without hard-coding the name?
> 
> Not possible per se without resorting to sys._getframe() or similar hackery.
> 
> A simple+elegant way to do this would require PEP 3130 
> (http://www.python.org/dev/peps/pep-3130/ ) or similar, but that particular 
> proposal got rejected.

Thanks for telling that. I thought that there is a direct way, and now you have 
confirmed that there isn't. So, as I can see, Mitya's code can be a perfect 
way-around, although it will require another function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Chris Rebert
On Dec 26, 2012 11:55 PM, "Abhas Bhattacharya" 
wrote:
>
> On Thursday, 27 December 2012 10:22:15 UTC+5:30, Tim Roberts  wrote:
> > Abhas Bhattacharya  wrote:
> >
[Oh god please stop/avoid using Google Groups with its godawful
reply-quoting style that adds excessive blank lines]
> > >While I am defining a function, how can I access the name (separately
as
> > >string as well as object) of the function without explicitly naming
> > >it(hard-coding the name)?
> > >For eg. I am writing like:
> >
> > >def abc():
> > >#how do i access the function abc here without hard-coding the
name?
> >
> > Why?  Of what value would that be?

> Because I have this situation:
> I have used a dictionary with "function_name":value pair in the top of
the code. Now when some function is called, I need to print the value
assigned to its name in the dictionary (the functions are defined after the
dictionary). Now there is only one bad way-around for me: I need to
hard-code the name in the function like this:
> def function_name():
> print(dict_name.get("function_name"))
> but ofcourse it is a bad thing to do because I have a lot of this type of
 functions. It would be better if I can can use the same code for all of
them, because they are all essentially doing the same thing.

I agree with the general outline of Mitya's suggestion, i.e. refactor the
"print the associated value" step into a separate function, thus obviating
the self-reference issue; it'd be bad to repeat that code in each function
anyway.

Anyhow, here's a simple variation that exploits decorators (because they're
generally awesome & one of my favorite features):

def printing_name_beforehand(func):
def wrapper(*args, **kwargs):
print(the_dict.get(func.__name__))
return func(*args, **kwargs)
return wrapper

Usage:

@printing_name_beforehand
def some_func(...):
# whatever

(Forgive me if there are typos; composing this reply on a tablet is
cumbersome.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Mitya Sirenef

On 12/27/2012 03:26 AM, Abhas Bhattacharya wrote:

On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:

How about defining a function that prints value and then calls a function?



def call(func_name):

print(mydict[func_name])

globals()[func_name]()





You could also define a custom class that does the same thing on attribute

lookup and do something like Call.func_name() .



   -m



--

Lark's Tongue Guide to Python: http://lightbird.net/larks/

Can you explain me what this means?
globals()[func_name]()


globals() is a globals dictionary that maps function
names to function objects (along with other things),
so we get the function object by name and then
run it.

 -m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


pickle module doens't work

2012-12-27 Thread Omer Korat
Hi all,

I'm working on a project in Python 2.7. I have a few large objects, and I want 
to save them for later use, so that it will be possible to load them whole from 
a file, instead of creating them every time anew. It is critical that they be  
transportable between platforms. Problem is, when I use the 2.7 pickle module, 
all I get is a file containing a string representing the commands used to 
create the object. But there's nothing I can do with this string, because it 
only contains information about the object's module, class and parameters. And 
that way, they aren't transportable.
In python 3.3 this problem is solved, and the pickle.dump generates a series of 
bytes, which can be loaded in any other module independently of anything. But 
in my project, I need NLTK 2.0, which is written in python 2.7...

Anybody has suggestions? Maybe there is a way to use pickle so that it yields 
the results I need? Or is there any other module that does pickle's job? Or 
perhaps there is a way to mechanically translate between python versions, so 
I'll be able to use pickle from 3.3 inside an application written in 2.7? Or 
perhaps somebody knows of a way to embed a piece of 3.3 code inside a 2.7 
program?

It can't be I'm the only one who wants to save python objects for later use! 
There must be a standard method to do this, but I couldn't find any on the web!
If someone can solve this for me I'll be so grateful.
-- 
http://mail.python.org/mailman/listinfo/python-list


A strange questions, about socket.py

2012-12-27 Thread Chaojie He
Code:
import urllib2 , socks , socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,'127.0.0.1',1080,True,None,None)
socket.socket = socks.socksocket
result = urllib2.urlopen("http://www.youtube.com",timeout=5)

If in the operation process of the server disconnected, the script will enter 
circulation state.

Log(The last part):
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
socks.py(140):  while len(data) < bytes:
socks.py(141):  data = data + self.recv(bytes-len(data))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A strange questions, about socket.py

2012-12-27 Thread Chaojie He
I made a mistake,Sorry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Steven D'Aprano
On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:

>> > two = lamba : "one"
>> > one = two
>> 
>> > Which one of these is the "name" of the function?
[...]
> If i call one() and two() respectively, i would like to see "one" and
> "two".

I'm afraid you're going to be disappointed. There is no possible way for 
one() and two() as shown above to report different names, because they 
are the same function object.

py> two = lambda : "one"
py> one = two
py> one is two
True
py> one, two
( at 0xb7abd92c>,  at 0xb7abd92c>)



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


Re: pickle module doens't work

2012-12-27 Thread Peter Otten
Omer Korat wrote:

> I'm working on a project in Python 2.7. I have a few large objects, and I
> want to save them for later use, so that it will be possible to load them
> whole from a file, instead of creating them every time anew. It is
> critical that they be  transportable between platforms. Problem is, when I
> use the 2.7 pickle module, all I get is a file containing a string
> representing the commands used to create the object. But there's nothing I
> can do with this string, because it only contains information about the
> object's module, class and parameters. And that way, they aren't
> transportable. In python 3.3 this problem is solved, and the pickle.dump
> generates a series of bytes, which can be loaded in any other module
> independently of anything. But in my project, I need NLTK 2.0, which is
> written in python 2.7...
> 
> Anybody has suggestions? Maybe there is a way to use pickle so that it
> yields the results I need? Or is there any other module that does pickle's
> job? Or perhaps there is a way to mechanically translate between python
> versions, so I'll be able to use pickle from 3.3 inside an application
> written in 2.7? Or perhaps somebody knows of a way to embed a piece of 3.3
> code inside a 2.7 program?
> 
> It can't be I'm the only one who wants to save python objects for later
> use! There must be a standard method to do this, but I couldn't find any
> on the web! If someone can solve this for me I'll be so grateful.

Pickling works the same way in Python 2 and Python 3. For classes only the 
names are dumped, so you need (the same version of) NLTK on the source and 
the destination platform.

If you can provide a short demo of what works in Python 3 but fails in 
Python 2 we may be able to find the actual problem or misunderstanding.
Maybe it is just that different protocols are used by default? I so, try

with open(filename, "wb") as f:
pickle.dump(f, your_data, protocol=pickle.HIGHEST_PROTOCOL)

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


Re: pickle module doens't work

2012-12-27 Thread Omer Korat
You're probably right in general, for me the 3.3 and 2.7 pickles definitely 
don't work the same:

3.3:
>>> type(pickle.dumps(1))


2.7:
>>> type(pickle.dumps(1, pickle.HIGHEST_PROTOCOL))



As you can see, in 2.7 when I try to dump something, I get useless string. Look 
what I gen when I dump an NLTK object such as the sent_tokenize function:

'\x80\x02cnltk.tokenize\nsent_tokenize\ng\x00'

Now, this is useless. If I try to load it on a platform without NLTK installed 
on it, I get:

ImportError: No module named 'nltk'

So it means the actual sent_tokenizer wasn't saved. Just it's module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2012-12-27 Thread Dave Angel
On 12/27/2012 07:05 AM, Omer Korat wrote:
> You're probably right in general, for me the 3.3 and 2.7 pickles definitely 
> don't work the same:
>
> 3.3:
 type(pickle.dumps(1))
> 
>
> 2.7:
 type(pickle.dumps(1, pickle.HIGHEST_PROTOCOL))
> 

That is the same. In 2.7, str is made up of bytes, while in 3.3, str
would be unicode. So 'bytes' is the 3.3 equivalent of str.

>
> As you can see, in 2.7 when I try to dump something, I get useless string. 
> Look what I gen when I dump an NLTK object such as the sent_tokenize function:
>
> '\x80\x02cnltk.tokenize\nsent_tokenize\ng\x00'
>
> Now, this is useless. If I try to load it on a platform without NLTK 
> installed on it, I get:
>
> ImportError: No module named 'nltk'
>
> So it means the actual sent_tokenizer wasn't saved. Just it's module.

As Peter Otten has already pointed out, that's how pickle works. It does
not somehow encode the whole module into the pickle, only enough
information to recreate the particular objects you're saving, *using*
the same modules. I don't know of any method of avoiding the destination
machine needing nltk, regardless of Python version.

Perhaps you'd rather see it in the Python docs.

http://docs.python.org/2/library/pickle.html
http://docs.python.org/3.3/library/pickle.html

pickle can
save and restore class instances transparently, however the class
definition must be importable and live in the same module as when the
object was stored.
and
Similarly, when class instances are pickled, their class’s code and data
are not pickled along with them. Only the instance data are pickled.
This is done on purpose, so you can fix bugs in a class or add methods
to the class and still load objects that were created with an earlier
version of the class.

-- 

DaveA

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


Re: [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-27 Thread Chris Angelico
On Thu, Dec 27, 2012 at 5:50 PM, Ranting Rick
 wrote:
> Every keyword, syntactical structure, style, etc, etc, should be based
> on logical foundations; not adolescent fads or propagating more
> idiotic cultural traditions. You piss and moan about language X and
> how asinine the language is, them you go and repeat the same stupid
> mistakes simply because you don't want to "rock the boat"?!

Rick, ever heard of the ELIZA Effect?

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Steven D'Aprano
On Tue, 25 Dec 2012 22:11:28 -0500, Roy Smith wrote:

> I've only ever wanted the name.  If you need the actual function object,
> I suppose you might eval() the name, or something like that.

Oh look, I found a peanut! Let me get a 50lb sledgehammer to crack it 
open!

*wink*

Please do not use eval to retrieve the function object. It's slow, 
overkill, a bad habit to get into, and a security risk if the name you 
are eval'ing comes from an untrusted source.

Instead, look the name up in globals() or locals():


py> def spam():
... return "NOBODY expects the Spanish Inquisition!"
...
py> name = "spam"
py> func = globals()[name]
py> func()
'NOBODY expects the Spanish Inquisition!'



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


Re: pickle module doens't work

2012-12-27 Thread Omer Korat
I see. In that case, all I have to do is make sure NLTK is available when I 
load the pickled objects. That pretty much solves my problem. Thanks!
So it means pickle doesn't ever save the object's values, only how it was 
created? 

Say I have a large object that requires a lot of time to train on data. It 
means pickle doesn't save its values, so you have to train it every time anew? 
Is there no way to save its trained values?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2012-12-27 Thread Chris Angelico
On Fri, Dec 28, 2012 at 12:16 AM, Omer Korat
 wrote:
> I see. In that case, all I have to do is make sure NLTK is available when I 
> load the pickled objects. That pretty much solves my problem. Thanks!
> So it means pickle doesn't ever save the object's values, only how it was 
> created?
>
> Say I have a large object that requires a lot of time to train on data. It 
> means pickle doesn't save its values, so you have to train it every time 
> anew? Is there no way to save its trained values?

It'll save instance data but not class data or code. So it'll save all
that content, and it assumes that class data is either static or will
be recreated appropriately during unpickling.

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


Re: Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-27 Thread alex23
On 27 Dec, 22:58, Chris Angelico  wrote:
> Rick, ever heard of the ELIZA Effect?

Can we _please_ stop feeding this troll?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-27 Thread Tim Chase
On 12/27/12 04:58, Steven D'Aprano wrote:
> On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:
> 
 two = lamba : "one"
 one = two
>>>
 Which one of these is the "name" of the function?
> [...]
>> If i call one() and two() respectively, i would like to see "one" and
>> "two".
> 
> I'm afraid you're going to be disappointed. There is no possible way for 
> one() and two() as shown above to report different names, because they 
> are the same function object.
> 
> py> two = lambda : "one"
> py> one = two
> py> one is two
> True
> py> one, two
> ( at 0xb7abd92c>,  at 0xb7abd92c>)

And for similar fun:

  def call(fn, *args, **kwargs):
return fn(*args, **kwargs)

  two = lambda : "one"
  one = two
  print(call(two))
  print(call(one))

Depending on where in the code you are, the same function object
also has a local name of "fn".  It's madness until you understand
it, and then it's beauty :)

-tkc


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


Re: Finding the name of a function while defining it

2012-12-27 Thread Steven D'Aprano
On Tue, 25 Dec 2012 18:00:38 -0800, Abhas Bhattacharya wrote:

> While I am defining a function, how can I access the name (separately as
> string as well as object) of the function without explicitly naming
> it(hard-coding the name)? For eg. I am writing like:
> def abc():
> #how do i access the function abc here without hard-coding the name?

You can't easily get the function name from inside the function. But you 
*can* easily get the function name from outside the function, so the 
simple solution is to use a decorator to wrap the function with something 
that knows its name. For example:


import functools

def print_function_name(func):
# Decorate func so that it prints a message when called.
@functools.wraps(func)
def inner(*args, **kwargs):
print "Calling function %s" % func.__name__
return func(*args, **kwargs)
return inner


@print_function_name
def spam(n):
return ' '.join(['spam']*n)

@print_function_name
def breakfast(n):
return ' and '.join(['ham', 'eggs', spam(n)])


And then in use:

py> spam(3)
Calling function spam
'spam spam spam'
py> 
py> breakfast(5)
Calling function breakfast
Calling function spam
'ham and eggs and spam spam spam spam spam'


I recommend you use this solution if possible.

Unfortunately this doesn't help if you actually need the function name 
*inside* the function, for example:

def invert(n):
if n != 0:
return 1/n
else:
raise ZeroDivisionError(
'divide by zero error in function %s' % ***MAGIC GOES HERE***)

(But note, why would I bother doing this? When the traceback prints, it 
already displays the function name. Why am I doing by hand what Python 
automatically does for me?)

If you really must do this, you can do it like this:


import traceback

def get_current_function_name():
"""If this looks like magic, that's because it is."""
x = traceback.extract_stack(limit=2)
return x[0][2]


def invert(n):
if n != 0:
return 1/n
else:
me = get_current_function_name()
raise ZeroDivisionError('divide by zero error in func %s' % me)



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


Re: Finding the name of a function while defining it

2012-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2012 07:32:16 -0600, Tim Chase wrote:

> Depending on where in the code you are, the same function object also
> has a local name of "fn".  It's madness until you understand it, and
> then it's beauty :)

"This is madness!"

"No, this is PYTHON!!!"



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


Creating an iterator in a class

2012-12-27 Thread Joseph L. Casale
I am writing a class to provide a db backed configuration for an application.

In my programs code, I import the class and pass the ODBC params to the
class for its __init__ to instantiate a connection.

I would like to create a function to generically access a table and provide an
iterator. How does one create a function in a class that takes an argument and
returns an iterator? I saw some examples where the class gets instantiated
with the table defined but I was hoping not to do this so I could continue to
access various tables through one connection/cursor.

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Roy Smith
In article <[email protected]>,
 Steven D'Aprano  wrote:

> On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:
> 
> >> > two = lamba : "one"
> >> > one = two
> >> 
> >> > Which one of these is the "name" of the function?
> [...]
> > If i call one() and two() respectively, i would like to see "one" and
> > "two".
> 
> I'm afraid you're going to be disappointed. There is no possible way for 
> one() and two() as shown above to report different names, because they 
> are the same function object.

Well, there is the (yes, I know it's absurd) sledgehammer-and-peanut way 
of getting a stack trace, finding the frame that called your function, 
and parsing the text of that line.

Never tell a hacker, "no possible way" :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating an iterator in a class

2012-12-27 Thread Peter Otten
Joseph L. Casale wrote:

> I am writing a class to provide a db backed configuration for an
> application.
> 
> In my programs code, I import the class and pass the ODBC params to the
> class for its __init__ to instantiate a connection.
> 
> I would like to create a function to generically access a table and
> provide an iterator. How does one create a function in a class that takes
> an argument and returns an iterator? I saw some examples where the class
> gets instantiated with the table defined but I was hoping not to do this
> so I could continue to access various tables through one
> connection/cursor.

Have the method yield instead of returning:

>>> class Names:
... def __init__(self, template):
... self.template = template
... def generate_names(self, upto):
... for index in range(1, upto+1):
... yield self.template.format(index)
... 
>>> names = Names("file{}.txt")
>>> for name in names.generate_names(3):
... print name
... 
file1.txt
file2.txt
file3.txt
>>> list(names.generate_names(2))
['file1.txt', 'file2.txt']
>>> g = names.generate_names(3)
>>> next(g)
'file1.txt'
>>> next(g)
'file2.txt'
>>> next(g)
'file3.txt'
>>> next(g)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration


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


Re: Creating an iterator in a class

2012-12-27 Thread TommyVee
"Joseph L. Casale"  wrote in message 
news:[email protected]...


I am writing a class to provide a db backed configuration for an 
application.


In my programs code, I import the class and pass the ODBC params to the
class for its __init__ to instantiate a connection.

I would like to create a function to generically access a table and provide 
an
iterator. How does one create a function in a class that takes an argument 
and

returns an iterator? I saw some examples where the class gets instantiated
with the table defined but I was hoping not to do this so I could continue 
to

access various tables through one connection/cursor.

Thanks!
jlc=

Python makes it easy.  Read up on "Generators", and the "yield" statement. 
Works very elegantly with a "for ... in" loop.


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


ImportError: /usr/local/lib/python3.2/dist-packages/OpenSSL/SSL.cpython-32mu.so: undefined symbol: SSLv2_method

2012-12-27 Thread Jason Friedman
Hello,
I downloaded:
https://launchpad.net/pyopenssl/main/0.11/+download/pyOpenSSL-0.11.tar.gz

Then:
$ python3 setup.py build
$ sudo python3 setup.py install

Then:
$ python3 -c "from OpenSSL import SSL"
Traceback (most recent call last):
  File "", line 1, in 
  File "OpenSSL/__init__.py", line 40, in 
from OpenSSL import crypto
ImportError: cannot import name crypto

Then I downloaded:
http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz

Then
$ python3 setup.py build
$ sudo python3 setup.py install

Now:
$ python3 -c "from OpenSSL import SSL"
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.2/dist-packages/OpenSSL/__init__.py",
line 45, in 
from OpenSSL import rand, SSL
ImportError: /usr/local/lib/python3.2/dist-packages/OpenSSL/SSL.cpython-32mu.so:
undefined symbol: SSLv2_method

(Which does not turn up any hits on Google, even with the local path removed.)

$ which python3
/usr/bin/python3

$ whereis python3
python3: /usr/bin/python3 /usr/bin/python3.2mu
/usr/bin/python3.2mu-config /usr/bin/python3.2-config
/usr/bin/python3.2 /etc/python3 /etc/python3.2 /usr/lib/python3
/usr/lib/python3.2 /usr/bin/X11/python3 /usr/bin/X11/python3.2mu
/usr/bin/X11/python3.2mu-config /usr/bin/X11/python3.2-config
/usr/bin/X11/python3.2 /usr/local/lib/python3.2
/usr/include/python3.2mu /usr/include/python3.2 /usr/share/python3
/opt/python/bin/python3.2m /opt/python/bin/python3
/opt/python/bin/python3.2m-config /opt/python/bin/python3.2-config
/opt/python/bin/python3.2 /usr/share/man/man1/python3.1.gz
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Creating an iterator in a class

2012-12-27 Thread Joseph L. Casale
>Have the method yield instead of returning:

Thanks, that was simple, I was hung up on implementing magic methods.

Thanks for the pointers guys!
jlc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding Jython support in IBM and HP platforms

2012-12-27 Thread Kev Dwyer
Naresh Kumar wrote:

> 
> 
> 
> Hello,
> 
> I am trying to use the Jython in IBM AIX and HP machines to test our
> framework which is based on JAVA. when trying to run our python and jython
> based testcases using system test framework we are getting below errors in
> jython.err file
> 
> 
> 
> Error: could not find libjava.so
> 
> Error: could not find Java 2 Runtime
> Environment.” (Shared library of java)
> 
> 
> 
> Trying to find in online whether jython is supported on these two
> platforms HP and IBM and i could not able to get proper info. so could you
> please provide me the info like what are all platforms it
> supports(jython)? If not when do you guys are supporting on HP and IBM
> because java is pretty much support on all platforms and machine
> independent, so jython is similar like java.
> 
> Thanks in advance,
> Naresh


Hello,

Jython is an implementation of the Python language in Java, so it will run 
on any platform that can run a JVM.

From the information that you have provided, it seems that Jython cannot 
find libjava.so.

The Jython docs suggest that Jython's behaviour can be influenced by the 
value of the environmental variable JAVA_HOME 
(http://www.jython.org/docs/using/cmdline.html#environment-variables).

Have you checked that $JAVA_HOME is set to a suitable value for the user 
that is running Jython?

My JAVA_HOME:

kev@pluto ~/Download  echo $JAVA_HOME   
  
/usr/lib64/jvm/java  

If I download the jython 2.5.3 jar and run a simple test script I get:

kev@pluto ~/Download  java -jar jython.jar jtest.py 
  
*sys-package-mgr*: processing new jar, '/home/kev/Download/jython.jar'  
  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/resources.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/rt.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/jsse.jar' 
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/jce.jar'  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/charsets.jar' 
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/rhino.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/pulse-java.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/gnome-java-bridge.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/sunpkcs11.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/localedata.jar'   
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/dnsns.jar'
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/swt.jar'  
*sys-package-mgr*: processing new jar, '/usr/lib64/jvm/java-1.6.0-
openjdk-1.6.0/jre/lib/ext/sunjce_provider.jar'  
Hello Jython world!  

So I think you need to check your environment.

Cheers,

Kevin

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


Re: Custom alphabetical sort

2012-12-27 Thread wxjmfauth
Le lundi 24 décembre 2012 16:32:56 UTC+1, Pander Musubi a écrit :
> Hi all,
> 
> 
> 
> I would like to sort according to this order:
> 
> 
> 
> (' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 
> 'A', 'ä', 'Ä', 'á', 'Á', 'â', 'Â', 'à', 'À', 'å', 'Å', 'b', 'B', 'c', 'C', 
> 'ç', 'Ç', 'd', 'D', 'e', 'E', 'ë', 'Ë', 'é', 'É', 'ê', 'Ê', 'è', 'È', 'f', 
> 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'ï', 'Ï', 'í', 'Í', 'î', 'Î', 'ì', 'Ì', 
> 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'ñ', 'N', 'Ñ', 'o', 'O', 'ö', 
> 'Ö', 'ó', 'Ó', 'ô', 'Ô', 'ò', 'Ò', 'ø', 'Ø', 'p', 'P', 'q', 'Q', 'r', 'R', 
> 's', 'S', 't', 'T', 'u', 'U', 'ü', 'Ü', 'ú', 'Ú', 'û', 'Û', 'ù', 'Ù', 'v', 
> 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z')
> 
> 
> 
> How can I do this? The default sorted() does not give the desired result.
> 

-

One way is to create a list of 2-lists / 2-tuples, like

[(modified_word_1, word_1), (modified_word_2, word_2), ...]

and to use the native sorting wich will use the first element
modified_word_2 as primary key.

The task lies in the creation of the primary keys.

I did it once for French (seriously) and for German (less
seriously) scripts. (Only as an exercise for fun).

Eg.

>>> rob = ['noduleux', 'noël', 'noèse', 'noétique',
... 'nœud', 'noir', 'noirâtre']
>>> z = list(rob)
>>> random.shuffle(z)
>>> z
['noirâtre', 'noèse', 'noir', 'noël', 'nœud', 'noétique',
'noduleux']
>>> zo = libfrancais.sortfr(z)
>>> zo
['noduleux', 'noël', 'noèse', 'noétique', 'nœud', 'noir',
'noirâtre']
>>> zo == rob
True

PS Py 3.3 warranty: ~30% slower than Py 3.2

jmf

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


Re: Creating an iterator in a class

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 7:44 AM, Joseph L. Casale
 wrote:
> I am writing a class to provide a db backed configuration for an application.
>
> In my programs code, I import the class and pass the ODBC params to the
> class for its __init__ to instantiate a connection.
>
> I would like to create a function to generically access a table and provide an
> iterator. How does one create a function in a class that takes an argument and
> returns an iterator? I saw some examples where the class gets instantiated
> with the table defined but I was hoping not to do this so I could continue to
> access various tables through one connection/cursor.

It's probably best if you use separate cursors anyway.  Say you have
two methods with a shared cursor:

def iter_table_a(self):
self.cursor.execute("SELECT * FROM TABLE_A")
yield from self.cursor

def iter_table_b(self):
self.cursor.execute("SELECT * FROM TABLE_B")
yield from self.cursor

If the client code calls iter_table_a and partially iterates over the
result, and then needs to use iter_table_b for some reason, then when
it gets back to the table A results the data will be gone.  You can
only safely share cursors when you can guarantee that each query will
be completely processed before the next query is run, and you can't
guarantee that if you're just returning iterators.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-27 Thread Steven W. Orr

On 12/26/2012 11:11 AM, Benjamin Kaplan wrote:


On Dec 26, 2012 11:00 AM, "Antoon Pardon" mailto:[email protected]>> wrote:
 >
 > I am converting some programs to python 3. These programs manipulate
tarfiles. In order for the python3 programs to be really useful
 > they need to be able to process the tarfiles produced by python2 that
however seems to be a problem.
 >
 > This is testcode that produces a tarfile.
 >
 > #! /usr/bin/python
 >
 > compression = "bz2"
 > tarmode = "w|%s" % compression
 > rt = '.'
 >
 > import os
 > import os.path
 > import errno
 >
 > import tarfile as tar
 >
 > def process():
 > pj = os.path.join
 > entries = os.listdir(rt)
 > of = open("DUMP.tbz", "w")
 > tf = tar.open(mode = tarmode, fileobj = of,
 >   encoding = 'ascii', format = tar.PAX_FORMAT)
 > for entry in entries:
 > fqpn = pj(rt, entry)
 > try:
 > tf.add(fqpn, entry, recursive = False)
 > except OSError as ErrInfo:
 > print("%s: disappeared" % fqpn)
 > if ErrInfo.errno != errno.ENOENT:
 > raise
 > tf.close()
 > of.close()
 >
 > if __name__ == "__main__":
 > process()
 >
 >
==
 > This is testcode that checks a tarfile
 >
 > #!/usr/bin/python
 >
 > compression = "bz2"
 > tarmode = "r|%s" % compression
 >
 > import os
 > import os.path
 > import stat
 >
 > import tarfile as tar
 >
 > def equalfile(fl1, fl2):
 > bf1 = fl1.read(8192)
 > bf2 = fl2.read(8192)
 > while bf1 == bf2:
 > if bf1 == "":
 > return True
 > bf1 = fl1.read(8192)
 > bf2 = fl2.read(8192)
 > return False
 >
 > def process():
 > gf = open("DUMP.tbz", "r")
 > tf = tar.open(mode = tarmode, fileobj = gf,
 >   encoding = 'ascii', format = tar.PAX_FORMAT)
 > for tarinfo in tf:
 > entry = tarinfo.name 
 > fileinfo = os.stat(entry)
 > if stat.S_ISREG(fileinfo.st_mode) and tarinfo.isreg():
 > bfl = tf.extractfile(tarinfo)
 > ofl = open(entry)
 > if not equalfile(bfl, ofl):
 > print("%s: does not match backup" % entry)
 > sync = False
 > tf.close()
 > gf.close()
 >
 > if __name__ == "__main__":
 > process()
 >
 >
=
 >
 > When I use python2.7 to produce and later check the tarfile
everything works as expected. However when I use python3.2 to check the
tarfile I
 > get the following traceback.
 >
 > Traceback (most recent call last):
 >   File "tarchck", line 39, in 
 > process()
 >   File "tarchck", line 25, in process
 > encoding = 'ascii', format = tar.PAX_FORMAT)
 >   File "/usr/lib/python3.2/tarfile.py", line 1771, in open
 > t = cls(name, filemode, stream, **kwargs)
 >   File "/usr/lib/python3.2/tarfile.py", line 1667, in __init__
 > self.firstmember = self.next()
 >   File "/usr/lib/python3.2/tarfile.py", line 2418, in next
 > tarinfo = self.tarinfo.fromtarfile(self)
 >   File "/usr/lib/python3.2/tarfile.py", line 1281, in fromtarfile
 > buf = tarfile.fileobj.read(BLOCKSIZE)
 >   File "/usr/lib/python3.2/tarfile.py", line 573, in read
 > buf = self._read(size)
 >   File "/usr/lib/python3.2/tarfile.py", line 585, in _read
 > buf = self.__read(self.bufsize)
 >   File "/usr/lib/python3.2/tarfile.py", line 604, in __read
 > buf = self.fileobj.read(self.bufsize)
 >   File "/usr/lib/python3.2/codecs.py", line 300, in decode
 > (result, consumed) = self._buffer_decode(data, self.errors, final)
 > UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position
10: invalid start byte
 >
 > I have been looking around but have no idea how I have to adapt this
code in order to have it process the tarfile under python3.2. The
original code didn't have the coding and format keywords on the tar.open
statement and after reading the documentation I thought that
 > would make things work, but no such luck. Further reading didn't
 > provide anything usefull
 >
 > --
 > Antoon Pardon
 > --

You're opening the file in text mode, so it's trying to decode it as
text using your default encoding (utf-8). You want the file read as a
series of bytes, so open it in binary mode.

gf =open("DUMP.tbz", "rb")





Really? I thought that the whole idea of using "rb" or "wb" was 
something that was necessitated by WinBlo$e. We're not doing IO on a 
text file here. It's a tar file which by definition is binary and it's 
not clear to me why unicode has anything to do with it. The files you 
extract should be unaffected and the archive you produce shouldn't care. 
Am I missing something?


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


Re: Py 3.3, unicode / upper()

2012-12-27 Thread Serhiy Storchaka

On 19.12.12 17:40, Chris Angelico wrote:

Interestingly, IDLE on my Windows box can't handle the bolded
characters very well...


s="\U0001d407\U0001d41e\U0001d425\U0001d425\U0001d428, 
\U0001d430\U0001d428\U0001d42b\U0001d425\U0001d41d!"
print(s)

Traceback (most recent call last):
   File "", line 1, in 
 print(s)
UnicodeEncodeError: 'UCS-2' codec can't encode character '\U0001d407'
in position 0: Non-BMP character not supported in Tk

I think this is most likely a case of "yeah, Windows XP just sucks".
But I have no reason or inclination to get myself a newer Windows to
find out if it's any different.


No, this is a Tcl/Tk limitation (I don't know if this was fixed in 8.6).

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


Re: Password hash

2012-12-27 Thread Peter Pearson
On Sun, 23 Dec 2012 20:38:12 -0600, Robert Montgomery wrote:
> I am writing a script that will send an email using an account I set up
> in gmail. It is an smtp server using tls on port 587, and I would like
> to use a password hash in the (python) script for login rather than
> plain text. Is this do-able? Details please.

No, *you* need to provide details.  Security problems nearly always
emerge from the details, so it's important to be as clear as possible
about what you want to achieve and what the threat is.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 11:50 AM, Steven W. Orr  wrote:
> Really? I thought that the whole idea of using "rb" or "wb" was something
> that was necessitated by WinBlo$e. We're not doing IO on a text file here.
> It's a tar file which by definition is binary and it's not clear to me why
> unicode has anything to do with it. The files you extract should be
> unaffected and the archive you produce shouldn't care. Am I missing
> something?

Python 3 uses the 'b' mode to signify that a binary stream should be
opened instead of a text stream.  A binary stream returns bytes when
read from.  A text stream returns strings when read from, which means
that the bytes must be decoded; it also performs optional newline
conversion.  For full details, see the io module documentation.

You're correct that it makes no sense to open a tar file in binary
mode, but the basic io.open constructor has no concept of file type
and relies on the caller to specify the mode properly.  The tarfile
module has its own tarfile.open function which has no "text mode";
this is generally the correct way to open a tar file.  For some reason
the OP is not using this but is instead opening the file with io.open
(in the wrong mode) and then passing the already-opened file object to
tarfile.open.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 12:25 PM, Ian Kelly  wrote:
> You're correct that it makes no sense to open a tar file in binary
> mode,

Of course that should have read: "it makes no sense to open a tar file
in text mode."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command Line Progress Bar

2012-12-27 Thread Oscar Benjamin
On 26 December 2012 06:17, Kevin Anthony  wrote:
> Hello,
> I'm writing a file processing script(Linux), and i would like to have a
> progress bar.  But i would also like to be able to print messages.  Is there
> a simple way of doing this without implementing something like ncurses?

Other projects have been suggested. I've used this one:
http://code.google.com/p/python-progressbar/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py 3.3, unicode / upper()

2012-12-27 Thread wxjmfauth
Le jeudi 27 décembre 2012 20:00:37 UTC+1, Serhiy Storchaka a écrit :
> On 19.12.12 17:40, Chris Angelico wrote:
> 
> > Interestingly, IDLE on my Windows box can't handle the bolded
> 
> > characters very well...
> 
> >
> 
>  s="\U0001d407\U0001d41e\U0001d425\U0001d425\U0001d428, 
>  \U0001d430\U0001d428\U0001d42b\U0001d425\U0001d41d!"
> 
>  print(s)
> 
> > Traceback (most recent call last):
> 
> >File "", line 1, in 
> 
> >  print(s)
> 
> > UnicodeEncodeError: 'UCS-2' codec can't encode character '\U0001d407'
> 
> > in position 0: Non-BMP character not supported in Tk
> 
> >
> 
> > I think this is most likely a case of "yeah, Windows XP just sucks".
> 
> > But I have no reason or inclination to get myself a newer Windows to
> 
> > find out if it's any different.
> 
> 
> 
> No, this is a Tcl/Tk limitation (I don't know if this was fixed in 8.6).

-


This is a strange error message. Remember: a coding scheme
covers a *set of characters*.
The guilty code point corresponds to a character which
is not part of the ucs-2 characters set!

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


RE: Creating an iterator in a class

2012-12-27 Thread Joseph L. Casale
> It's probably best if you use separate cursors anyway.  Say you have
> two methods with a shared cursor:
>
> def iter_table_a(self):
> self.cursor.execute("SELECT * FROM TABLE_A")
> yield from self.cursor
>
> def iter_table_b(self):
> self.cursor.execute("SELECT * FROM TABLE_B")
> yield from self.cursor
>
> If the client code calls iter_table_a and partially iterates over the
> result, and then needs to use iter_table_b for some reason, then when
> it gets back to the table A results the data will be gone.  You can
> only safely share cursors when you can guarantee that each query will
> be completely processed before the next query is run, and you can't
> guarantee that if you're just returning iterators.

Oops, I admit I never tested that scenario before and you are right, its
not a sane assumption.

Thanks, I'll rewrite that section.
jlc
-- 
http://mail.python.org/mailman/listinfo/python-list


New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread mogul
'Aloha!

I'm new to python, got 10-20 years perl and C experience, all gained on unix 
alike machines hacking happily in vi, and later on in vim.

Now it's python, and currently mainly on my kubuntu desktop.

Do I really need a real IDE, as the windows guys around me say I do, or will 
vim, git, make and other standalone tools make it the next 20 years too for me? 

Oh, by the way, after 7 days I'm completely in love with this python thing. I 
should have made the switch much earlier!

/mogul %-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regarding compiling the Python 2.7 and 3.3 with mingw

2012-12-27 Thread erikj
Hi,

have you been able to resolve this issue for 3.3 ? I've arrived
at the same point after applying the patches mentioned here :

http://bugs.python.org/issue3754

and creating a custom site.config

Thx,

Erik

On Wednesday, December 26, 2012 1:16:00 AM UTC+1, ginzzer wrote:
> Hi all, 
> 
>   For some reason, I have to develop my software with mingw under windows. 
> First of all, I need python installed in the msys but I try all my ways to 
> install 2.6.x, 2.7.x, 3.2.x and 3.3.0, no one succeed. I search all issues 
> and google the related information online, it seems that it doesn't support 
> python on mingw? But what stranger is there are a few posts here with the 
> patch presented, so is there any way to make the source compiled in mingw? I 
> try all the available patches but again, it didn't solve the problem. Here 
> are the error messages when I try to compile the 3.3.0 in mingw, 
> 
> 
> 
>   ./configure  ---> no problem
> 
>   make ---> errors shown below
> 
>   Objects/exceptions.c:2527:5: error: 'EALREADY' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2527:5: note: each undeclared identifier is reported 
> only once for each function it appears in
> 
>   Objects/exceptions.c:2528:5: error: 'EINPROGRESS' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2529:5: error: 'EWOULDBLOCK' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2532:5: error: 'ESHUTDOWN' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2536:5: error: 'ECONNABORTED' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2538:5: error: 'ECONNREFUSED' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2540:5: error: 'ECONNRESET' undeclared (first use in 
> this function)
> 
>   Objects/exceptions.c:2557:5: error: 'ETIMEDOUT' undeclared (first use in 
> this function)
> 
>   make: *** [Objects/exceptions.o] Error 1
> 
> 
> 
> I then try compiling the version 2.7.3, different errors were shown while 
> 'make'
> 
> 
> 
>   ./Modules/posixmodule.c:6151:5: warning: implicit declaration of function 
> 'wait'[-Wimplicit-function-declaration]
> 
>   ./Modules/posixmodule.c: In function 'posix_fdopen':
> 
>   ./Modules/posixmodule.c:6751:9: warning: implicit declaration of function 
> 'fcntl' [-Wimplicit-function-declaration]
> 
>   ./Modules/posixmodule.c:6751:27: error: 'F_GETFL' undeclared (first use in 
> this function)
> 
>   ./Modules/posixmodule.c:6751:27: note: each undeclared identifier is 
> reported only once for each function it appears in
> 
>   ./Modules/posixmodule.c:6753:23: error: 'F_SETFL' undeclared (first use in 
> this function)
> 
>   ./Modules/posixmodule.c: In function 'posix_pipe':
> 
>   ./Modules/posixmodule.c:6816:5: warning: implicit declaration of function 
> 'pipe' [-Wimplicit-function-declaration]
> 
>   ./Modules/posixmodule.c: At top level:
> 
>   ./Modules/posixmodule.c:671:1: warning: 'posix_fildes' defined but not used 
> [-Wunused-function]
> 
>   ./Modules/posixmodule.c:7480:1: warning: 'conv_confname' defined but not 
> used [-Wunused-function]
> 
>   ./Modules/posixmodule.c:8387:1: warning: 'setup_confname_table' defined but 
> not used [-Wunused-function]
> 
>   make: *** [Modules/posixmodule.o] Error 1
> 
> 
> 
> I highly appreciate it if you could show me any hints in compiling the
> 
> python in mingw.

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread ian douglas
Some would argue that vim is always good enough, especially with its plugin
system.

I bounce between vim and Sublime Text 2, and recently bought PyCharm went
it went on sale a week ago.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Daniel Fetchinson
> I'm new to python, got 10-20 years perl and C experience, all gained on unix
> alike machines hacking happily in vi, and later on in vim.
>
> Now it's python, and currently mainly on my kubuntu desktop.

Welcome to the club!

> Do I really need a real IDE, as the windows guys around me say I do, or will
> vim, git, make and other standalone tools make it the next 20 years too for
> me?

Sure they will!

> Oh, by the way, after 7 days I'm completely in love with this python thing.

Again, welcome to the club!

> I should have made the switch much earlier!

Indeed..

BTW, I also use vim only,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Function Parameters

2012-12-27 Thread Joseph L. Casale
When you use optional named arguments in a function, how do you deal with with
the incorrect assignment when only some args are supplied?

If I do something like:

def my_func(self, **kwargs):

then handle the test cases with:

if not kwargs.get('some_key'):
raise SyntaxError
or:

if kwargs.get('some_key') and kwargs.get('another_key'):
...

I loose the introspection that some IDE's provide from the doc strings.

Any ideas on how to deal with this?

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread peter

On 12/27/2012 05:01 PM, mogul wrote:

'Aloha!

I'm new to python, got 10-20 years perl and C experience, all gained on unix 
alike machines hacking happily in vi, and later on in vim.

Now it's python, and currently mainly on my kubuntu desktop.

Do I really need a real IDE, as the windows guys around me say I do, or will 
vim, git, make and other standalone tools make it the next 20 years too for me?

Oh, by the way, after 7 days I'm completely in love with this python thing. I 
should have made the switch much earlier!

/mogul %-)
You going to create a war here. My honest advice, is just taste the 
different ides that are out there.


- emacs
- vi
- aptana
- eclipse
- pycharm
- wingide.
- etc
- etc.

I currently use emacs for everything.
--
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Alister
On Thu, 27 Dec 2012 12:01:16 -0800, mogul wrote:

> 'Aloha!
> 
> I'm new to python, got 10-20 years perl and C experience, all gained on
> unix alike machines hacking happily in vi, and later on in vim.
> 
> Now it's python, and currently mainly on my kubuntu desktop.
> 
> Do I really need a real IDE, as the windows guys around me say I do, or
> will vim, git, make and other standalone tools make it the next 20 years
> too for me?
> 
> Oh, by the way, after 7 days I'm completely in love with this python
> thing. I should have made the switch much earlier!
> 
> /mogul %-)

I don't use vi/vim myself but would suggest that if you are happy 
developing C without an IDE then python should be a walk in the park.




-- 
For 20 dollars, I'll give you a good fortune next time ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function Parameters

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 1:16 PM, Joseph L. Casale
 wrote:
> When you use optional named arguments in a function, how do you deal with with
> the incorrect assignment when only some args are supplied?
>
> If I do something like:
>
> def my_func(self, **kwargs):
>
> then handle the test cases with:
>
> if not kwargs.get('some_key'):
> raise SyntaxError
> or:
>
> if kwargs.get('some_key') and kwargs.get('another_key'):
> ...
>
> I loose the introspection that some IDE's provide from the doc strings.
>
> Any ideas on how to deal with this?

Don't use kwargs for this.  List out the arguments in the function
spec and give the optional ones reasonable defaults.

def my_func(self, some_key=None, another_key=None):
if some_key and another_key:
do_something()

If None is a meaningful value for the argument, then a good technique
is to use a unique object as the default instead.

MISSING = object()

def my_func(self, some_key=MISSING, another_key=MISSING):
if some_key is not MISSING and another_key is not MISSING:
do_something()

I only use kwargs myself when the set of possible arguments is dynamic
or unknown.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Function Parameters

2012-12-27 Thread Joseph L. Casale
> Don't use kwargs for this.  List out the arguments in the function
> spec and give the optional ones reasonable defaults.

> I only use kwargs myself when the set of possible arguments is dynamic
> or unknown.

Gotch ya, but when the inputs to some keywords are similar, if the function is 
called
with two of three (which is valid) and the arg name isn't used, the assignment 
is order
dependent and arbitrary in a sense and I can not distinguish.

It would be nice if you could force the keyword to be mandatory to forgo the 
assumption
in assignment like kwargs provides with gets. I suppose all the time wasted 
here is in vain
as the caller could blunder elsewhere...

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Terry Reedy

On 12/27/2012 3:01 PM, mogul wrote:

'Aloha!

I'm new to python, got 10-20 years perl and C experience, all gained
on unix alike machines hacking happily in vi, and later on in vim.

Now it's python, and currently mainly on my kubuntu desktop.

Do I really need a real IDE, as the windows guys around me say I do,
or will vim, git, make and other standalone tools make it the next 20
years too for me?


We try to avoid religious issues on this list.
Programming editors are a religious issue.
Therefore ... ;-)

Kidding aside, I am sure there is at least one core Python developer 
using vim (as well as emacs). I believe there are one or more 
'customization files' (or settings packages? don't know proper term for 
vim) which you should be able to find if you have not already.


Some 'real IDE' users consider IDLE a limited beginner's toy. I use it 
happily for what *I* do. I don't even use all the features if *does* have.


The one thing I would suggest is to make sure that you can run a python 
file with the '-i' flag so that the interpreter drops into interactive 
mode and gives a prompt instead of exiting when done. Then, if you get 
an exception like

AttributeError: 'Foo' object has no 'frobulate attribute
and you know the Foo object is named foo, you can enter (in the 
interpreter) 'dir(foo)' and perhaps see that it *does* has a 'fribulate' 
attribute. (When IDLE runs the code in an editor window, it stops with 
an interactive prompt in the shell window, and one can then enter code 
such as above.)



Oh, by the way, after 7 days I'm completely in love with this python
thing. I should have made the switch much earlier!


Welcome to the club.

--
Terry Jan Reedy

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


Re: Function Parameters

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 1:47 PM, Joseph L. Casale
 wrote:
>> Don't use kwargs for this.  List out the arguments in the function
>> spec and give the optional ones reasonable defaults.
>
>> I only use kwargs myself when the set of possible arguments is dynamic
>> or unknown.
>
> Gotch ya, but when the inputs to some keywords are similar, if the function 
> is called
> with two of three (which is valid) and the arg name isn't used, the 
> assignment is order
> dependent and arbitrary in a sense and I can not distinguish.

But the caller knows the order of the arguments, so if they just pass
two arguments positionally, then presumably those first two arguments
are the ones that they intend.

> It would be nice if you could force the keyword to be mandatory to forgo the 
> assumption
> in assignment like kwargs provides with gets. I suppose all the time wasted 
> here is in vain
> as the caller could blunder elsewhere...

In Python 3 you can designate arguments as keyword-only by placing
them after the * argument:

def example(self, *args, keyword1, keyword2=None):
# Takes one or more positional arguments.
# Required argument keyword1 and optional argument keyword2
# can only be passed by keyword.
pass

def example2(self, *, keyword='foo'):
# Takes exactly one positional argument.
# Optional argument keyword can only be passed by keyword.
pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function Parameters

2012-12-27 Thread Oscar Benjamin
On 27 December 2012 20:47, Joseph L. Casale  wrote:
>> Don't use kwargs for this.  List out the arguments in the function
>> spec and give the optional ones reasonable defaults.
>
>> I only use kwargs myself when the set of possible arguments is dynamic
>> or unknown.
>
> Gotch ya, but when the inputs to some keywords are similar, if the function 
> is called
> with two of three (which is valid) and the arg name isn't used, the 
> assignment is order
> dependent and arbitrary in a sense and I can not distinguish.
>
> It would be nice if you could force the keyword to be mandatory to forgo the 
> assumption
> in assignment like kwargs provides with gets. I suppose all the time wasted 
> here is in vain
> as the caller could blunder elsewhere...

In Python 3 you can do this using keyword-only arguments like so (note
the asterisk that separates keyword arguments from positional
arguments):

def my_func(self, *, some_key=MISSING, another_key=MISSING):


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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Walter Hurry
On Thu, 27 Dec 2012 12:01:16 -0800, mogul wrote:

> 'Aloha!
> 
> I'm new to python, got 10-20 years perl and C experience, all gained on
> unix alike machines hacking happily in vi, and later on in vim.
> 
> Now it's python, and currently mainly on my kubuntu desktop.
> 
> Do I really need a real IDE, as the windows guys around me say I do, or
> will vim, git, make and other standalone tools make it the next 20 years
> too for me?

If you don't want an IDE, don't use one (I don't). Just use whatever text 
editor you prefer. Although I avoid the editor wars, one advantage of vi 
is that it's always available on client *nix sites. Handy if you move 
around.

One suggestion though: It's probably a good idea not to post to this list 
using G**gle Groups. Many will ignore such posts.

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


Re: pickle module doens't work

2012-12-27 Thread Terry Reedy

On 12/27/2012 7:34 AM, Dave Angel wrote:


Perhaps you'd rather see it in the Python docs.

http://docs.python.org/2/library/pickle.html
http://docs.python.org/3.3/library/pickle.html

pickle can
save and restore class instances transparently, however the class
definition must be importable and live in the same module as when the
object was stored.
and
Similarly, when class instances are pickled, their class’s code and data
are not pickled along with them. Only the instance data are pickled.
This is done on purpose, so you can fix bugs in a class or add methods
to the class and still load objects that were created with an earlier
version of the class.


I should point out the the above was probably written before the 
(partial) unification of types and classes in 2.2 (completed in 3.3). So 
'class' is referring to 'Python-coded class' and 'code' is referring to 
'(compiled) Python code', and not machine code. Now, everything that 
pickle pickles is a 'class instance' and class code can be compiled from 
either Python or the interpreter's system language (C, Java, C#, others, 
or even Python itself).


--
Terry Jan Reedy


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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Tim Chase
On 12/27/12 14:01, mogul wrote:
> Do I really need a real IDE, as the windows guys around me say I
> do, or will vim, git, make and other standalone tools make it the
> next 20 years too for me?

Coding Python (and before that C, Pascal, and even some VB in there)
using vi/vim has worked for about 10 of the last 15 years of my
career.  Most VCS concepts carry over, even if the exact technology
changes:  I started off with zipfiles, then an unfortunate dance
with VSS & CVS before finding Subversion, then Mercurial, and now
git.  So time spent with git won't be lost.

Some like the hand-holding of a full-blown IDE, but I prefer to get
intimate with the code and stick to a text editor.

> Oh, by the way, after 7 days I'm completely in love with this
> python thing. I should have made the switch much earlier!

Alas, one of the worst parts about programming in Python is that I
now find it hard to go back to any of the other languages that I
know. :-)

-tkc



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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Michael Torrie
On 12/27/2012 01:01 PM, mogul wrote:
> Do I really need a real IDE, as the windows guys around me say I do,
> or will vim, git, make and other standalone tools make it the next 20
> years too for me?

I've never ever used an IDE with Python.  With Python I can code for an
hour in vim and it runs with only maybe one minor syntax error.  Often
the code runs first try, and runs correctly.  Having a reference to the
python standard library is about the only thing I need.  I typically use
python in a nutshell (dead tree) or just a browser page open to the
official docs.  Fortunately Python's use of namespaces and allowing the
use of singleton objects (we call them modules!) eliminates must of the
verbose rubbish that Java's libraries have.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Michael Torrie
On 12/27/2012 02:25 PM, Tim Chase wrote:
> Alas, one of the worst parts about programming in Python is that I
> now find it hard to go back to any of the other languages that I
> know. :-)

Amen.  I find myself wishing for a python-like language for programming
Arduino boards.

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


Re: Custom alphabetical sort

2012-12-27 Thread Terry Reedy

On 12/27/2012 1:17 PM, [email protected] wrote:

Le lundi 24 décembre 2012 16:32:56 UTC+1, Pander Musubi a écrit :

I would like to sort according to this order:
(' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 
'A', 'ä', 'Ä', 'á', 'Á', 'â', 'Â', 'à', 'À', 'å', 'Å', 'b', 'B', 'c', 'C', 'ç', 
'Ç', 'd', 'D', 'e', 'E', 'ë', 'Ë', 'é', 'É', 'ê', 'Ê', 'è', 'È', 'f', 'F', 'g', 
'G', 'h', 'H', 'i', 'I', 'ï', 'Ï', 'í', 'Í', 'î', 'Î', 'ì', 'Ì', 'j', 'J', 'k', 
'K', 'l', 'L', 'm', 'M', 'n', 'ñ', 'N', 'Ñ', 'o', 'O', 'ö', 'Ö', 'ó', 'Ó', 'ô', 
'Ô', 'ò', 'Ò', 'ø', 'Ø', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 
'U', 'ü', 'Ü', 'ú', 'Ú', 'û', 'Û', 'ù', 'Ù', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 
'Y', 'z', 'Z')



One way is to create a list of 2-lists / 2-tuples, like

[(modified_word_1, word_1), (modified_word_2, word_2), ...]

and to use the native sorting wich will use the first element
modified_word_2 as primary key.

The task lies in the creation of the primary keys.

I did it once for French (seriously) and for German (less
seriously) scripts. (Only as an exercise for fun).



>>> rob = ['noduleux', 'noël', 'noèse', 'noétique',
... 'nœud', 'noir', 'noirâtre']
>>> z = list(rob)
>>> random.shuffle(z)
>>> z
['noirâtre', 'noèse', 'noir', 'noël', 'nœud', 'noétique',
'noduleux']
>>> zo = libfrancais.sortfr(z)
>>> zo
['noduleux', 'noël', 'noèse', 'noétique', 'nœud', 'noir',
'noirâtre']
>>> zo == rob
True



PS Py 3.3 warranty: ~30% slower than Py 3.2


Do you have any actual timing data to back up that claim?
If so, please give specifics, including build, os, system, timing code, 
and result.


--
Terry Jan Reedy


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


Re: Custom alphabetical sort

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 3:17 PM, Terry Reedy  wrote:
>> PS Py 3.3 warranty: ~30% slower than Py 3.2
>
>
> Do you have any actual timing data to back up that claim?
> If so, please give specifics, including build, os, system, timing code, and
> result.

There was another thread about this one a while back.  Using IDLE on Windows XP:

>>> import timeit, locale
>>> li = ['noël', 'noir', 'nœud', 'noduleux', 'noétique', 'noèse', 'noirâtre']
>>> locale.setlocale(locale.LC_ALL, 'French_France')
'French_France.1252'

>>> # Python 3.2
>>> min(timeit.repeat("sorted(li, key=locale.strxfrm)", "import locale; from 
>>> __main__ import li", number=10))
1.1581226105552531

>>> # Python 3.3.0
>>> min(timeit.repeat("sorted(li, key=locale.strxfrm)", "import locale; from 
>>> __main__ import li", number=10))
1.4595282361305697

1.460 / 1.158 = 1.261

>>> li = li * 100
>>> import random
>>> random.shuffle(li)

>>> # Python 3.2
>>> min(timeit.repeat("sorted(li, key=locale.strxfrm)", "import locale; from 
>>> __main__ import li", number=1000))
1.233450899485831

>>> # Python 3.3.0
>>> min(timeit.repeat("sorted(li, key=locale.strxfrm)", "import locale; from 
>>> __main__ import li", number=1000))
1.5793845307155152

1.579 / 1.233 = 1.281

So about 26% slower for sorting a short list of French words and about
28% slower for a longer list.  Replacing the strings with ASCII and
removing the 'key' argument gives a comparable result for the long
list but more like a 40% slowdown for the short list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Modulok
> 'Aloha!
>
> I'm new to python, got 10-20 years perl and C experience, all gained on unix
> alike machines hacking happily in vi, and later on in vim.
>
> Now it's python, and currently mainly on my kubuntu desktop.
>
> Do I really need a real IDE, as the windows guys around me say I do, or will
> vim, git, make and other standalone tools make it the next 20 years too for
> me?
>
> Oh, by the way, after 7 days I'm completely in love with this python thing.
> I should have made the switch much earlier!
>
> /mogul %-)


No. If you want to test one out, great. If not, it's totally not required. I
use jEdit (text editor) and a bunch of command line tools on FreeBSD. I've
tried various IDEs and have yet to find one I totally agree with. Yet, I know
guys who use them and wouldn't part with them 'til death. I always end up back
in a customized text editor and a *nix command shell. I prefer it.

There's a lot of *very* skilled programmers in both camps.
-Modulok-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Cameron Simpson
On 27Dec2012 12:01, mogul  wrote:
| I'm new to python, got 10-20 years perl and C experience, all gained
| on unix alike machines hacking happily in vi, and later on in vim.
| 
| Now it's python, and currently mainly on my kubuntu desktop.
| 
| Do I really need a real IDE, as the windows guys around me say I do,
| or will vim, git, make and other standalone tools make it the next 20
| years too for me?

Your Windows guys are weak. Use the tools that make you happy.

Personally, my normal programming env is an editor window (vim for me,
or vi) and a shell window. With the docs (2.x or 3.x, local
all-in-one-HTML file saved on my desktop for instant open at need and
offline use) in a browser window behind the terminals. (I'm usually on a
Mac, so terminals and browser side-by-side aren't so easy with its
desktop metaphor - it is a single keystroke to toggle back and forth
though).

| Oh, by the way, after 7 days I'm completely in love with this python
| thing. I should have made the switch much earlier!

I thought that after biting the bullet a few years ago. I had (well,
still have, though it grows not these days) this personal Perl library
that kept me back, and hadn;t realised:

  - how many batteries are already included in the stdlib

  - how little of that library was current; re-implement the live stuff
(better and cleaner) and move on - very liberating

Cheers,
-- 
Cameron Simpson 

Avoid bickering and petty arguments by immediately punching anyone with whom
you disagree.   - [email protected] (John Young)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Chris Angelico
On Fri, Dec 28, 2012 at 7:01 AM, mogul  wrote:
> Do I really need a real IDE, as the windows guys around me say I do, or will 
> vim, git, make and other standalone tools make it the next 20 years too for 
> me?

Welcome!

No, you don't *need* an IDE. Some people like them and are the more
productive for them, but if standalone tools have served you well for
20 years, they'll continue to do so. My current editor is SciTE,
because it supports all the languages I use (except LilyPond - must
look into that one day) and is available on Windows as well (I support
both platforms), but there are plenty of other excellent editors, and
vim is definitely one of them.

When I'm on Windows, I like to keep IDLE handy, but not for editing
source files. IDLE feels much nicer than command-line Python for
interactive work; the ability to recall entire blocks of code, rather
than individual lines, is hugely advantageous. (I don't do enough on
Linux IDLE to be able to call the difference there, but GNU readline
is so much better than the Windows interactive line reader that it's
not as big an issue.) To me, IDLE is my calculator, my test space for
python-list posts, and so on, but SciTE is where I write actual code.

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


Re: How to get time.strptime()?

2012-12-27 Thread Gnarlodious
Graham Dumpleton has informed me that the the relevant bug reports are:

http://bugs.python.org/issue8098
http://bugs.python.org/issue9260

To quote:

All the problems derive from a stupid function in Python internals called 
PyImport_ImportModuleNoBlock(). It was designed to avoid lockups of the import 
machinery but just causes other problems because a module import can fail if 
the import lock is held by a different thread. This faulty magic fairy dust was 
sprinkled on the time.strptime() function which internally loads _strptime 
module. If you access time.strptime() when another thread holds the import 
lock, the call will fail because of a failed import.

So there. As more people update to Python 3.3.0 hopefully this magic fairy dust 
workaround will see some daylight.

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


Re: Finding the name of a function while defining it

2012-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2012 10:09:01 -0500, Roy Smith wrote:

> In article <[email protected]>,
>  Steven D'Aprano  wrote:
> 
>> On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:
>> 
>> >> > two = lamba : "one"
>> >> > one = two
>> >> 
>> >> > Which one of these is the "name" of the function?
>> [...]
>> > If i call one() and two() respectively, i would like to see "one" and
>> > "two".
>> 
>> I'm afraid you're going to be disappointed. There is no possible way
>> for one() and two() as shown above to report different names, because
>> they are the same function object.
> 
> Well, there is the (yes, I know it's absurd) sledgehammer-and-peanut way
> of getting a stack trace, finding the frame that called your function,
> and parsing the text of that line.
> 
> Never tell a hacker, "no possible way" :-)


1) That is not supported by Python the language, only by certain Python 
implementations. You might be running IronPython with frame support 
turned off, or some other implementation with no frames at all.


2) Even if you have frames, you might not have access to the source code. 
The code may be running from the (CPython) interactive interpreter, or 
from a .pyc or .pyo file.


3) Even if you have the text of the source code, it might be ambiguous 
(e.g. "f(); g(); one(); two()") and you cannot tell which is "the 
current" function call.


4) Or the code may be obfuscated and too hard for you to parse:

eval("eval(''.join('ronnie'[1::2])+chr(40)+chr(41))")

(I expect that you, a human intelligence, can decipher the above, but can 
your parser?)


5) Which also rules out decompiling the byte code and parsing the pseudo-
assembly.

No matter how clever your parser, a sufficiently obfuscated algorithm 
will defeat it.


When I say something is impossible, I mean it is not a promised by the 
language. Naturally there may be ways of accomplishing a task that the 
language does not promise to allow which "only sometimes" works. At 
worst, you can always guess an answer, and hope that you're right!

def get_current_function_name():
# Only sometimes right.
return "one" if random.random() < 0.5 else "two"


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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread TommyVee
"mogul"  wrote in message 
news:[email protected]...


'Aloha!

I'm new to python, got 10-20 years perl and C experience, all gained on unix 
alike machines hacking happily in vi, and later on in vim.


Now it's python, and currently mainly on my kubuntu desktop.

Do I really need a real IDE, as the windows guys around me say I do, or will 
vim, git, make and other standalone tools make it the next 20 years too for 
me?


Oh, by the way, after 7 days I'm completely in love with this python thing. 
I should have made the switch much earlier!


/mogul %-)

I'd say start with IDLE.  I wouldn't exactly consider it an "IDE", but it 
gives you a decent Python-oriented editor.  For me it handles 95% of what I 
need to do (for more ambitious projects, I use PyScripter on the Windows 
platform).


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


Re: Finding the name of a function while defining it

2012-12-27 Thread alex23
On Dec 27, 11:31 pm, Steven D'Aprano  wrote:
> Unfortunately this doesn't help if you actually need the function name
> *inside* the function

Here's an extension of Steven's original decorator that adds a
reference to the function itself into the function's globals, and then
composes a new function from the component parts:

import new

def IdentityAwareFunctionDecorator( fn ):
_globals = fn.__globals__
_globals['selffunc'] = fn
name_aware_func = new.function(
fn.__code__, _globals, fn.__name__, fn.__defaults__,
fn.__closure__ )
return name_aware_func

id = IdentityAwareFunctionDecorator

@id
def foo():
return selffunc.__name__

Unfortunately, it also only knows about the original function name, so
'bar = foo; bar()' will still give you 'foo'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Roy Smith
In article <[email protected]>,
 "TommyVee"  wrote:

> Do I really need a real IDE, as the windows guys around me say I do, or will 
> vim, git, make and other standalone tools make it the next 20 years too for 
> me?

You'll do fine with vim (or emacs, or whatever).  You may find an IDE 
convenient, but it's certainly not necessary.
-- 
http://mail.python.org/mailman/listinfo/python-list


PYTHON 3.3 + GUI + COMPILE

2012-12-27 Thread Dimitrios Xenakis
Morning,
I have been looking for a library solution of both GUI and Compiler but for 
Python 3.3 and ofcourse i was hoping for a combination that would be most 
compatible between them. After searching i may have concluded to cx_Freeze 
(because it was the only one that noticed that currently supports version 
Python 3.3), but i do not know what GUI library should i combine it with. Does 
cx_Freeze alone put any kind of restriction to my choice of GUI? I would also 
be interested in using my programs for commercial purposes, so would this put 
again some other kind of limitations to my GUI choice? I have read many good 
stuff about PySide, but still i do not know wether this is the one that i 
should choose. Is PySide same as PyQT and PyQT4 and QT or which is the exact 
relationship between those? Disadvantages - advantages, capabilities, benefits, 
costs, etc. (What is the lowest possible cost of buying such a commercial 
license for my programming?. Are there different versions and should i be 
carefull
  to choose the best for me? Where could i get this from? PySide is total free 
for my commercial needs?) I need to be legit so i guess i should learn how to 
handle with the licencing thing. Please somebody clear things for me.

Thanks 4 your time i really appreciate that.
-- 
http://mail.python.org/mailman/listinfo/python-list


learning curve

2012-12-27 Thread Verde Denim
Just getting into Py coding and not understanding why this code doesn't
seem to do anything -

# File: dialog2.py
import dialog_handler

class MyDialog(dialog_handler.Dialog):
def body(self, master):
Label(master, text="First:").grid(row=0)
Label(master, text="Second:").grid(row=1)
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
return self.e1 # initial focus

def apply(self):
first = string.atoi(self.e1.get())
second = string.atoi(self.e2.get())
print first, second # or something

# File: dialog_handler.py

from Tkinter import *
import os

class Dialog(Toplevel):

def __init__(self, parent, title = None):
Toplevel.__init__(self, parent)
self.transient(parent)

if title:
self.title(title)
self.parent = parent
self.result = None
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=5, pady=5)
self.buttonbox()
self.grab_set()

if not self.initial_focus:
self.initial_focus = self

self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
  parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)

#
# construction hooks
def body(self, master):
# create dialog body.  return widget that should have
# initial focus.  this method should be overridden
pass

def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = Frame(self)

w = Button(box, text="OK", width=10, command=self.ok,
   default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Cancel", width=10,
   command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)

self.bind("", self.ok)
self.bind("", self.cancel)

box.pack()

#
# standard button semantics
def ok(self, event=None):
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()

def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()

#
# command hooks
def validate(self):
return 1 # override

def apply(self):
pass # override
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learning curve

2012-12-27 Thread alex23
On Dec 28, 11:20 am, Verde Denim  wrote:
> Just getting into Py coding and not understanding why this code doesn't
> seem to do anything -

Is that the sum total of your code? You're not showing any
instantiation of your classes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learning curve

2012-12-27 Thread MRAB

On 2012-12-28 01:20, Verde Denim wrote:

Just getting into Py coding and not understanding why this code doesn't
seem to do anything -

# File: dialog2.py
import dialog_handler

class MyDialog(dialog_handler.Dialog):

[snip]


# File: dialog_handler.py

from Tkinter import *
import os

class Dialog(Toplevel):

[snip]

You've defined 2 classes, but that's all. At no point did you ask it to
do anything with them!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get time.strptime()?

2012-12-27 Thread Ian Kelly
On Thu, Dec 27, 2012 at 5:33 PM, Gnarlodious  wrote:
> Graham Dumpleton has informed me that the the relevant bug reports are:
>
> http://bugs.python.org/issue8098
> http://bugs.python.org/issue9260
>
> To quote:
>
> All the problems derive from a stupid function in Python internals called 
> PyImport_ImportModuleNoBlock(). It was designed to avoid lockups of the 
> import machinery but just causes other problems because a module import can 
> fail if the import lock is held by a different thread. This faulty magic 
> fairy dust was sprinkled on the time.strptime() function which internally 
> loads _strptime module. If you access time.strptime() when another thread 
> holds the import lock, the call will fail because of a failed import.
>
> So there. As more people update to Python 3.3.0 hopefully this magic fairy 
> dust workaround will see some daylight.

Thanks for the context, but that actually seems to be describing the
situation from Python 3.2.  Python 3.3 introduced module-level import
locking with improved deadlock detection that looks for actual cycles
and is supposed to fix the unnecessary ImportErrors described in
#8098, rendering the PyImport_ImportModuleNoBlock "fairy dust"
unnecessary -- in 3.3, I understand that PyImport_ImportModuleNoBlock
is now just a synonym for PyImport_ImportModule.  But you're reporting
that you're still seeing issues with this in Python 3.3.  Diving into
the code, I think I start to understand why.  Take a look at this
function from Lib/importlib/_bootstrap.py:

def _lock_unlock_module(name):
"""Release the global import lock, and acquires then release the
module lock for a given module name.
This is used to ensure a module is completely initialized, in the
event it is being imported by another thread.

Should only be called with the import lock taken."""
lock = _get_module_lock(name)
_imp.release_lock()
try:
lock.acquire()
except _DeadlockError:
# Concurrent circular import, we'll accept a partially initialized
# module object.
pass
else:
lock.release()


Normally, it just acquires and releases the module lock to ensure that
the module has been completely initialized.  If a deadlock is
detected, however, then it skips that step and instead of raising an
ImportError (which would seem to me to be the right thing to do here)
it allows the importing code to simply proceed with a module that may
not be fully imported yet.  Since your error message concerned missing
module-level attributes within the _strptime module, that seems to be
what you're running into.  The time.strptime function attempts to
import _strptime, which is already being imported by another thread;
for some unknown reason it detects a cyclical deadlock as a result of
this; it then white-washes the deadlock and tries to use the _strptime
module anyway, causing a different error to occur.  The question then
is how you're managing to get an import cycle by using strptime.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHON 3.3 + GUI + COMPILE

2012-12-27 Thread Kevin Walzer

On 12/27/12 9:08 PM, Dimitrios Xenakis wrote:

Morning,
I have been looking for a library solution of both GUI and Compiler but for 
Python 3.3 and ofcourse i was hoping for a combination that would be most 
compatible between them. After searching i may have concluded to cx_Freeze 
(because it was the only one that noticed that currently supports version 
Python 3.3), but i do not know what GUI library should i combine it with. Does 
cx_Freeze alone put any kind of restriction to my choice of GUI? I would also 
be interested in using my programs for commercial purposes, so would this put 
again some other kind of limitations to my GUI choice? I have read many good 
stuff about PySide, but still i do not know wether this is the one that i 
should choose. Is PySide same as PyQT and PyQT4 and QT or which is the exact 
relationship between those? Disadvantages - advantages, capabilities, benefits, 
costs, etc. (What is the lowest possible cost of buying such a commercial 
license for my programming?. Are there different versions and should i be carefu

l
l to choose the best for me? Where could i get this from? PySide is total free 
for my commercial needs?) I need to be legit so i guess i should learn how to 
handle with the licencing thing. Please somebody clear things for me.


Thanks 4 your time i really appreciate that.



cx_Freeze has good support for Tkinter, PyQt, and (as far as I know) 
wxPython.


License: Qt is LGPL. PyQt is GPL or commercial. PySide is, I believe, 
the same as Qt itself. I'm not sure how mature or well-supported PySide 
is, in general.


wxPython is LGPL with a commercial exception clause, which allows you to 
use it in closed-source apps.


Tkinter, as part of the stlib, has a very liberal license (BSD-style), 
as does Tcl/Tk, which allows for free use in commercial apps.


Hope this helps,
Kevin

--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: learning curve

2012-12-27 Thread Dave Angel
On 12/27/2012 08:20 PM, Verde Denim wrote:
> Just getting into Py coding and not understanding why this code doesn't
> seem to do anything -

Welcome to Python.

Can I ask the obvious question?  How can this be your first program? 
Are you just typing it in from somewhere (eg. a book, or a website)?  If
you're just starting, you should postpone writing classes and GUI, and
do some simple things.  At least till you understand more about the
python programming model.

Secondary questions you should be answering with any question here: 
What versions of Python have you installed, and on what OS.  And what
version are you running and how?  And when you launch Python, how are
you launching it?  You have two files here.  Running either of these as
python scripts will do nothing useful, because neither has any top-level
code. beyond defining some classes.  So you should show the source for
the main.py that you actually run, and show what you type at the
terminal prompt.



-- 

DaveA

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


Re: How to get time.strptime()?

2012-12-27 Thread Gnarlodious
Thank you for a reasonable discussion of the problem, although I don't really 
understand what you said. This is a WSGI webapp configured for one-process and 
one-thread.

I can imagine my unorthodox handling of imported modules is suspect. To 
explain, my webapp first loads modules from a dict of allowed pages:

__init__
for module in self.allowedPages:
try:
self.Pages[module]=getattr(__import__(module), module)


This gives me a dict of objects like this:
self.Pages
{'Yijing': , 'Strand': 
, 'Gnomon': , 'Lexicon': , 'Dream': , 'Grid': 
}


I can then extract the first query string variable name and get the page 
content:
__call__
page='Gnomon'
xml=self.Pages[page](EnvDict, qList) # sends environ & query list


I don't know how several modules are normally handled in a CGI webapp, but this 
homegrown system has served me well. Threadlocking, however, may find this sort 
of referencing problematic. That would be my first suspicion.

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2012 12:01:16 -0800, mogul wrote:

> 'Aloha!
> 
> I'm new to python, got 10-20 years perl and C experience, all gained on
> unix alike machines hacking happily in vi, and later on in vim.
> 
> Now it's python, and currently mainly on my kubuntu desktop.
> 
> Do I really need a real IDE, as the windows guys around me say I do, or
> will vim, git, make and other standalone tools make it the next 20 years
> too for me?

You only *need* an IDE when your environment has feeble stand-alone 
tools, like Windows. As far as I am concerned, Unix (including Linux) is 
itself the ultimate in hot-plug IDEs.

http://blog.sanctum.geek.nz/series/unix-as-ide/

My own preferred IDE is:

* The KDE editor Kate[1];

* For preference, KDE's Konsole with multiple tabs, although any decent 
terminal app will do:

- one tab for file system operations (e.g. renaming files) and source code
  control using hg or git;
- one for running the script or stand-alone application I am writing,
  e.g. "python myscript.py", or if a library, for running unittests
  or doctests, e.g. "python -m doctest mylibrary.py"
- at least one for running an interactive Python shell for testing code,
  reading documentation ("help(some_object)") etc.
- anything else needed e.g. monitoring system load with top, etc.

* A browser for searching the web and accessing the Python docs.

I've never really got into automatic refactoring tools, but if I needed 
something more powerful than my editor's Find And Replace, I would 
investigate Bicycle Repair Man, or Rope. At a pinch, there's always sed, 
although I'm not a sed expert. (I can just about spell it... *wink*)

I'm sure that IDEs have their good points, but in my experience whatever 
good points they have are overshadowed by the negatives (e.g. a clunky 
editor that doesn't respond instantly when you type). A Swiss Army Knife 
might be the best Swiss Army Knife money can buy, but in general it is no 
substitute for a toolbox filled with independent tools.

In sports, it is said that "a champion team will beat a team of 
champions", but in software the opposite is the case: a set of excellent 
single-purpose tools is usually more powerful than a single tool that 
tries to do it all.

Having said all that, if somebody has a personal preference for a 
specific IDE, then good for them, I certainly wouldn't tell them that 
they shouldn't use it.



[1] KDE 3 only. KDE 4 is unspeakable. Gedit from Gnome 2 is almost a good 
substitute.

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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread Jamie Paul Griffin
* mogul  [2012-12-27 12:01:16 -0800]:

> 'Aloha!
> 
> I'm new to python, got 10-20 years perl and C experience, all gained on unix 
> alike machines hacking happily in vi, and later on in vim.
> 
> Now it's python, and currently mainly on my kubuntu desktop.
> 
> Do I really need a real IDE, as the windows guys around me say I do, or will 
> vim, git, make and other standalone tools make it the next 20 years too for 
> me? 
> 
> Oh, by the way, after 7 days I'm completely in love with this python thing. I 
> should have made the switch much earlier!
> 
> /mogul %-)

If these are the tools you're used to, stick with them. 

I have a tmux session with however many terminals open I need. I use the
traditional vi editor (not vim) and the python shell/interpreter as well
as the UNIX tools I need. A web browser and a separate urxvt window for
my mutt client when I need to mail a list for some help. That's it. 

The benefit of the tmux client (terminal multiplexer) is that I can see
all the screens at the same time and quickly switch between them. I
believe Linux has screen(1) which does the same thing. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am facing an issue while decoding json string using json.loads

2012-12-27 Thread sajuptpm
Hi,

Fixed:
=

urllib.unquote is messing up the JSON. Reverse the
order of unquote, and loads, i.e., do a json.loads on
the original string, and then urllib.unquote the components
that need unquote.

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