Re: pymongo and attribute dictionaries

2015-02-04 Thread Steven D'Aprano
Vito De Tullio wrote:

> Steven D'Aprano wrote:
> 
>>> This just does not roll of the fingers well. Too many “reach for
>>> modifier keys” in a row.
>> 
>> *One* modifier key in a row is too many?
>> 
>> s o m e SHIFT D o c [ ' SHIFT _ i d ' ]
> 
> I'm not OP, but as side note... not everyone has "[" as a direct character
> on the keyboard. I need to press "AltGr" + "è" (and "AltGr" + "+" to get
> "]"), so I can feel the OP lamenting :)

Point taken. Thank you.


-- 
Steven

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


Re: pymongo and attribute dictionaries

2015-02-04 Thread Vito De Tullio
Steven D'Aprano wrote:

>> This just does not roll of the fingers well. Too many “reach for modifier
>> keys” in a row.
> 
> *One* modifier key in a row is too many?
> 
> s o m e SHIFT D o c [ ' SHIFT _ i d ' ]

I'm not OP, but as side note... not everyone has "[" as a direct character 
on the keyboard. I need to press "AltGr" + "è" (and "AltGr" + "+" to get 
"]"), so I can feel the OP lamenting :)

s o m e SHIFT D o c ALTGR è ' SHIFT - i d ' ALTRG +

-- 
By ZeD

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


Re: Usage of some pastebin service proposed

2015-02-04 Thread Ben Finney
Abhiram R  writes:

> I've noticed a lot of people enquiring about syntactic errors and email
> somewhat butchers the indentation every now and then and the actual error
> gets buried in this mess.

It is almost never email that butchers the indentation. It is the
mis-use of HTML in email.

The simplest solution is: don't compose email messages in HTML.

> So is it possible to let everyone know that they need to paste their
> code on some site like pastebin.com and give us the link here so help
> can be provided better?
>
> Just a thought :)

No, it's far better to have the code right in the body of the message
where it is available to everyone viewing the message at any point in
time, regardless of the temporal availability of some arbitrary URL at
some third-party service.

-- 
 \  “It is well to remember that the entire universe, with one |
  `\   trifling exception, is composed of others.” —John Andrew Holmes |
_o__)  |
Ben Finney

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


Usage of some pastebin service proposed

2015-02-04 Thread Abhiram R
Hey guys,
I've noticed a lot of people enquiring about syntactic errors and email
somewhat butchers the indentation every now and then and the actual error
gets buried in this mess. So is it possible to let everyone know that they
need to paste their code on some site like pastebin.com and give us the
link here so help can be provided better?

Just a thought :)

​Cheers
Abhiram R
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Indentation issues with python

2015-02-04 Thread Terry Reedy



class EventHubClient(object):  ...
def sendMessage(self,body,partition):

...
> ^

IndentationError: expected an indented block
***


and 'def' is not indented as it must be.  This must be covered in the 
tutorial.


--
Terry Jan Reedy

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


Re: Indentation issues with python

2015-02-04 Thread Ben Finney
syed khalid  writes:

>  I downloaded this code and am attempting to run it. I keep getting
> indentation error.

Indentation is crucial information in Python code. If it is lost, don't
waste time trying to guess it; instead, get the correct code.

How did you download it? You should download the code as a “plain text”
file.

-- 
 \ “I got some new underwear the other day. Well, new to me.” —Emo |
  `\   Philips |
_o__)  |
Ben Finney

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


Indentation issues with python

2015-02-04 Thread syed khalid
 I downloaded this code and am attempting to run it. I keep getting
indentation error. there is a way to handle it with a editor which can
recognize the tab or space issue. I have tried different options such as 2
or 3 spaces or tab to no avail.

I have encased the error mesage with line 23 between ""

import sys
import azure
import socket

from azure.servicebus import (
_service_bus_error_handler
)

from azure.servicebus.servicebusservice import (
ServiceBusService,
ServiceBusSASAuthentication
)

from azure.http import (
HTTPRequest,
HTTPError
)

from azure.http.httpclient import _HTTPClient

class EventHubClient(object):
def sendMessage(self,body,partition):eventHubHost =
"pac-ns.servicebus.windows.net"
httpclient = _HTTPClient(service_instance=self)
 
File "test1.py", line 23
def sendMessage(self,body,partition):
^
IndentationError: expected an indented block
***
sasKeyName = "SendPolicy"
sasKeyValue = "erENqf/5wdWCNEbCA9NsDIRqd5MRKdkii07+wezl/NU="

authentication = ServiceBusSASAuthentication(sasKeyName,sasKeyValue)

