Re: Printing a text over an image
On Wednesday, November 7, 2012 5:52:36 PM UTC+1, Martha Morrigan wrote:
> Hi guys,
>
>
>
> Using python, wxpython and sqlite in a windows system, Im trying to
>
> print some certificates/diplomas/cards with a image at background with
>
> the name of person/text over it.
>
>
>
> I know the basic steps to print the text using win32print from Pywin32
>
> but...:
>
>
>
> 1) I dont know how to add an image and set it to background.
>
>
>
>while .
>
>
>
> .
>
>
>
> # Query sqlite rows and collumn name and set the self.text for
>
> each certificate
>
>
>
> .
>
>
>
> # Now send to printer
>
>
>
> DC = win32ui.CreateDC()
>
> DC.CreatePrinterDC(win32print.GetDefaultPrinter())
>
>
>
> DC.SetMapMode(win32con.MM_TWIPS)
>
>
>
> DC.StartDoc("Certificates Job")
>
>
>
> DC.StartPage()
>
>
>
> ux = 1000
>
> uy = -1000
>
> lx = 5500
>
> ly = -55000
>
>
>
> DC.DrawText(self.text, (ux, uy, lx, ly),win32con.DT_LEFT)
>
>
>
> DC.EndPage()
>
> DC.EndDoc()
>
>
>
> This printer-code is inside a while loop calling each people name from
>
> a sqlite database per check condition.
>
>
>
>
>
> 2) All the names of database was printed at same page... how i command
>
> the printer to spit out 1 page per name from the database?
>
>
>
>
>
> 3) Any more simple approach or module to deals with printers (paper
>
> and/or pdf) will be welcome.
>
>
>
> Thanks in advance,
>
>
>
> Martha
Hi Martha,
Since you are on windows, why don't you use MS/Word directly from Python. It
has all the abstractions you need (documents, pages, tables, figures, printing
etc.). Working with MS/Word through the win32 bindings is really simple.
I have done this a while ago for some automatic report generation. The basic
routine is to start recording your actions with the MS/Word macro recorder, do
the things you want to do, stop recording, look at the VB code and guess the
equivalent Python code. This is not as bad as it sounds. It normally is really
straightforward.
I am on Linux at the moment, so I cannot present any code examples. Feel free
to try and post some example code if you get stuck.
Marco
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 110, Issue 106
- Original Message - > Hi, > I have a question about Django. I easy_installed Django1.4 and > psycopg2, and python manage.py syncdb. And gave me a error; No > module named psycopg2.extensions. posgre9.1 is installed. > It works fine on my MAC but not my Windows. Does anyone know about > this issue > Hope to resolve this issue soon. > Jun > -- > http://mail.python.org/mailman/listinfo/python-list Hi, Check that the psychopg2 version is the same on your MAC and Windows. Otherwise you better ask this question on the django mailing list. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python garbage collector/memory manager behaving strangely
Am 17.09.2012 04:28 schrieb Jadhav, Alok:
Thanks Dave for clean explanation. I clearly understand what is going on
now. I still need some suggestions from you on this.
There are 2 reasons why I was using self.rawfile.read().split('|\n')
instead of self.rawfile.readlines()
- As you have seen, the line separator is not '\n' but its '|\n'.
Sometimes the data itself has '\n' characters in the middle of the line
and only way to find true end of the line is that previous character
should be a bar '|'. I was not able specify end of line using
readlines() function, but I could do it using split() function.
(One hack would be to readlines and combine them until I find '|\n'. is
there a cleaner way to do this?)
- Reading whole file at once and processing line by line was must
faster. Though speed is not of very important issue here but I think the
tie it took to parse complete file was reduced to one third of original
time.
With
def itersep(f, sep='\0', buffering=1024, keepsep=True):
if keepsep:
keepsep=sep
else: keepsep=''
data = f.read(buffering)
next_line = data # empty? -> end.
while next_line: # -> data is empty as well.
lines = data.split(sep)
for line in lines[:-1]:
yield line+keepsep
next_line = f.read(buffering)
data = lines[-1] + next_line
# keepsep: only if we have something.
if (not keepsep) or data:
yield data
you can iterate over everything you want without needing too much
memory. Using a larger "buffering" might improve speed a little bit.
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
debugging in eclipse
Hi all! I have a stupid problem, for which I cannot find a solution... I have a python module, lets call it debugTest.py. and it contains: def test(): a=1 b=2 c=a+b c so as simple as possible. Now I would like to debug it in eclipse.. (I have pydev and all) so the question is how do I debug the test function? (by debug I mean go into it in the debugging mode and execute step by step, inspect the variables and so on.. you know, like it is so easily done in Matlab for example). I place a break point in the function, run the debugger and it stars and is terminated immediately. (of course it does not know where to go..) So how can I do this? please help! Thank you all in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
In article , [email protected] wrote: > Now I would like to debug it in eclipse.. Heh. It took me a while to realize that the subject line was not referring to http://en.wikipedia.org/wiki/Solar_eclipse_of_November_13,_2012 -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On 11/15/2012 07:29 AM, [email protected] wrote: > Hi all! > > I have a stupid problem, for which I cannot find a solution... > > I have a python module, lets call it debugTest.py. > > and it contains: > def test(): > a=1 > b=2 > c=a+b > c > > so as simple as possible. > > Now I would like to debug it in eclipse.. (I have pydev and all) > so the question is how do I debug the test function? (by debug I mean go into > it in the debugging mode and execute step by step, inspect the variables and > so on.. you know, like it is so easily done in Matlab for example). > I don't know Eclipse, but you probably have to have some top-level code in your program. As it stands, it's just an importable module, doing nothing useful when you run it. Add a call to test() to the end of the file, and it might do better. I'd also add a print statement, just to assure yourself that it's running. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, 15 November 2012 12:29:04 UTC, [email protected] wrote: > Hi all! > > > > I have a stupid problem, for which I cannot find a solution... > > > > I have a python module, lets call it debugTest.py. > > > > and it contains: > > def test(): > > a=1 > > b=2 > > c=a+b > > c > > > > so as simple as possible. > > > > Now I would like to debug it in eclipse.. (I have pydev and all) > > so the question is how do I debug the test function? (by debug I mean go into > it in the debugging mode and execute step by step, inspect the variables and > so on.. you know, like it is so easily done in Matlab for example). > > > > I place a break point in the function, run the debugger and it stars and is > terminated immediately. (of course it does not know where to go..) > > > > So how can I do this? please help! > > > > Thank you all in advance! I assume you have at the end of the debugTest.py file something like this: if __name__ == '__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, November 15, 2012 1:49:22 PM UTC+1, Roy Smith wrote: > Heh. It took me a while to realize that the subject line was not > referring to > http://en.wikipedia.org/wiki/Solar_eclipse_of_November_13,_2012 :)) -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, November 15, 2012 2:42:09 PM UTC+1, Dave Angel wrote: > Add a call to test() to the end of the file, and it might do better. > > I'd also add a print statement, just to assure yourself that it's running. > > thanks, that is it, (stupid me) now if I have many functions in the model I will simply ad a call to the specific function at the end and that is it... working on the project too long, all the simple and smart ideas are long gone ;) thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, November 15, 2012 2:44:22 PM UTC+1, Martin P. Hellwig wrote: > I assume you have at the end of the debugTest.py file something like this: > if __name__ == '__main__': >test() no i did not have it... is main really necessary? -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
In article , Dave Angel wrote: > I'd also add a print statement, just to assure yourself that it's running. My trick to make sure something is running is to add "assert 0". To be fair, I usually start by adding a print statement, as Dave suggests. If I see the output, I know it ran. But if I don't see the output, there's two possibilities. Either it didn't run, or it ran but something snarfed the output and hid it from my eyes. That's common in test frameworks. It's also common in background processes where stdout goes who-knows-where, and it's anybody's guess how the logging config might be borked. On the other hand, an "assert 0" is pretty much guaranteed to produce some visible evidence that it ran. About the only thing that would stop it is if somebody had wrapped the code in a try block which caught AssertionError (or Exception). -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
Am 15.11.2012 13:29, schrieb [email protected]: I have a python module, lets call it debugTest.py. and it contains: def test(): a=1 b=2 c=a+b c so as simple as possible. Should that be "return c" instead of "c" on a line? Now I would like to debug it in eclipse.. (I have pydev and all) so the question is how do I debug the test function? [...] I place a break point in the function, run the debugger and it stars and is terminated immediately. For a start, I would try to actually call the function. Just add "print(test())" after the function definition. Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thu, 15 Nov 2012 05:46:49 -0800, chip9munk wrote: > On Thursday, November 15, 2012 2:44:22 PM UTC+1, Martin P. Hellwig > wrote: >> I assume you have at the end of the debugTest.py file something like >> this: >> if __name__ == '__main__': >>test() > > no i did not have it... > > is main really necessary? doing it that way means that it will only call test when executed directly & not when imported as a module -- I used to be an agnostic, but now I'm not so sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, November 15, 2012 2:43:26 PM UTC+1, Ulrich Eckhardt wrote: > Should that be "return c" instead of "c" on a line? oh it is just a silly example function, the functionality is not important. It does not have to return anything... > For a start, I would try to actually call the function. Just add > "print(test())" after the function definition. yes I call the function now, that was the thing... -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thursday, November 15, 2012 3:21:52 PM UTC+1, Alister wrote: > doing it that way means that it will only call test when executed > directly & not when imported as a module I see, thanks! -- http://mail.python.org/mailman/listinfo/python-list
error importing smtplib
Hello,
I created some bindings to a 3rd party library.
I have found that when I run Python and import smtplib it works fine.
If I first log into the 3rd party application using my bindings however I
get a bunch of errors.
What do you think this 3rd party login could be doing that would affect the
ability to import smtp lib.
Any suggestions for debugging this further. I am lost.
This works...
import smtplib
FOO_login()
This doesn't...
FOO_login()
import smtplib
Errors.
>>> import smtplib
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha512
--
http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
In article , Roy Smith wrote: >In article , > Dave Angel wrote: >> >> I'd also add a print statement, just to assure yourself that it's running. > >My trick to make sure something is running is to add "assert 0". ``1/0`` is shorter. ;-) -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" -- www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect file is locked - windows
In article ,
Tim Golden wrote:
>On 14/11/2012 00:33, Ali Akhavan wrote:
>>
>> I am trying to open a file in 'w' mode open('file', 'wb'). open()
>> will throw with IOError with errno 13 if the file is locked by
>> another application or if user does not have permission to open/write
>> to the file.
>>
>> How can I distinguish these two cases ? Namely, if some application
>> has the file open or not.
>
>Can I ask what you expect to do differently in each of those cases? In
>other words, if you can't access the file, you can't access it. (Not to
>dismiss your question; I just wonder how you're going to handle the
>different cases)
Real-life use case for user-requested operation: if no permission, skip
the file "permanently" (until it changes, at least); if locked, place in
retry loop.
And in response to your other post, you absolutely want to use
CreateFileW()... ;-)
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/
"LL YR VWL R BLNG T S" -- www.nancybuttons.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Functions
On 2012-11-15 16:04, Kevin Gullikson wrote:
Hi all,
I am trying to make a dictionary of functions, where each entry in the
dictionary is the same function with a few of the parameters set to
specific parameters. My actual use is pretty complicated, but I managed
to boil down the issue I am having to the following example:
In [1]: def test_fcn(a, x):
...: return a*x
...:
In [2]: fcn_dict = {}
In [3]: for i in [1,2,3]:
...: fcn_dict[i] = lambda x: test_fcn(i, x)
...:
In [4]: fcn_dict
Out[4]:
{1: at 0x102b42c08>,
2: at 0x102b42b18>,
3: at 0x102b42c80>}
In [5]: fcn_dict[1](5)
Out[5]: 15
In [6]: fcn_dict[2](5)
Out[6]: 15
In [7]: fcn_dict[3](5)
Out[7]: 15
As you can see, all of the functions are returning the value that I want
for fcn_dict[3]. If I make separate functions for each case instead of a
dictionary it works, but I would really prefer to use dictionaries if
possible. Is there a way to make this work?
It's looking up 'i' at the time that the function is called, which is
after the 'for' loop has finished and 'i' has been left as 3.
What you need to do is capture the current value of 'i'. The usual way
is with a default argument:
for i in [1,2,3]:
fcn_dict[i] = lambda x, i=i: test_fcn(i, x)
--
http://mail.python.org/mailman/listinfo/python-list
Re: error importing smtplib
On 11/15/2012 9:38 AM, Eric Frederich wrote:
Hello,
I created some bindings to a 3rd party library.
I have found that when I run Python and import smtplib it works fine.
If I first log into the 3rd party application using my bindings however
I get a bunch of errors.
What do you think this 3rd party login could be doing that would affect
the ability to import smtp lib.
I don't know what 'login' actually means,...
This works...
import smtplib
FOO_login()
This doesn't...
FOO_login()
import smtplib
but my first guess is that FOO_login alters the module search path so
that at least one of smtplib, hashlib, or the _xxx modules imported by
hashlib is being imported from a different place. To check that
import sys
before = sys.path
FOO_login()
print sys.path==before
Similar code can check anything else accessible through sys.
Errors.
>>> import smtplib
ERROR:root:code for hash sha224 was not found.
I am puzzled by this line before the traceback. I cannot find 'ERROR' in
either smtplib or hashlib.
Traceback (most recent call last):
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in
globals()[__func_name] = __get_hash(__func_name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha224
[snip similar messages]
It is also unusual to get multiple tracebacks. *Exactly* how are you
running python and is 2.7 what you intend to run?
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Thu, 15 Nov 2012 07:56:17 -0800, Aahz wrote: > In article , Roy Smith > wrote: >>In article , >> Dave Angel wrote: >>> >>> I'd also add a print statement, just to assure yourself that it's >>> running. >> >>My trick to make sure something is running is to add "assert 0". > > ``1/0`` is shorter. ;-) It is also guaranteed to run, unlike assert. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Functions
On Thu, Nov 15, 2012 at 8:04 AM, Kevin Gullikson
wrote:
> Hi all,
>
> I am trying to make a dictionary of functions, where each entry in the
> dictionary is the same function with a few of the parameters set to specific
> parameters. My actual use is pretty complicated, but I managed to boil down
> the issue I am having to the following example:
>
> In [1]: def test_fcn(a, x):
>...: return a*x
>...:
>
> In [2]: fcn_dict = {}
>
> In [3]: for i in [1,2,3]:
>...: fcn_dict[i] = lambda x: test_fcn(i, x)
>...:
In this case, I would recommend using functools.partial instead of a lambda.
It will solve this problem (although MRAB's solution will as well), is
trivially faster (likely insignificant in any real application), and,
IMO, clearer:
for i in [1,2,3]:
fcn_dict[i] = functools.partial(test_fcn, i)
Note that this only works if you are either only specifying the first
arguments by position, or specifying arguments by keyword. There is no
way to specify the second argument by position; you'd have to pass it
as a keyword argument.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Getting "empty" attachment with smtplib
I can already say that "smtplib" is not to blame. It is (mostly) unconcerned with the internal structure of the message -- and by itself will not empty attachments. On the advice of a co-worker, I tried using web2py's gluon.tools.Mail. It was easier to accomplish the attachment, and Thunderbird opened the .pdf just fine. Thanks for the suggestions. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: error importing smtplib
Thanks for the idea.
sys.path was the same before and after the login
What else should I be checking?
On Thu, Nov 15, 2012 at 11:57 AM, Terry Reedy wrote:
> On 11/15/2012 9:38 AM, Eric Frederich wrote:
>
>> Hello,
>>
>> I created some bindings to a 3rd party library.
>> I have found that when I run Python and import smtplib it works fine.
>> If I first log into the 3rd party application using my bindings however
>> I get a bunch of errors.
>>
>> What do you think this 3rd party login could be doing that would affect
>> the ability to import smtp lib.
>>
>
> I don't know what 'login' actually means,...
>
>
> This works...
>>
>> import smtplib
>> FOO_login()
>>
>> This doesn't...
>>
>> FOO_login()
>> import smtplib
>>
>
> but my first guess is that FOO_login alters the module search path so that
> at least one of smtplib, hashlib, or the _xxx modules imported by hashlib
> is being imported from a different place. To check that
>
> import sys
> before = sys.path
> FOO_login()
> print sys.path==before
>
> Similar code can check anything else accessible through sys.
>
>
> Errors.
>>
>> >>> import smtplib
>> ERROR:root:code for hash sha224 was not found.
>>
>
> I am puzzled by this line before the traceback. I cannot find 'ERROR' in
> either smtplib or hashlib.
>
>
> Traceback (most recent call last):
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 139, in
>>
>> globals()[__func_name] = __get_hash(__func_name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 103, in
>> __get_openssl_constructor
>> return __get_builtin_constructor(**name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 91, in
>> __get_builtin_constructor
>> raise ValueError('unsupported hash type %s' % name)
>> ValueError: unsupported hash type sha224
>>
> [snip similar messages]
>
> It is also unusual to get multiple tracebacks. *Exactly* how are you
> running python and is 2.7 what you intend to run?
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: error importing smtplib
Sorry, only saw your first response, didn't see the others.
I compiled Python 2.7.2 myself with --enable-shared
To create standalone applications that interact with this 3rd party program
your main C file instead of having a "main" function has a FOO_user_main
function.
When you link your program you link against a provided foo_main.o file.
My python executable (called FOO_user_main) was created from python.c but
with main replaced with FOO_user_main no other differences.
I have been using this type of installation for a couple of years and
everything works fine.
I only get these errors/warnings on one environment out of 10 or so
development and qa machines.
Any help trying to figure out what is different before and after the login
would be appreciated.
Is there some place in /proc I could look to see what happened?
Thanks,
~Eric
On Thu, Nov 15, 2012 at 11:57 AM, Terry Reedy wrote:
> On 11/15/2012 9:38 AM, Eric Frederich wrote:
>
>> Hello,
>>
>> I created some bindings to a 3rd party library.
>> I have found that when I run Python and import smtplib it works fine.
>> If I first log into the 3rd party application using my bindings however
>> I get a bunch of errors.
>>
>> What do you think this 3rd party login could be doing that would affect
>> the ability to import smtp lib.
>>
>
> I don't know what 'login' actually means,...
>
>
> This works...
>>
>> import smtplib
>> FOO_login()
>>
>> This doesn't...
>>
>> FOO_login()
>> import smtplib
>>
>
> but my first guess is that FOO_login alters the module search path so that
> at least one of smtplib, hashlib, or the _xxx modules imported by hashlib
> is being imported from a different place. To check that
>
> import sys
> before = sys.path
> FOO_login()
> print sys.path==before
>
> Similar code can check anything else accessible through sys.
>
>
> Errors.
>>
>> >>> import smtplib
>> ERROR:root:code for hash sha224 was not found.
>>
>
> I am puzzled by this line before the traceback. I cannot find 'ERROR' in
> either smtplib or hashlib.
>
>
> Traceback (most recent call last):
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 139, in
>>
>> globals()[__func_name] = __get_hash(__func_name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 103, in
>> __get_openssl_constructor
>> return __get_builtin_constructor(**name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 91, in
>> __get_builtin_constructor
>> raise ValueError('unsupported hash type %s' % name)
>> ValueError: unsupported hash type sha224
>>
> [snip similar messages]
>
> It is also unusual to get multiple tracebacks. *Exactly* how are you
> running python and is 2.7 what you intend to run?
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Lazy Attribute
A lazy attribute is an attribute that is calculated on demand and only once. The post below shows how you can use lazy attribute in your Python class: http://mindref.blogspot.com/2012/11/python-lazy-attribute.html Comments or suggestions are welcome. Thanks. Andriy Kornatskyy -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Functions
On 15 November 2012 17:13, Chris Kaynor wrote:
> On Thu, Nov 15, 2012 at 8:04 AM, Kevin Gullikson
> wrote:
> > Hi all,
> >
> > I am trying to make a dictionary of functions, where each entry in the
> > dictionary is the same function with a few of the parameters set to
> specific
> > parameters. My actual use is pretty complicated, but I managed to boil
> down
> > the issue I am having to the following example:
> >
> > In [1]: def test_fcn(a, x):
> >...: return a*x
> >...:
> >
> > In [2]: fcn_dict = {}
> >
> > In [3]: for i in [1,2,3]:
> >...: fcn_dict[i] = lambda x: test_fcn(i, x)
> >...:
>
> In this case, I would recommend using functools.partial instead of a
> lambda.
> It will solve this problem (although MRAB's solution will as well), is
> trivially faster (likely insignificant in any real application), and,
> IMO, clearer:
>
> for i in [1,2,3]:
> fcn_dict[i] = functools.partial(test_fcn, i)
>
> Note that this only works if you are either only specifying the first
> arguments by position, or specifying arguments by keyword. There is no
> way to specify the second argument by position; you'd have to pass it
> as a keyword argument.
>
Another way to do this is by making a factory function:
>>> def factor_multiplier(factor):
... def factor_multiply(target):
... return factor * target
... return factor_multiply
...
Testing it:
>>> trippler = factor_multiplier(3)
>>> trippler
.factor_multiply at 0x7ffeb5d6db90>
>>> trippler(10)
30
>>> doubler = factor_multiplier(2)
>>> doubler(15)
30
>>> doubler(trippler(1))
6
>>>
Solving your problem:
>>> function_dict = {}
>>> for i in range(100):
... function_dict[i] = factor_multiplier(i)
...
>>>
>>> function_dict[42](2)
84
>>> function_dict[20](3)
60
>>>
This is definitely longer that Chris' approach, but it's more powerful
overall. It's worth learning and using both.
In a sense, you were close, but you were just not catching the variable:
>>> function_dict.clear()
>>> for i in range(100):
... function_dict[i] = (lambda i: lambda x: x*i)(i)
...
>>> function_dict[19](2)
38
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python questions help
On 15 November 2012 01:47, su29090 <[email protected]> wrote: > I brought a python book and i'm a beginner and I read and tried to do the > questions and I still get it wrong. > > How to create a program that reads an uspecified number of integers, that > determines how many positive and negative values have been read, and > computes the total and average of the input values(not counting zeroes). My > program have to end with the input 0 and have to display the average as a > floating-point number. > Think about the requirements. For example, you need here: * Some sort of loop to take in an unlimited number of integers * Some way to take in integers * Some way of stopping when a 0 is entered * Some way of finding the total and averages * Some way of putting it all together If you can solve some of these sub-tasks and just need help with others, tell us what you've done and we'll help you work out the rest. Use nested loops that display the following patterns in separate programs: > > 1 > 12 > 123 > 1234 > 12345 > 123456 > What are the patterns here? 1st: 1 -> 2 -> 3 -> 4 -> ... 2nd: 1 -> 12 -> 123 -> 1234 -> ... How would you do these? How would you combine them? > 123456 > 12345 > 1234 > 123 > 12 > 1 > How would you change the above to do this instead? > 1 > 21 >321 > 4321 > 54321 > 654321 > How would you change it to do this? > Write a program that computes the following summation: > > 1/ 1+square root of 2 + 1/ 1+square root of 2 + square root of 3 + 1/ > 1+square root of 3 + square root of 4...+ 1/ 1+square root of 624 + square > root of 625 > You've probably written this wrong. You've got: (1/ 1) + (square root of 2) + (1/ 1) + (square root of 2) + (square root of 3) + (1/ 1) + (square root of 3) + (square root of 4)... + (1/ 1) + (square root of 624) + (square root of 625) Which you can write as: 1 + root(2) + 1 + root(2) + root(3) + 1 + root(3) + root(4) + ... + 1 + root(624) + root(625) As (1/1) is 1. You probably need brackets somewhere. I've never seen any equation like this, so I can't guess at what you really wanted. Do you know how to find the square root? Just search "square root python" if you do not. Then put it in a loop. > How to a program to draw a chessboard using range? > I imagine you want to use "loops", where a range is what you loop over. O X O X O X O X X O X O X O X O O X O X O X O X X O X O X O X O O X O X O X O X X O X O X O X O O X O X O X O X X O X O X O X O It's 8 by 8, so you want to loop 8 times for one dimension and 8 times for the other. How would you use range to do this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On 11/14/2012 04:07 PM, Steven D'Aprano wrote: > On Wed, 14 Nov 2012 10:20:13 -0800, rurpy wrote: I'll skip the issues already addressed by Joshua Landau. >[...] > I don't understand why you suggest counting setup time for the > alternatives to Google Groups, but *don't* consider setup time for Google > Groups. You had to create a Google Account didn't you? You've either put > in your mobile phone number -- and screw those who don't have one -- or > you get badgered every time you sign in. You do sign in don't you? Yes I sign in. And I've never entered my mobile phone number and no I don't get badgered every time (I've not been asked when I logged in several times today and I just tried again to confirm.) I have been asked in the past and just ignore it -- click Save (or whatever the button is) with a blank text box. As was pointed out, a large number of people already have Google accounts. And creating an account at Google is not comparable to researching news readers, downloading and installing software, setting up an account, etc for someone who's never even heard of usenet before. Subscribing to email is easier but it has its own problems (all those email you don't care about, the time delay (I've had to wait over 24 hours for a response for some email lists), what to do when you're traveling, reading some groups via email but others by GG. I've also had problems trying to post through Gmane and then there were Gmane's accessibly problems a few months ago, fixed now but for how long? The OP had already found her way to GG and managed to post. So the incremental cost for her to *continue* using GG is very low. That's in comparision to *changing* to a new posting method. I'm not saying the Google is always easier than an alternative but for a significant number of people it is. But most importantly it is *their* place to say what is easier for them, not yours or mine. [...] > Even if you are right that Google Groups is easier for some users, in my > opinion it is easy in the same way as the Dark Side of the Force. > Quicker, faster, more seductive, but ultimately destructive. Well, that's the best example of FUD I've seen in this thread so far. Congratulations. ;-) >> As for "best", that is clearly a matter of opinion. The very fact that >> someone would killfile an entire class of poster based on a some others' >> posts reeks of intolerance and group-think. > > Intolerance? Yes. But group-think? You believe that people are merely > copying the group's prejudice against Google Groups. Please don't tell me what I believe, especially when you get it wrong. > I don't think they > are. I think that the dislike against GG is group consensus based on the > evidence of our own eyes, not a mere prejudice. The use of Google Groups > is, as far as I can tell, the single most effective predictor of badly > written, badly thought out, badly formatted posts, and a common source of > spam. Again you repeat Chris Angelo's mistake (if it's a mistake). "group's prejudice"? You've presented no evidence that "the group" as a whole or in large part (including many people who seldom if ever post) share your view. Same with "consensus". A consensus of whom? Are you saying there is a consensus among those who dislike GG posts that they dislike GG posts? You say the dislike is "not a mere prejudice" and yet I can't help but wonder where the hard evidence is. I've not seen it posted though I could have easily missed it. All the news/email tools I use make it a little work to see where a post came from -- usually they'll be a button somewhere or a menu item to show the headers and one will scan those for the source. While easy enough it is still (at least for me) much easier to simply skip a post based on the subject/poster or a quick peak at the contents. So I've never had any inclination to look and have no idea how many crap posts come from GG. Yet you claim that a large percentage of this group has made the effort to do that. (Or maybe there is an easier way to check?) However I can easily imagine how some could think they are checking... "Oh man, what a crap post! Let's check the headers. Yup, just as I thought, Google Groups." But of course, our genius doesn't keep any records and the cases where he is wrong don't make as much impression on his memory. Further, he doesn't bother to check the headers on the non-crap posts. Even a junior-high science student could see the problems with this methodology. And how many people actually do even that? Some may find it an offensive suggestion but there is such a thing as group psychology and there are people who follow leaders. (I suspect those people are all of "us" at least some of the time.) Further people tend to be convinced even more easily when they think "everybody knows it". So when a few of the more prolific and respected posters here start talking about "the consensu
Re: error importing smtplib
On 11/15/2012 1:48 PM, Eric Frederich wrote: Thanks for the idea. sys.path was the same before and after the login Too bad. That seems to be a typical cause of import failure. What else should I be checking? No idea. You are working beyond my knowledge. But I might either look at the foo-login code carefully, or disable (comment out) parts of it to see what makes the import fail. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On 15/11/2012 21:29, [email protected] wrote: All I'll say is that when I read something on gmane via Thunderbird on Windows Vista on any of the 25 Python mailing lists that I subscribe to, I don't want to read the double spaced crap that comes from G$. I hence perceive a problem. 1) G$ are too interested in making huge profits and so have no interest in people who have to read the garbage that originates from them. 2) People who are too bone idle to get hold of any other mechanism that doesn't put the double spaced garbage in. Any and all answers to this dilemma are welcome. -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lazy Attribute
On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy wrote: > > A lazy attribute is an attribute that is calculated on demand and only once. > > The post below shows how you can use lazy attribute in your Python class: > > http://mindref.blogspot.com/2012/11/python-lazy-attribute.html > > Comments or suggestions are welcome. The name "attribute" is not very descriptive. Why not "lazy_attribute" instead? I note that trying to access the descriptor on the class object results in an error: >>> from descriptors import attribute >>> class Foo: ... @attribute ... def forty_two(self): ... return 6 * 9 ... >>> Foo().forty_two 54 >>> Foo.forty_two Traceback (most recent call last): File "", line 1, in File ".\descriptors.py", line 33, in __get__ setattr(obj, f.__name__, val) AttributeError: 'NoneType' object has no attribute 'forty_two' If accessing the descriptor on the class object has no special meaning, then the custom is to return the descriptor object itself, as properties do. >>> class Foo: ... @property ... def forty_two(self): ... return 6 * 9 ... >>> Foo().forty_two 54 >>> Foo.forty_two -- http://mail.python.org/mailman/listinfo/python-list
Re: Lazy Attribute
On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy
wrote:
>
> A lazy attribute is an attribute that is calculated on demand and only once.
>
> The post below shows how you can use lazy attribute in your Python class:
>
> http://mindref.blogspot.com/2012/11/python-lazy-attribute.html
>
> Comments or suggestions are welcome.
I should add that I like the approach you're taking here. Usually
when I want a lazy property I just make an ordinary property of a
memoized function call:
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwset = frozenset(kwargs.items())
try:
return cache[args, kwset]
except KeyError:
result = cache[args, kwset] = func(*args, **kwargs)
return result
return wrapper
class Foo:
def __init__(self):
self.times_called = 0
@property
@memoize # Alternatively, use functools.lru_cache
def forty_two(self):
self.times_called += 1
return 6 * 9
>>> foo = Foo()
>>> foo.times_called
0
>>> foo.forty_two
54
>>> foo.times_called
1
>>> foo.forty_two
54
>>> foo.times_called
1
Although you don't go into it in the blog entry, what I like about
your approach of replacing the descriptor with an attribute is that,
in addition to being faster, it makes it easy to force the object to
lazily reevaluate the attribute, just by deleting it. Using the
Person example from your blog post:
>>> p = Person('John', 'Smith')
>>> p.display_name
'John Smith'
>>> p.display_name
'John Smith'
>>> p.calls_count
1
>>> p.first_name = 'Eliza'
>>> del p.display_name
>>> p.display_name
'Eliza Smith'
>>> p.calls_count
2
Although in general it's probably better to use some form of reactive
programming for that.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Subprocess puzzle and two questions
On Wed, 14 Nov 2012 20:49:19 -0500, Roy Smith wrote: >> I'm slightly surprised that there's no way with the Python stdlib to >> point a DNS query at a specific server > > Me too, including the "only slightly" part. The normal high-level C > resolver routines (getaddrinfo/getnameinfo, or even the old > gethostbyname series), don't expose any way to do that. That's because the high-level routines aren't tied to DNS. gethostbyname() and getaddrinfo() use the NSS (name-service switch) mechanism, which is configured via /etc/nsswitch.conf. Depending upon configuration, hostnames can be looked up via a plain text file (/etc/hosts), Berkeley DB files, DNS, NIS, NIS+, LDAP, WINS, etc. DNS is just one particular back-end, which may or may not be used on any given system. If you specifically want to perform DNS queries, you have to use a DNS-specific interface (e.g. the res_* functions described in the resolver(3) manpage), or raw sockets, rather than a high-level interface such as gethostbyname() or getaddrinfo(). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
On Saturday, November 10, 2012 10:35:12 AM UTC-5, Aahz wrote: > In article , > > Peter Otten <[email protected]> wrote: > > >Miki Tebeka wrote: > > > > > >>> Is there a simpler way to modify all arguments in a function before using > > >>> the arguments? > > >> > > >> You can use a decorator: > > >> > > >> from functools import wraps > > >> > > >> def fix_args(fn): > > >> @wraps(fn) > > >> def wrapper(*args): > > >> args = (arg.replace('_', '') for arg in args) > > >> return fn(*args) > > >> > > >> return wrapper > > >> > > >> @fix_args > > >> def foo(x, y): > > >> print(x) > > >> print(y) > > > > > >I was tempted to post that myself, but he said /simpler/ ;) > > > > From my POV, that *is* simpler. When you change the parameters for foo, > > you don't need to change the arg pre-processing. Also allows code reuse, > > probably any program needing this kind of processing once will need it > > again. > > -- > > Aahz ([email protected]) <*> http://www.pythoncraft.com/ > > > > "Normal is what cuts off your sixth finger and your tail..." --Siobhan Using a decorator works when named arguments are not used. When named arguments are used, unexpected keyword error is reported. Is there a simple fix? Thanks to all, Bruce Code: - from functools import wraps def fix_args(fn): @wraps(fn) def wrapper(*args): args = (arg.replace('_', '') for arg in args) return fn(*args) return wrapper @fix_args def foo(a1="", a2="", b1="", b2=""): print(a1) print(a2) print(b1) print(b2) foo ('a1a1_x', 'a2a2_x', 'b1b1_x', 'b2b2_x') foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_x') Results: a1a1x a2a2x b1b1x b2b2x Traceback (most recent call last): File "C:\WORK\masterDB_Update\argtest.py", line 19, in foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_x') TypeError: wrapper() got an unexpected keyword argument 'a1' -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
[email protected] wrote: Using a decorator works when named arguments are not used. When named arguments are used, unexpected keyword error is reported. Is there a simple fix? Extend def wrapper(*args) to handle *kwargs as well Emile Code: - from functools import wraps def fix_args(fn): @wraps(fn) def wrapper(*args): args = (arg.replace('_', '') for arg in args) return fn(*args) return wrapper @fix_args def foo(a1="", a2="", b1="", b2=""): print(a1) print(a2) print(b1) print(b2) foo ('a1a1_x', 'a2a2_x', 'b1b1_x', 'b2b2_x') foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_x') Results: a1a1x a2a2x b1b1x b2b2x Traceback (most recent call last): File "C:\WORK\masterDB_Update\argtest.py", line 19, in foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_x') TypeError: wrapper() got an unexpected keyword argument 'a1' -- http://mail.python.org/mailman/listinfo/python-list
Re: Subprocess puzzle and two questions
In article , Nobody wrote: > That's because the high-level routines aren't tied to DNS. This is true. >> gethostbyname() and getaddrinfo() use the NSS (name-service switch) > mechanism, which is configured via /etc/nsswitch.conf. Depending upon > configuration, hostnames can be looked up via a plain text file > (/etc/hosts), Berkeley DB files, DNS, NIS, NIS+, LDAP, WINS, etc. Gethostbyname() long predates NSS. For that matter, I think it even predates DNS (i.e. back to the days when /etc/hosts was the *only* way to look up a hostname). But, that's a nit. -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging in eclipse
On Nov 16, 3:05 am, Steven D'Aprano wrote: > > ``1/0`` is shorter. ;-) > > It is also guaranteed to run, unlike assert. Only if they actively pass the command line switch to turn it off, which I'd assume someone intentionally using an assertion wouldn't do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On 2012-11-15, Mark Lawrence wrote: > On 15/11/2012 21:29, [email protected] wrote: > > All I'll say is that when I read something on gmane via Thunderbird on > Windows Vista on any of the 25 Python mailing lists that I subscribe to, > I don't want to read the double spaced crap that comes from G$. Doesn't Thunderbird have a scoring, blocking, or blacklisting facility to allow you to hide/ignore those posts? I have slrn hide all postings with headers that contain a line that matches this (case-insensitve) RE: Message-ID: .*googlegroups.com > I hence perceive a problem. Indeed. > 1) G$ are too interested in making huge profits and so have no interest >in people who have to read the garbage that originates from them. While I generally find Google to be mostly non-evil[1] (at least when compared to most other behmouth companies), their attitude regarding Google Groups is notably awful. > 2) People who are too bone idle to get hold of any other mechanism that >doesn't put the double spaced garbage in. Or it could be they're too ignorant to know there's a problem. Trying to explain the problem and the available options is, IME, pointless. Even if you can drag them along to the point where they understand there's a problem and they can do something about it, as long as people read and respond to their posts, they've got no motivation to do so. > Any and all answers to this dilemma are welcome. I just gave up and now ignore posts from Google Groups. I've decided there's no point it trying to change either Google Groups itself or the people who use it. I occasionally see most/all of posts from GG when they get quoted in followups, and never have I had occasion to wish I hadn't missed a GG posting. [1] OK, so I'm am annoyed with them after my Google phone updated to Android 4.2 this afternoon and the lock-screen clock is now _physically_painful_ to look at. However, I'm convinced that's not evil -- just a complete and utter lack of visual design ability. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On Nov 16, 2:29 am, [email protected] wrote: > But of course, our genius doesn't keep any records > and the cases where he is wrong don't make as much > impression on his memory. Further, he doesn't bother > to check the headers on the non-crap posts. Even a > junior-high science student could see the problems > with this methodology. Reminds of the difference between pop and educated statistics: http://www.johndcook.com/blog/2008/10/20/nearly-everyone-is-above-average/ On the whole I agree with rurpy. One small addition: GG allows spam posts to be marked as spam. This feature costs a few seconds and can help everyone (if a few more GG users would use it) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
Emile van Sebille wrote: [email protected] wrote: Using a decorator works when named arguments are not used. When named arguments are used, unexpected keyword error is reported. Is there a simple fix? Extend def wrapper(*args) to handle *kwargs as well Emile Code: - from functools import wraps def fix_args(fn): @wraps(fn) def wrapper(*args): so this line ^ becomes def wrapper(*args, **kwargs): args = (arg.replace('_', '') for arg in args) and add a line for k, v in kwargs: kwargs[k] = v.replace('_', '') return fn(*args) and this line ^ becomes return fn(*args, **kwargs) return wrapper ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On Fri, Nov 16, 2012 at 3:10 PM, rusi wrote: > One small addition: GG allows spam posts to be marked as spam. > > This feature costs a few seconds and can help everyone (if a few more > GG users would use it) And Gmail lets you do the exact same thing, but I almost never need to do it, because the filter is already pretty good. Though every once in a while I go check the spambox and there's usually something that technically shouldn't have been called spam (but even then, I've never regretted missing it). And I'm sure you can get it with a newsreader too, though I've not looked. Spam filtering is nothing unique. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Question regarding running .py program
On Fri, Nov 16, 2012 at 5:37 PM, Chris Angelico wrote: > Spam filtering is nothing unique. > (Don't get me wrong though, that doesn't stop it from being a good thing. It's just not a reason to use GG above all else.) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Understanding '?' in regular expressions
Can someone explain the below behavior please?
>>> re1 = re.compile(r'(?:((?:1000|1010|1020))[ ]*?[\,]?[ ]*?){1,3}')
>>> re.findall(re_obj,'1000,1020,1000')
['1000']
>>> re.findall(re_obj,'1000,1020, 1000')
['1020', '1000']
However when I use "[\,]??" instead of "[\,]?" as below, I see a different
result
>>> re2 = re.compile(r'(?:((?:1000|1010|1020))[ ]*?[\,]??[ ]*?){1,3}')
>>> re.findall(re_obj,'1000,1020,1000')
['1000', '1020', '1000']
I am not able to understand what's causing the difference of behavior here, I
am assuming it's not 'greediness' if "?"
Thank you,
Kishor
--
http://mail.python.org/mailman/listinfo/python-list
RE: Lazy Attribute
Ian, Thank you for the comments. > The name "attribute" is not very descriptive. Why not "lazy_attribute" > instead? It just shorter and still descriptive. > If accessing the descriptor on the class object has no special > meaning, then the custom is to return the descriptor object itself, as > properties do. The lazy attribute, as a pattern, is designed to calculate something on demand, that being said means some `dynamic` nature must present, thus a class instance - object is a good candidate, while class itself is considered relatively `immutable`... of cause there might be extreme cases. > If accessing the descriptor on the class object has no special > meaning, then the custom is to return the descriptor object itself, as > properties do. If I would satisfy this, I will be forced to check for None 99.9% of the use cases (it is not None, being applied to an object). Thus it behaves as designed. Thanks. Andriy Kornatskyy > From: [email protected] > Date: Thu, 15 Nov 2012 15:24:40 -0700 > Subject: Re: Lazy Attribute > To: [email protected] > > On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy > wrote: > > > > A lazy attribute is an attribute that is calculated on demand and only once. > > > > The post below shows how you can use lazy attribute in your Python class: > > > > http://mindref.blogspot.com/2012/11/python-lazy-attribute.html > > > > Comments or suggestions are welcome. > > The name "attribute" is not very descriptive. Why not "lazy_attribute" > instead? > > I note that trying to access the descriptor on the class object > results in an error: > > >>> from descriptors import attribute > >>> class Foo: > ... @attribute > ... def forty_two(self): > ... return 6 * 9 > ... > >>> Foo().forty_two > 54 > >>> Foo.forty_two > Traceback (most recent call last): > File "", line 1, in > File ".\descriptors.py", line 33, in __get__ > setattr(obj, f.__name__, val) > AttributeError: 'NoneType' object has no attribute 'forty_two' > > If accessing the descriptor on the class object has no special > meaning, then the custom is to return the descriptor object itself, as > properties do. > > >>> class Foo: > ... @property > ... def forty_two(self): > ... return 6 * 9 > ... > >>> Foo().forty_two > 54 > >>> Foo.forty_two > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Lazy Attribute
Ian, Thank you for mentioning about this research, really appreciate that. Thanks. Andriy Kornatskyy > From: [email protected] > Date: Thu, 15 Nov 2012 15:46:19 -0700 > Subject: Re: Lazy Attribute > To: [email protected] > > On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy > wrote: > > > > A lazy attribute is an attribute that is calculated on demand and only once. > > > > The post below shows how you can use lazy attribute in your Python class: > > > > http://mindref.blogspot.com/2012/11/python-lazy-attribute.html > > > > Comments or suggestions are welcome. > > I should add that I like the approach you're taking here. Usually > when I want a lazy property I just make an ordinary property of a > memoized function call: > > def memoize(func): > cache = {} > @functools.wraps(func) > def wrapper(*args, **kwargs): > kwset = frozenset(kwargs.items()) > try: > return cache[args, kwset] > except KeyError: > result = cache[args, kwset] = func(*args, **kwargs) > return result > return wrapper > > class Foo: > def __init__(self): > self.times_called = 0 > > @property > @memoize # Alternatively, use functools.lru_cache > def forty_two(self): > self.times_called += 1 > return 6 * 9 > > > >>> foo = Foo() > >>> foo.times_called > 0 > >>> foo.forty_two > 54 > >>> foo.times_called > 1 > >>> foo.forty_two > 54 > >>> foo.times_called > 1 > > > Although you don't go into it in the blog entry, what I like about > your approach of replacing the descriptor with an attribute is that, > in addition to being faster, it makes it easy to force the object to > lazily reevaluate the attribute, just by deleting it. Using the > Person example from your blog post: > > >>> p = Person('John', 'Smith') > >>> p.display_name > 'John Smith' > >>> p.display_name > 'John Smith' > >>> p.calls_count > 1 > >>> p.first_name = 'Eliza' > >>> del p.display_name > >>> p.display_name > 'Eliza Smith' > >>> p.calls_count > 2 > > Although in general it's probably better to use some form of reactive > programming for that. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