request = HTTPRequest()
request.method = "POST"
request.host = eventHubHost
request.protocol_override = "https"
request.path = "/myhub/publishers/" + partition +
"/messages?api-version=2014-05
"
request.body = body
request.headers.append(('Content-Type',
'application/atom+xml;type=entry;charset
=utf-8'))

authentication.sign_request(request, httpclient)

request.headers.append(('Content-Length', str(len(request.body)))



-- 
*Syed Khalid*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Steven D'Aprano
Ian Kelly wrote:

>> Extending this to wrap methods of classes is also left as an exercise.
>> (Hint: don't subclass. Search the ActiveState Python recipes for
>> "automatic delegation" by Alex Martelli.)
> 
> Do you mean this one?
> 
> http://code.activestate.com/recipes/52295-automatic-delegation-as-an-
alternative-to-inherita/
> 
> That's based on old-style classes. With new-style classes it fails to
> delegate dunder methods like __str__. That recipe should be considered
> obsolete.

I'm aware of the problem with dunder methods. But that's not an 
insurmountable problem, if you need your delegation recipe to support 
dunders (and you may not), it's fiddly and annoying to do so, but not 
impossible. There are at least two approaches:

- manually delegate to the dunders that you care about with hand-
  written dunder methods:

def __str__(self):
return type(self.proxied_object).__str__(self.proxied_object)
# or for people who prefer simplicity over correctness
# return self.proxied_object.__str__()


- write a decorator which inspects the class and automatically adds 
  explicit dunders for you. (There's a recipe on ActiveState for 
  that one too.)

Regardless of whether you start with Alex's recipe or not, the idea is to 
make a proxy for the pymongo classes, and delegate to it rather than 
subclass or re-invent the wheel. That's a basic design pattern, and if 
dunders are a problem in Python that Ruby or Java doesn't have, oh well, 
life wasn't meant to be easy.



-- 
Steven

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


Re: pymongo and attribute dictionaries

2015-02-04 Thread Ian Kelly
On Wed, Feb 4, 2015 at 3:38 PM, Steven D'Aprano
 wrote:
> Travis Griggs wrote:
>> This just does not roll of the fingers well. Too many “reach for modifier
>> keys” in a row.
>
> *One* modifier key in a row is too many?
>
> s o m e SHIFT D o c [ ' SHIFT _ i d ' ]

I think the point was meant to be the number of keys that need to be
reached for, not just the number of times Shift needs to be pressed.

> Extending this to wrap methods of classes is also left as an exercise.
> (Hint: don't subclass. Search the ActiveState Python recipes for "automatic
> delegation" by Alex Martelli.)

Do you mean this one?

http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/

That's based on old-style classes. With new-style classes it fails to
delegate dunder methods like __str__. That recipe should be considered
obsolete.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: unpyc3 - a python bytecode decompiler for Python3

2015-02-04 Thread Michael Torrie
On 02/04/2015 05:19 PM, sohcahto...@gmail.com wrote:
> They can take your computer and it doesn't matter if you've got your files on 
> Dropbox.
> 
>> "My dog ate my USB stick."
>>
>> :-)
> 
> I never used a USB stick for school work.
> 
> At this point, I'm probably sounding like a shill for Dropbox, but I'm really 
> not.  I imagine Google Drive offers the same features.  Access to your files 
> from the web, synchronization of local files among computers with access to 
> it, and the ability to retrieve and restore files from previous versions.

In my mind, they are all tools.  And no one tool should be used and
trusted above all others.

Anyone that's programming should be using version control, period.  But
that's not for backup, and backup can and should be used as well as
version control.  Everything I work on I commit to git regularly because
of the utility git gives me.  If I end up trying something that doesn't
pan out, I can retrace my steps (that's what branches are for). I don't
have to dig through two weeks of hourly backups to find out where it was
when I started making a change.  Backup and git serve two complementary
but different purposes.

As well as regularly committing code to Git, I run CrashPlan and on a
regular schedule (hourly perhaps) it copies all changes, committed or
not, and including the git repo itself to the cloud, and also to my
other computer, as well as my parents' computer.  CrashPlan makes this
stuff easy, so there's no reason not have redundancy.  As well, I
semi-regularly run a manual rsync backup to three different USB hard
drives on a rotating backup.

Is this overkill? I don't believe so.  It requires virtually no work on
my part.

I don't see any one cloud service as the best product.  Why not use them
all?  Encrypt if you need to, and sync hourly snapshots to google drive,
drop box, and any other free cloud service.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: unpyc3 - a python bytecode decompiler for Python3

2015-02-04 Thread sohcahtoa82
On Wednesday, January 28, 2015 at 4:30:11 PM UTC-8, Steven D'Aprano wrote:
> sohcahto...@gmail.com wrote:
> 
> > I recently finished my CS degree, and I had more than one professor say
> > that they won't take "My computer crashed and I lost everything!" as an
> > excuse for not being able to turn in homework.  
> 
> How about "My computer crashed and died and now I can't get to Dropbox to
> access my files"?

If you have access to a web browser, you have access to your Dropbox files.

I don't own a printer.  If I needed to print something for school, I just 
printed it from my Dropbox at school.

> "My computer got infected by ransomware which encrypted all my data files
> and blocks access to Dropbox."

Dropbox saves previous versions of files.  Just restore them from the last 
version you had before they got encrypted by the ransomware.  This can be done 
from any browser.
 
> "One of my housemates torrented a Linux tarball, and the MPAA wrongly
> identified it as a movie file. Purely on their say-so, my ISP disabled my
> account and banned me from the Internet. But all is not lost, if I move 45
> miles away, I can sign up with a different ISP!"

Not exactly a likely scenario, and still not a problem unless you're not 
allowed to access the internet from someone's WiFi.

> "Some dude I've never seen before gate-crashed our party and was smoking
> pot, and the police raided us and seized my computer and everybody's
> phones. My lawyer tells me the raid was illegal and if spend two or three
> hundred thousand dollars in legal fees, I'll probably be able to get my
> computer back within eight years or so."

They can take your computer and it doesn't matter if you've got your files on 
Dropbox.

> "My dog ate my USB stick."
> 
> :-)

I never used a USB stick for school work.

At this point, I'm probably sounding like a shill for Dropbox, but I'm really 
not.  I imagine Google Drive offers the same features.  Access to your files 
from the web, synchronization of local files among computers with access to it, 
and the ability to retrieve and restore files from previous versions.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: unpyc3 - a python bytecode decompiler for Python3

2015-02-04 Thread Dave Angel

On 01/28/2015 07:34 PM, Steven D'Aprano wrote:

Devin Jeanpierre wrote:


On Wed, Jan 28, 2015 at 1:40 PM, Chris Angelico  wrote:

On Thu, Jan 29, 2015 at 5:47 AM, Chris Kaynor 
wrote:

I use Google Drive for it for all the stuff I do at home, and use SVN
for all my personal projects, with the SVN depots also in Drive. The
combination works well for me, I can transfer between my desktop and
laptop freely, and have full revision history for debugging issues.


I just do everything in git, no need for either Drive or something as
old as SVN. Much easier. :)


Git doesn't help if you lose your files in between commits,


Sure it does? You just lose the changes made since the previous commit, but
that's no different from restoring from backup. The restored file is only
as up to date as the last time a backup was taken.



or if you
lose the entire directory between pushes.


Then restore from wherever you are pushing to.

But as Devin says, any backup strategy that requires the user to make a
backup is untrustworthy. I'm hoping that the next generation of DVCSs will
support continuous commits, the next generation of editors support
continuous saves, and the only time you need interact with the editor
(apart from, you know, actual editing) is to tell it "start a new branch
now".


In emacs, bnd the git add, git commit to Ctrl-x - s, and saving also 
means committing.


My backup system uses MD5's to decide which files need backing up, so 
theoretically it shouldn't cost too much to backup the git archives once 
daily.  It's all still under development, however.  (I've been offline 
for two weeks, developing and running the backup system, and preparing 
for a complete reinstall of a corrupted system)




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


Re: Cairo module

2015-02-04 Thread Cousin Stanley


> You might consider using python-imaging
> to display the image after writing it
> from cairo 
> 
> import image

  import statement should be  

  import Image

  note uppercase I 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cairo module

2015-02-04 Thread Cousin Stanley

> 
> Could matplotlib be used to show the image?

  You might consider using python-imaging
  to display the image after writing it 
  from cairo  

  import image
  
  surface.write_to_png ( "x_surface.png" ) 

  img = Image.open( "x_surface.png" )

  img.show( command = 'display' )


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Steven D'Aprano
Travis Griggs wrote:

> I really like pymongo. And I really like Python. But one thing my fingers
> really get tired of typing is
> 
> someDoc[‘_’id’]

I've never used pymongo, so can't comment from experience, but surely any
library which encourages, if not requires, that you access private data _id
doesn't inspire me with confidence.

Also, the above is a syntax error, but you probably know that.


> This just does not roll of the fingers well. Too many “reach for modifier
> keys” in a row.

*One* modifier key in a row is too many? 

s o m e SHIFT D o c [ ' SHIFT _ i d ' ]


You can cut that by 50% by changing your naming convention:

somedoc['_id']

While you're at it, you can cut the total number of keystrokes too:

doc['_id']


If there are a fixed set of key names that you use repeatedly, you can do
this:


ID, FE, FI, FO, FUM = '_id', '_fe', '_fi', '_fo', '_fum'
# later
someDoc[ID]


Ah, but that needs the shiftkey... well, I guess that PEP 8 naming
conventions aren't compulsory, and so long as you don't need the built-in
`id` function, it's okay to shadow it (consenting adults and all that), so:

id, fe, fi, fo, fum = '_id', '_fe', '_fi', '_fo', '_fum'
# later
someDoc[id]


> I would rather use
> someDoc._id

That has exactly the same number of modifier keys as your original example.
I'm starting to sense that you don't actually care about the SHIFT key...


[...]
> The problem I have is not how to do the AttributeDictionary subclass,
> there are plenty of those examples. The problem is that the pymongo APIs
> already return dictionaries. In a language (Smalltalk, Objective-C, Ruby)
> that supports class extensions, that would be my first tool of choice to
> solve this problem. I’d just extend Dictionary to behave the way I want
> and be done with it. I can’t do that in Python though. I guess I could
> make my own module that subclasses the relevant pymongo classes, and do
> super() calling implementations of all of the relevant methods, coercing
> the return type. That is a maintenance headache though.
> 
> What are my options, if any?

HingTFU comes to mind :-)

But as "an academic exercise" *nudge nudge, wink wink* there's always the
Adaptor design pattern. Import as much or as little of pymongo as you need,
wrap it in an adaptor, and use that. There are lots of different ways that
you could do this, some more monkey-patchy than others.


# pymongo adaptor module (untested)
from pymongo import *

import functools

def wrap(name):
"""Wrap function called `name` so it returns an AttrDict instead 
of dict. May the gods have mercy on your soul."""
func = globals()[name]
@functools.wraps(func)
def inner(*args, **kwargs):
result = func(*args, **kwargs)
if isinstance(result, dict):
result = AttrDict(result)
return result
globals()[name] = func


FUNCTIONS_THAT_RETURN_DICTS = ['this', 'that', 'another']
for name in FUNCTIONS_THAT_RETURN_DICTS:
wrap(name)



Extending this to use introspection to automatically detect the pymongo
functions instead of having to list them manually is left as an exercise.
(Hint: import pymongo; for obj in vars(pymongo): ...).

Extending this to wrap methods of classes is also left as an exercise.
(Hint: don't subclass. Search the ActiveState Python recipes for "automatic
delegation" by Alex Martelli.)

And now just use the adaptor module instead of the original.


-- 
Steven

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


Re: pymongo and attribute dictionaries

2015-02-04 Thread Rob Gaddi
On Wed, 04 Feb 2015 13:54:22 -0700, Ian Kelly wrote:

> I'd prefer map (or itertools.imap in Python 2) over the inline generator
> in this case:
> 
> for doc in map(Doc, client.db.radios.find({’_id': {’$regex’:
> ‘^[ABC]'}})):
> pprint(doc)
> 
> Or if you like, a utility function wrapping the same.
> 
> def docs(dicts):
> return map(Doc, dicts)

Or, if you really wanted to be crazy

for d in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
doc = Doc(d)
pprint(doc)

I mean, I realize linefeeds don't grow on trees and all... 


-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cairo module

2015-02-04 Thread Poul Riis
Could you be a little more specific (giving, for instance, a full working 
example)?
I tried to interchange
 surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) 
with
 surface = cairo.Win32Surface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) 
but that didn't seem to work.

Could matplotlib be used to show the image?

Poul Riis
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-04 Thread Chris Angelico
On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten <__pete...@web.de> wrote:
> Another alternative is to put a list literal on the lefthand side:
>
 def f(): yield 42
>
> ...
 [result] = f()
 result
> 42

Huh, was not aware of that alternate syntax.

> (If you're worried: neither the list nor the tuple will be created; the
> bytecode is identical in both cases)

It can't possibly be created anyway. Python doesn't have a notion of
"assignable thing that, when assigned to, will assign to something
else" like C's pointers or C++'s references. There's nothing that you
could put into the list that would have this behaviour.

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


Re: pymongo and attribute dictionaries

2015-02-04 Thread Ian Kelly
On Wed, Feb 4, 2015 at 1:16 PM, Travis Griggs  wrote:
> Yes, that is clever. So if you wanted to minimize the amount of typing you 
> had to do at all of your pymongo API call sites, what strategy would you use 
> to keep that relatively terse?
>
> Is the following the right approach to take?
>
> class Doc(object):
> def __init__(self, target):
> self.__dict__ = target
>
> and then something like
>
> for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
> pprint(doc)
>
> changes to
>
> for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’: 
> ‘^[ABC]'}})):
> pprint(doc)
>
> Are there other approaches? Feel free to impress me with evil abuses in the 
> interest of academic enrichment...

I'd prefer map (or itertools.imap in Python 2) over the inline
generator in this case:

for doc in map(Doc, client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}})):
pprint(doc)

Or if you like, a utility function wrapping the same.

def docs(dicts):
return map(Doc, dicts)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Ian Kelly
On Wed, Feb 4, 2015 at 1:16 PM, Travis Griggs  wrote:
> Yes, that is clever. So if you wanted to minimize the amount of typing you 
> had to do at all of your pymongo API call sites, what strategy would you use 
> to keep that relatively terse?
>
> Is the following the right approach to take?
>
> class Doc(object):
> def __init__(self, target):
> self.__dict__ = target
>
> and then something like
>
> for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
> pprint(doc)
>
> changes to
>
> for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’: 
> ‘^[ABC]'}})):
> pprint(doc)
>
> Are there other approaches? Feel free to impress me with evil abuses in the 
> interest of academic enrichment...

I'd prefer map (or itertools.imap in Python 2) over the inline
generator in this case:

for doc in map(Doc, client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}})):
pprint(doc)

Or if you like, a utility function wrapping the same.

def docs(dicts):
return map(Doc, dicts)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Gregory Ewing

Travis Griggs wrote:

for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}): pprint(doc)

changes to

for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’:
‘^[ABC]'}})): pprint(doc)

Are there other approaches? Feel free to impress me with evil abuses in the
interest of academic enrichment...


You could encapsulate some of that in a helper function such as

def docs(source):
   for d in source:
  yield Doc(d)

then your example becomes

for doc in docs(client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}})):
   pprint(doc)

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Chris Kaynor
On Wed, Feb 4, 2015 at 12:16 PM, Travis Griggs  wrote:
>
>> On Feb 4, 2015, at 9:22 AM, Ian Kelly  wrote:
>>
>> On Wed, Feb 4, 2015 at 9:50 AM, Travis Griggs  wrote:
>>> I really like pymongo. And I really like Python. But one thing my fingers 
>>> really get tired of typing is
>>>
>>> someDoc[‘_’id’]
>>>
>>> This just does not roll of the fingers well. Too many “reach for modifier 
>>> keys” in a row. I would rather use
>>>
>>> someDoc._id
>>>
>>> Googling shows that I’m not the first to want to do this in the general 
>>> sense (e.g. 
>>> http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python).
>>>
>>> Arguments aside of whether this should or shouldn’t be done, I want to know 
>>> how I might solve this with Python. Consider it an academic pursuit.
>>>
>>> The problem I have is not how to do the AttributeDictionary subclass, there 
>>> are plenty of those examples. The problem is that the pymongo APIs already 
>>> return dictionaries. In a language (Smalltalk, Objective-C, Ruby) that 
>>> supports class extensions, that would be my first tool of choice to solve 
>>> this problem. I’d just extend Dictionary to behave the way I want and be 
>>> done with it. I can’t do that in Python though. I guess I could make my own 
>>> module that subclasses the relevant pymongo classes, and do super() calling 
>>> implementations of all of the relevant methods, coercing the return type. 
>>> That is a maintenance headache though.
>>>
>>> What are my options, if any?
>>
>> You could construct the AttributeDictionary by copying the dict
>> returned from pymongo. The question then is whether the copying would
>> be too expensive or not.
>>
>> Alternately, you could just wrap the dictionaries returned by pymongo
>> in an object. Something like this should be all you need:
>>
>> class AttrDictWrapper(object):
>>def __init__(self, the_dict):
>>self.__dict__ = the_dict
>>
> d = AttrDictWrapper({'spam': 42, 'ham': False})
> d.spam
>> 42
> d.ham
>> False
>>
>
> Yes, that is clever. So if you wanted to minimize the amount of typing you 
> had to do at all of your pymongo API call sites, what strategy would you use 
> to keep that relatively terse?
>
> Is the following the right approach to take?
>
> class Doc(object):
> def __init__(self, target):
> self.__dict__ = target
>
> and then something like
>
> for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
> pprint(doc)
>
> changes to
>
> for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’: 
> ‘^[ABC]'}})):
> pprint(doc)
>
> Are there other approaches? Feel free to impress me with evil abuses in the 
> interest of academic enrichment...

One possible approach, that may or may not work based on the use case,
would be to monkey patch the module. The main drawback is that if it
is used in places that do not expect the wrapper, it could well break.
Untested code:

import types
def monkey(module):
for attr in dir(module):
if attr.startswith('_'): # Ignore private attributes.
continue
object = getattr(module, attr)
if not isinstance(object, types.Function): # Ignore non-functions.
continue
setattr(module, attr, lambda *args, **kwargs:
AttrDictWrapper(object(*args, **kwargs)))


Another option would be to create a wrapper module. This option has
the side-effect that it would be difficult to recurse into classes, as
you would have to copy the class. This would be very similar (again,
untested):
import types # Note that this may get overridden in the function,
which could cause problems.
def makeWrapper(module):
for attr in dir(module):
if attr.startswith('_'): # Ignore private attributes.
continue
object = getattr(module, attr)
if not isinstance(object, types.Function): # Ignore non-functions.
object = lambda *args, **kwargs:
AttrDictWrapper(object(*args, **kwargs))
globals()[attr] = object


Both of these are written to (attempt) to replace all instances.
Obviously, this could be reduced to a white-list or additional checks
could be made to restrict the wrapped sets. I would be VERY weary of
actually using the first due to the noted drawback. The second is
safer, but you would want to be careful to test it for unexpected
side-effects.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymongo and attribute dictionaries

2015-02-04 Thread Travis Griggs

> On Feb 4, 2015, at 9:22 AM, Ian Kelly  wrote:
> 
> On Wed, Feb 4, 2015 at 9:50 AM, Travis Griggs  wrote:
>> I really like pymongo. And I really like Python. But one thing my fingers 
>> really get tired of typing is
>> 
>> someDoc[‘_’id’]
>> 
>> This just does not roll of the fingers well. Too many “reach for modifier 
>> keys” in a row. I would rather use
>> 
>> someDoc._id
>> 
>> Googling shows that I’m not the first to want to do this in the general 
>> sense (e.g. 
>> http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python).
>> 
>> Arguments aside of whether this should or shouldn’t be done, I want to know 
>> how I might solve this with Python. Consider it an academic pursuit.
>> 
>> The problem I have is not how to do the AttributeDictionary subclass, there 
>> are plenty of those examples. The problem is that the pymongo APIs already 
>> return dictionaries. In a language (Smalltalk, Objective-C, Ruby) that 
>> supports class extensions, that would be my first tool of choice to solve 
>> this problem. I’d just extend Dictionary to behave the way I want and be 
>> done with it. I can’t do that in Python though. I guess I could make my own 
>> module that subclasses the relevant pymongo classes, and do super() calling 
>> implementations of all of the relevant methods, coercing the return type. 
>> That is a maintenance headache though.
>> 
>> What are my options, if any?
> 
> You could construct the AttributeDictionary by copying the dict
> returned from pymongo. The question then is whether the copying would
> be too expensive or not.
> 
> Alternately, you could just wrap the dictionaries returned by pymongo
> in an object. Something like this should be all you need:
> 
> class AttrDictWrapper(object):
>def __init__(self, the_dict):
>self.__dict__ = the_dict
> 
 d = AttrDictWrapper({'spam': 42, 'ham': False})
 d.spam
> 42
 d.ham
> False
> 

Yes, that is clever. So if you wanted to minimize the amount of typing you had 
to do at all of your pymongo API call sites, what strategy would you use to 
keep that relatively terse?

Is the following the right approach to take?

class Doc(object):
def __init__(self, target):
self.__dict__ = target

and then something like

for doc in client.db.radios.find({’_id': {’$regex’: ‘^[ABC]'}}):
pprint(doc)

changes to

for doc in ((Doc(d) for d in client.db.radios.find({’_id': {’$regex’: 
‘^[ABC]'}})):
pprint(doc)

Are there other approaches? Feel free to impress me with evil abuses in the 
interest of academic enrichment...

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


Re: meaning of: line, =

2015-02-04 Thread Peter Otten
Rustom Mody wrote:

> Well its cryptic and confusing (to me at least)
> And is helped by adding 2 characters:
> 
> (result,) = f()
> 
> instead of
> 
> result, = f()

Another alternative is to put a list literal on the lefthand side:

>>> def f(): yield 42

... 
>>> [result] = f()
>>> result
42

(If you're worried: neither the list nor the tuple will be created; the 
bytecode is identical in both cases)

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


Re: pymongo and attribute dictionaries

2015-02-04 Thread Ian Kelly
On Wed, Feb 4, 2015 at 9:50 AM, Travis Griggs  wrote:
> I really like pymongo. And I really like Python. But one thing my fingers 
> really get tired of typing is
>
> someDoc[‘_’id’]
>
> This just does not roll of the fingers well. Too many “reach for modifier 
> keys” in a row. I would rather use
>
> someDoc._id
>
> Googling shows that I’m not the first to want to do this in the general sense 
> (e.g. 
> http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python).
>
> Arguments aside of whether this should or shouldn’t be done, I want to know 
> how I might solve this with Python. Consider it an academic pursuit.
>
> The problem I have is not how to do the AttributeDictionary subclass, there 
> are plenty of those examples. The problem is that the pymongo APIs already 
> return dictionaries. In a language (Smalltalk, Objective-C, Ruby) that 
> supports class extensions, that would be my first tool of choice to solve 
> this problem. I’d just extend Dictionary to behave the way I want and be done 
> with it. I can’t do that in Python though. I guess I could make my own module 
> that subclasses the relevant pymongo classes, and do super() calling 
> implementations of all of the relevant methods, coercing the return type. 
> That is a maintenance headache though.
>
> What are my options, if any?

You could construct the AttributeDictionary by copying the dict
returned from pymongo. The question then is whether the copying would
be too expensive or not.

Alternately, you could just wrap the dictionaries returned by pymongo
in an object. Something like this should be all you need:

class AttrDictWrapper(object):
def __init__(self, the_dict):
self.__dict__ = the_dict

>>> d = AttrDictWrapper({'spam': 42, 'ham': False})
>>> d.spam
42
>>> d.ham
False
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic generator question

2015-02-04 Thread Ian Kelly
On Wed, Feb 4, 2015 at 6:23 AM, Neal Becker  wrote:
> class rpt:
>   def __init__ (self, value, rpt):
> self.value = value; self.rpt = rpt
>   def __call__ (self):
> for i in range (self.rpt):
>   yield self.value

Note that this class is just reimplementing itertools.repeat.

>>> list(itertools.repeat('hello', 5))
['hello', 'hello', 'hello', 'hello', 'hello']
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-04 Thread Ethan Furman
On 02/04/2015 07:04 AM, Chris Angelico wrote:
> On Thu, Feb 5, 2015 at 1:38 AM, Albert-Jan Roskam  wrote:
>> I have also never seen this before, but perhaps this:
>>
> f = lambda: [42]
> result, = f()
> result
>> 42
>>
>> ... is slightly cleaner than this:
> result = f()[0]
> result
>> 42
> 
> They're not technically identical. If the thing returned is
> subscriptable (as with your list example), then I would definitely
> subscript it rather than unpacking;

By unpacking you are also double checking that the returned iterable contains 
exactly one item; more or less will cause
an exception -- you only get half that check if you index.

--
~Ethan~



signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


pymongo and attribute dictionaries

2015-02-04 Thread Travis Griggs
I really like pymongo. And I really like Python. But one thing my fingers 
really get tired of typing is

someDoc[‘_’id’]

This just does not roll of the fingers well. Too many “reach for modifier keys” 
in a row. I would rather use

someDoc._id

Googling shows that I’m not the first to want to do this in the general sense 
(e.g. 
http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python).

Arguments aside of whether this should or shouldn’t be done, I want to know how 
I might solve this with Python. Consider it an academic pursuit.

The problem I have is not how to do the AttributeDictionary subclass, there are 
plenty of those examples. The problem is that the pymongo APIs already return 
dictionaries. In a language (Smalltalk, Objective-C, Ruby) that supports class 
extensions, that would be my first tool of choice to solve this problem. I’d 
just extend Dictionary to behave the way I want and be done with it. I can’t do 
that in Python though. I guess I could make my own module that subclasses the 
relevant pymongo classes, and do super() calling implementations of all of the 
relevant methods, coercing the return type. That is a maintenance headache 
though.

What are my options, if any?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic generator question

2015-02-04 Thread Steven D'Aprano
Neal Becker wrote:

> I have an object that expects to call a callable to get a value:
> 
> class obj:
>   def __init__ (self, gen):
> self.gen = gen
>   def __call__ (self):
> return self.gen()

As written, there is no need for this "obj" class, it just adds a pointless
layer of indirection. Perhaps it was written by a Java programmer?

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html

Instead of:

x = obj(something_callable)
# later
result = x()

just do:

x = something_callable
result = x()

or even

result = something_callable()


 
> Now I want gen to be a callable that repeats N times.

What happens on the sixth time? The world ends? Most callables can be called
indefinitely.

I'm going to assume an exception. Later I'll use a RuntimeException, but you
can do anything you like.


> I'm thinking, this sounds perfect for yield
> 
> class rpt:
>   def __init__ (self, value, rpt):
> self.value = value; self.rpt = rpt
>   def __call__ (self):
> for i in range (self.rpt):
>   yield self.value
> 
> so I would do:
> 
> my_rpt_obj = obj (rpt ('hello', 5))
> 
> to repeat 'hello' 5 times (for example).
> 
> But this doesn't work.  when obj calls self.gen(), that returns a
> generator, not the next value.
> 
> How can I make this work?  I can't change the interface of the existing
> class obj, which expects a callable to get the next value.

The built-in function `next` almost does what we want, except the exception
raised is inappropriate. Unless you are very careful, you don't want to
allow StopIteration to propagate, lest it be caught in an unexpected place
and cause surprises. (Not the pleasant kind.)


py> from functools import partial
py> f = partial(next, rpt("hello", 2)())  # note the extra parens
py> f()
'hello'
py> f()
'hello'
py> f()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration


But I wouldn't use rpt as given. I'd say:

def repeat(obj, count):
for i in range(count):
yield obj
raise RuntimeError  # or whatever

mycallable = partial(next, repeat("hello", 5))  # no extra parens

And now pass mycallable to your other class.



P.S. your naming conventions give me a blood clot. Class "rpt" taking an
argument "rpt" -- I lost six months of life just from reading that.


-- 
Steven

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


Re: basic generator question

2015-02-04 Thread Peter Otten
Neal Becker wrote:

> I have an object that expects to call a callable to get a value:
> 
> class obj:
>   def __init__ (self, gen):
> self.gen = gen
>   def __call__ (self):
> return self.gen()
 
As written that looks a bit like

if boolean_expression == True: ...

as you could replace

inst = obj(callable)

with 

inst = callable

but that may be an artifact of the example.

> Now I want gen to be a callable that repeats N times.  I'm thinking, this
> sounds perfect for yield
> 
> class rpt:
>   def __init__ (self, value, rpt):
> self.value = value; self.rpt = rpt
>   def __call__ (self):
> for i in range (self.rpt):
>   yield self.value
> 
> so I would do:
> 
> my_rpt_obj = obj (rpt ('hello', 5))
> 
> to repeat 'hello' 5 times (for example).

What do you expect to happen when my_rpt_obj is called the sixth time?
 
> But this doesn't work.  when obj calls self.gen(), that returns a
> generator, not the next value.
> 
> How can I make this work?  I can't change the interface of the existing
> class obj, which expects a callable to get the next value.

>>> class Obj:
... def __init__(self, gen):
... self.gen = iter(gen)
... def __call__(self):
... return next(self.gen)
... 
>>> class Repeat:
... def __init__(self, value, times):
... self.value = value
... self.times = times
... def __iter__(self):
... for i in range(self.times):
... yield self.value
... 
>>> r = Obj(Repeat("hello", 3))
>>> r()
'hello'
>>> r()
'hello'
>>> r()
'hello'
>>> r()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in __call__
StopIteration

Instead of the Repeat class you may use a generator:

>>> def repeat(value, times):
... for i in range(times):
... yield value
... 
>>> r = Obj(repeat("hello", 2))
>>> r()
'hello'
>>> r()
'hello'
>>> r()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in __call__
StopIteration

This is for demonstration purposes as there is already itertools.repeat():

>>> import itertools
>>> r = Obj(itertools.repeat("world", 2))
>>> r()
'world'
>>> r()
'world'
>>> r()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in __call__
StopIteration

Depending on your actual need you may also omit the Obj() class:

>>> import functools
>>> r = functools.partial(next, itertools.repeat("goodbye", 2))
>>> r()
'goodbye'
>>> r()
'goodbye'
>>> r()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

Somewhat less formal you can bind the iterator method directly:

>>> r = itertools.repeat("GOODBYE", 2).__next__ # next in Python 2
>>> r()
'GOODBYE'
>>> r()
'GOODBYE'
>>> r()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration


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


Re: basic generator question

2015-02-04 Thread Joel Goldstick
On Wed, Feb 4, 2015 at 10:19 AM, Joel Goldstick 
wrote:

>
>
> On Wed, Feb 4, 2015 at 9:32 AM, Chris Angelico  wrote:
>
>> On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker  wrote:
>> > Now I want gen to be a callable that repeats N times.  I'm thinking,
>> this
>> > sounds perfect for yield
>> >
>> > class rpt:
>> >   def __init__ (self, value, rpt):
>> > self.value = value; self.rpt = rpt
>> >   def __call__ (self):
>> > for i in range (self.rpt):
>> >   yield self.value
>> >
>> > so I would do:
>> >
>> > my_rpt_obj = obj (rpt ('hello', 5))
>> >
>> > to repeat 'hello' 5 times (for example).
>> >
>> > But this doesn't work.  when obj calls self.gen(), that returns a
>> generator, not
>> > the next value.
>> >
>> > How can I make this work?  I can't change the interface of the existing
>> class
>> > obj, which expects a callable to get the next value.
>>
>
> Can you actually show your code and the traceback?
>

When you do rpt('hello',5)) you create an instance of rpt but you don't
actually invoke it.

maybe try:

my_rpt_obj = obj(rpt('hello',5))()

If I'm thinking straight, its the final () that actually cause your
__call__ to happen.

>
>> So, if I understand you correctly, you want your rpt object to return
>> 'hello' five times to five consecutive calls?
>>
>> >>> a = rpt()
>> >>> a()
>> 'hello'
>> >>> a()
>> 'hello'
>> >>> a()
>> 'hello'
>> >>> a()
>> 'hello'
>> >>> a()
>> 'hello'
>>
>> You could do that with a generator by repeatedly calling next() on it,
>> or you could just keep track of the number of times you were called:
>>
>> class rpt:
>>   def __init__ (self, value, rpt):
>> self.value = value; self.rpt = rpt
>>   def __call__ (self):
>> if self.rpt:
>>   self.rpt -= 1
>>   return self.value
>># ... otherwise?
>>
>> Up to you to figure out what to do when self.rpt hits zero.
>>
>> ChrisA
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> Joel Goldstick
> http://joelgoldstick.com
>



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic generator question

2015-02-04 Thread Joel Goldstick
On Wed, Feb 4, 2015 at 9:32 AM, Chris Angelico  wrote:

> On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker  wrote:
> > Now I want gen to be a callable that repeats N times.  I'm thinking, this
> > sounds perfect for yield
> >
> > class rpt:
> >   def __init__ (self, value, rpt):
> > self.value = value; self.rpt = rpt
> >   def __call__ (self):
> > for i in range (self.rpt):
> >   yield self.value
> >
> > so I would do:
> >
> > my_rpt_obj = obj (rpt ('hello', 5))
> >
> > to repeat 'hello' 5 times (for example).
> >
> > But this doesn't work.  when obj calls self.gen(), that returns a
> generator, not
> > the next value.
> >
> > How can I make this work?  I can't change the interface of the existing
> class
> > obj, which expects a callable to get the next value.
>

Can you actually show your code and the traceback?

>
> So, if I understand you correctly, you want your rpt object to return
> 'hello' five times to five consecutive calls?
>
> >>> a = rpt()
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
>
> You could do that with a generator by repeatedly calling next() on it,
> or you could just keep track of the number of times you were called:
>
> class rpt:
>   def __init__ (self, value, rpt):
> self.value = value; self.rpt = rpt
>   def __call__ (self):
> if self.rpt:
>   self.rpt -= 1
>   return self.value
># ... otherwise?
>
> Up to you to figure out what to do when self.rpt hits zero.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-04 Thread Rustom Mody
On Wednesday, February 4, 2015 at 8:14:29 PM UTC+5:30, Albert-Jan Roskam wrote:
> - Original Message -
> 
> > From: Chris Angelico 
> > Sent: Wednesday, February 4, 2015 3:24 PM
> > Subject: Re: meaning of: line, =
> > 
> > On Thu, Feb 5, 2015 at 1:08 AM, ast wrote:
> >>  I dont understand why there is a comma just after line in the following
> >>  command:
> >> 
> >>  line, = plt.plot(x, np.sin(x), '--', linewidth=2)
> >> 
> >> 
> >>  I never saw that before
> >> 
> >>  Found here:
> >> 
> > http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
> >> 
> > 
> > That's a slightly unusual form of unpacking. Compare:
> > 
> > def get_values():
> > return 5, 7, 2
> > 
> > x, y, z = get_values()
> > 
> > This is like "x = 5; y = 7; z = 2", because it unpacks the 
> > function's
> > return value into those three targets.
> > 
> > What you have is exactly the same, except that it has only one target.
> > So it's expecting plt.plot() to return an iterable with exactly one
> > thing in it, and it'll unpack it and put that thing into line:
> > 
> > def get_packaged_value():
> > return [42]
> > 
> > x, = get_packaged_value()
> > 
> > This is equivalent to "x = 42". I don't know matplotlib, so I 
> > don't
> > know what it's returning or why, but as long as it's iterable and
> > yields exactly one thing, this will work.
> 
> 
> 
> I have also never seen this before, but perhaps this:
> 
> >>> f = lambda: [42]
> >>> result, = f()
> >>> result
> 42
> 
> ... is slightly cleaner than this:
> >>> result = f()[0]
> >>> result
> 42

Well its cryptic and confusing (to me at least)
And is helped by adding 2 characters:

(result,) = f()

instead of 

result, = f()

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


Re: meaning of: line, =

2015-02-04 Thread Chris Angelico
On Thu, Feb 5, 2015 at 1:38 AM, Albert-Jan Roskam  wrote:
> I have also never seen this before, but perhaps this:
>
 f = lambda: [42]
 result, = f()
 result
> 42
>
> ... is slightly cleaner than this:
 result = f()[0]
 result
> 42

They're not technically identical. If the thing returned is
subscriptable (as with your list example), then I would definitely
subscript it rather than unpacking; but if it's something iterable but
not subscriptable, the unpack will still work.

>>> def f(): yield 42
...
>>> result, = f()
>>> result
42
>>> result = f()[0]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'generator' object is not subscriptable

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


Re: meaning of: line, =

2015-02-04 Thread Albert-Jan Roskam


- Original Message -

> From: Chris Angelico 
> To: 
> Cc: "python-list@python.org" 
> Sent: Wednesday, February 4, 2015 3:24 PM
> Subject: Re: meaning of: line, =
> 
> On Thu, Feb 5, 2015 at 1:08 AM, ast  wrote:
>>  I dont understand why there is a comma just after line in the following
>>  command:
>> 
>>  line, = plt.plot(x, np.sin(x), '--', linewidth=2)
>> 
>> 
>>  I never saw that before
>> 
>>  Found here:
>> 
> http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
>> 
> 
> That's a slightly unusual form of unpacking. Compare:
> 
> def get_values():
> return 5, 7, 2
> 
> x, y, z = get_values()
> 
> This is like "x = 5; y = 7; z = 2", because it unpacks the 
> function's
> return value into those three targets.
> 
> What you have is exactly the same, except that it has only one target.
> So it's expecting plt.plot() to return an iterable with exactly one
> thing in it, and it'll unpack it and put that thing into line:
> 
> def get_packaged_value():
> return [42]
> 
> x, = get_packaged_value()
> 
> This is equivalent to "x = 42". I don't know matplotlib, so I 
> don't
> know what it's returning or why, but as long as it's iterable and
> yields exactly one thing, this will work.



I have also never seen this before, but perhaps this:

>>> f = lambda: [42]
>>> result, = f()
>>> result
42

... is slightly cleaner than this:
>>> result = f()[0]
>>> result
42
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic generator question

2015-02-04 Thread Chris Angelico
On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker  wrote:
> Now I want gen to be a callable that repeats N times.  I'm thinking, this
> sounds perfect for yield
>
> class rpt:
>   def __init__ (self, value, rpt):
> self.value = value; self.rpt = rpt
>   def __call__ (self):
> for i in range (self.rpt):
>   yield self.value
>
> so I would do:
>
> my_rpt_obj = obj (rpt ('hello', 5))
>
> to repeat 'hello' 5 times (for example).
>
> But this doesn't work.  when obj calls self.gen(), that returns a generator, 
> not
> the next value.
>
> How can I make this work?  I can't change the interface of the existing class
> obj, which expects a callable to get the next value.

So, if I understand you correctly, you want your rpt object to return
'hello' five times to five consecutive calls?

>>> a = rpt()
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'

You could do that with a generator by repeatedly calling next() on it,
or you could just keep track of the number of times you were called:

class rpt:
  def __init__ (self, value, rpt):
self.value = value; self.rpt = rpt
  def __call__ (self):
if self.rpt:
  self.rpt -= 1
  return self.value
   # ... otherwise?

Up to you to figure out what to do when self.rpt hits zero.

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


Re: meaning of: line, =

2015-02-04 Thread Chris Angelico
On Thu, Feb 5, 2015 at 1:08 AM, ast  wrote:
> I dont understand why there is a comma just after line in the following
> command:
>
> line, = plt.plot(x, np.sin(x), '--', linewidth=2)
>
>
> I never saw that before
>
> Found here:
> http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
>

That's a slightly unusual form of unpacking. Compare:

def get_values():
return 5, 7, 2

x, y, z = get_values()

This is like "x = 5; y = 7; z = 2", because it unpacks the function's
return value into those three targets.

What you have is exactly the same, except that it has only one target.
So it's expecting plt.plot() to return an iterable with exactly one
thing in it, and it'll unpack it and put that thing into line:

def get_packaged_value():
return [42]

x, = get_packaged_value()

This is equivalent to "x = 42". I don't know matplotlib, so I don't
know what it's returning or why, but as long as it's iterable and
yields exactly one thing, this will work.

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


Re: meaning of: line, =

2015-02-04 Thread leo kirotawa
You'll find some explanation here:
http://stackoverflow.com/questions/1708292/meaning-of-using-commas-and-underscores-with-python-assignment-operator

On Wed, Feb 4, 2015 at 12:08 PM, ast  wrote:
> hello
>
> I dont understand why there is a comma just after line in the following
> command:
>
> line, = plt.plot(x, np.sin(x), '--', linewidth=2)
>
>
> I never saw that before
>
> Found here:
> http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
>
> thanks
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

--
Leônidas S. Barbosa (Kirotawa)
blog: corecode.wordpress.com
-- 
https://mail.python.org/mailman/listinfo/python-list


meaning of: line, =

2015-02-04 Thread ast

hello

I dont understand why there is a comma just after line in the following 
command:


line, = plt.plot(x, np.sin(x), '--', linewidth=2)


I never saw that before

Found here:
http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html

thanks
--
https://mail.python.org/mailman/listinfo/python-list


Re: re.findall help

2015-02-04 Thread Jugurtha Hadjar

On 02/04/2015 03:52 AM, w3t...@gmail.com wrote:

I am trying to extract the following from a data stream using find
all what would be the best way to capture the ip address only from
the following text " ip=192.168.1.36 port=4992 " I also want to make
sure the program can handle the ip that is as high as
255.255.255.255

Thanks for any help you can provide



Hello,

It depends on whether you trust the data (if it's yours and you *know*
they're IP addresses) and just want to automate, or not..


pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')


Tested on:


test = "ip=192.168.1.36 port=4992 ip=255.255.255.255 port=80"


Gives:

['192.168.1.36', '255.255.255.255']


Add "ip=" in order to avoid confusion (data may have by chance something
that looks like an IP address, but the "ip=" bit acts as a discriminant.


pattern = re.compile(r'ip=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')


Testing for the string test:

test = "ip=192.168.1.36 port=4992fdjsqklmfqsjdkip=192.168.541.36
port=222 2.2.2.2random"


Gives:

['ip=192.168.1.36', 'ip=192.168.541.36']

It ignores the 2.2.2.2 because it doesn't have "ip=" in front of it, and
was just lucky to have an IP address structure.

You can then split "ip=" out of each item to have the IP address.


--
~Jugurtha Hadjar,
--
https://mail.python.org/mailman/listinfo/python-list


basic generator question

2015-02-04 Thread Neal Becker
I have an object that expects to call a callable to get a value:

class obj:
  def __init__ (self, gen):
self.gen = gen
  def __call__ (self):
return self.gen()

Now I want gen to be a callable that repeats N times.  I'm thinking, this
sounds perfect for yield

class rpt:
  def __init__ (self, value, rpt):
self.value = value; self.rpt = rpt
  def __call__ (self):
for i in range (self.rpt):
  yield self.value

so I would do:

my_rpt_obj = obj (rpt ('hello', 5))

to repeat 'hello' 5 times (for example).

But this doesn't work.  when obj calls self.gen(), that returns a generator, not
the next value.

How can I make this work?  I can't change the interface of the existing class 
obj, which expects a callable to get the next value.



-- 
-- Those who don't understand recursion are doomed to repeat it

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


PSF Python Brochure "sold out" - help us kick start the second print run !

2015-02-04 Thread M.-A. Lemburg
[Please help spread the word by forwarding to other relevant mailing lists,
 user groups, etc. world-wide; thanks :-)]




*** PSF Python Brochure "sold out" ***

Please help us kick start the second print run !

   http://brochure.getpython.info/


You can also read this posting online at:
http://pyfound.blogspot.de/2015/02/psf-python-brochure-sold-out-help-us.html


First print run distributed to the community

We are happy to announce that we have successfully distributed the
first 5,000 copies of the PSF Python Brochure to Python conferences
and user groups around the world:

 PSF Python Brochure Vol. 1
 http://brochure.getpython.info/brochure-vol1.pdf

Even without doing any major announcement of the possibility to order
the brochure for conferences and user groups, we easily received
enough requests to have the first print run completely distributed in
just a few months.

Brochures were sent to PyCon US 2014 in Montreal, EuroPython 2014,
PyCons and open source conferences in India, UK, South Africa,
Australia, New Zealand, France, Belgium and to many professional users
around the world.



Promoting Python to new audiences

The feedback we received was positive all around.

Conference attendees were really happy to be able to easily show and
prove how Python changes the world, to make the point that learning
and using Python is a good investment.

The brochure helps them in promoting Python in their local and
professional communities, especially to the many non-technical people
we cannot easily reach with our python.org web site.

We would like to thank all our sponsors and contributors for their
hard work to achieve this impressing result.

Learn more about the project
http://brochure.getpython.info/learn-more



Please help us kick start the second print run !

In order to continue with the distribution of the remaining 5,000
copies of the Vol. 1 edition, we are now looking for two additional
half page ad sponsors to help finance the print run and distribution
costs.

We have reserved the notes area on the inner back cover page of the
brochure for these extra ads.

If you would like to show your support for Python and its community
and reach out to thousands of people interested in Python, now is the
time to sign up as ad sponsor!

Sign up as ad sponsor
http://brochure.getpython.info/



Pre-order the PSF Python Brochure

We provide two options for pre-ordering the brochure from the second
print run which will be available early in April 2015:

 * free Community Orders for conference and user groups

 * paid Company Orders for companies and organizations

The costs for the community orders are sponsored through sponsor ads,
the PSF and the company orders.

Place your pre-order
http://brochure.getpython.info/



More information

More information on the brochure, the idea and people behind it, media
data and ordering links are available on our project page:

PSF Python Brochure Project Website
http://brochure.getpython.info/

Thank you for your help,
-- 
Marc-Andre Lemburg
Director
Python Software Foundation
http://www.python.org/psf/



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


Re: Cairo module

2015-02-04 Thread Michiel Overtoom

Hi Poul,

I recently used cairo in a python project 
(https://github.com/luismqueral/jumpcityrecords). To see the cairo drawing 
directly on the screen I wrote a minimal Gtk application. It's in the 'src' 
directory and is called 'randomdraw.py'. Maybe it is of some help to you.

Greetings,

-- 
"You can't actually make computers run faster, you can only make them do less." 
- RiderOfGiraffes

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