Re: Style question - defining immutable class data members

2009-03-15 Thread Gary Herron

John Posner wrote:

Matthew Woodcraft said:

  

I doubt it's because anyone particularly wanted this
behaviour; it just
falls out of the way '+=' is defined.

At the point where 'inst.x += 1' is compiled,
Python doesn't know
whether 'inst.x' is going to turn out to be a class
attribute or an
instance attribute or a property. So really the only thing
it can do is
generate code to read inst.x in the usual way and then
assign to inst.x
in the usual way (where 'the usual way' for CPython
is LOAD_ATTR and
STORE_ATTR).



That sounds reasonable to me.


Matthew Woodcraft also said:

  

Is there any actual advantage to self.attribute picking up
Class.attribute instead of raising a NameError?
  


  

You use that any time you call an ordinary method using syntax like
'self.foo()'.



Yes, but that's performing a read (and call) operation on an attribute. My 
question concerned itself with potential confusion when you perform a write 
operation on an attribute.


Bruno Desthuilliers said:

  

My question is ... WHY does the interpreter  silently create the
instance attribute at this point,
  


  

Becaause that's how you create instance attributes in Python. Why do you
think 'self' - that is, a reference to some object - is mandatory in
"methods" (really, functions) arguments list ?



  

Or do you mean that the existence of a synonym class attribute should be
checked on each instance variable assignement ? This would probably be a
big performance hit, ...



Yes, Bruno, I'm persuaded by this argument. Ideally, I'd like the interpreter 
to prevent the programmer from shooting him/herself in the foot, but it's not 
worth the performance hit.

  

and it would make per-instance method overloading
impossible (remember that OOP is about objects, not classes).



Yes again. While I was writing the above comment ("write operation on an 
attribute"), it *did* cross my mind that you might want to write self.attribute, 
even if it names a method, not a data-item.


Summary: I no longer suspect that "Python is broken". I *do* think that there's 
a situation that is potentially quite confusing:

 * In the statement "self.x = self.x + 1", the two "self.x" names can sometimes 
refer to different objects.

 * Even worse, in the equivalent statement "self.x += 1", the single name 
"self.x" can sometimes refer to two different objects!

I think this situation should be handled in documentation. (I'm a tech writer 
in my day job ... oh wait, I forgot ... I got laid off from my day job in 
December.) I'll look into what the standard Python doc set says on this matter.
  


What's broken here is trying to have a class variable and an instance 
variable of the same name and expecting Python to get it right. 

Both of these problems become non-issues if you follow the "best 
practice" for defining instance variables: 

That is, set instance variables to their initial value in the __init__ 
method.And if you need a class default value, name it differently:


For example:

class C:
 default_x = 123

 def __init__(self):
   self.x = self.default_x

 def inc(self):
   self.x += 1 // behaves as expected

Then self.x or inst=C() and inst.x will always refer to a instance 
variable, the code is clear,  and no confusion ensues.




Gary Herron






-John

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


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


Re: VMware and pywin32 error...

2009-03-15 Thread dash

Joshua Kugler schrieb:

dot wrote:

has anyone experience with installing Python and pywin32 to Windows XP
Pro running in a VMware environment?

At the end of installing pywin32 I get following error:


Traceback (most recent call last):
   File "", line 601, in 
   File "", line 311, in install
   File "", line 149, in LoadSystemModule
ImportError: DLL load failed: This application has failed to start
because the application configuration is incorrect. Reinstalling the
application may fix this problem.


I use following versions:

VMware Workstation 6.5.0 build-118166
Microsoft Windows XP Professional English Build 2600
added SP1 and than SP3
Python 2.6.1
pywin32 213


I've installed and run Python and pywin32 in a VMWare environment and have
had no trouble.  This is not an issue with VMWare. Something is
misconfigured in your XP and/or Python install.  I'm assuming you installed
Python before installing pywin32?

j


Yes. Of course. Python 2.6.1 installs with no problem.

BTW: I get the same result, if I use Microsoft VirtualPC 2007 instead of 
VMware...


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


Re: VMware and pywin32 error...

2009-03-15 Thread dash

Joshua Kugler schrieb:

dot wrote:

has anyone experience with installing Python and pywin32 to Windows XP
Pro running in a VMware environment?

At the end of installing pywin32 I get following error:


Traceback (most recent call last):
   File "", line 601, in 
   File "", line 311, in install
   File "", line 149, in LoadSystemModule
ImportError: DLL load failed: This application has failed to start
because the application configuration is incorrect. Reinstalling the
application may fix this problem.


I use following versions:

VMware Workstation 6.5.0 build-118166
Microsoft Windows XP Professional English Build 2600
added SP1 and than SP3
Python 2.6.1
pywin32 213


I've installed and run Python and pywin32 in a VMWare environment and have
had no trouble.  This is not an issue with VMWare. Something is
misconfigured in your XP and/or Python install.  I'm assuming you installed
Python before installing pywin32?

j


Yes. Of course. Python 2.6.1 installs with no problem.

BTW: I get the same result, if I use Microsoft VirtualPC 2007 instead of 
VMware...


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


Re: VMware and pywin32 error...

2009-03-15 Thread dash

Joshua Kugler schrieb:

dot wrote:

has anyone experience with installing Python and pywin32 to Windows XP
Pro running in a VMware environment?

At the end of installing pywin32 I get following error:


Traceback (most recent call last):
   File "", line 601, in 
   File "", line 311, in install
   File "", line 149, in LoadSystemModule
ImportError: DLL load failed: This application has failed to start
because the application configuration is incorrect. Reinstalling the
application may fix this problem.


I use following versions:

VMware Workstation 6.5.0 build-118166
Microsoft Windows XP Professional English Build 2600
added SP1 and than SP3
Python 2.6.1
pywin32 213


I've installed and run Python and pywin32 in a VMWare environment and have
had no trouble.  This is not an issue with VMWare. Something is
misconfigured in your XP and/or Python install.  I'm assuming you installed
Python before installing pywin32?

j


Yes. Of course. Python 2.6.1 installs with no problem.

BTW: I get the same result, if I use Microsoft VirtualPC 2007 instead of 
VMware...


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


Re: Problem while copying a file from a remote filer

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 10:24 PM, venutaurus...@gmail.com
 wrote:
> Hi all,
>      I have to write an application which does a move and copy of a
> file from a remote machine to the local machine. I tried something
> like:
>
> file = ur"venuwin2008\\C\\4Folders\\Folder02\\Folder002\
> \TextFile_06.txt"

The 'r' prefix on the string makes it a raw string, meaning you don't
have do double-up the backslashes, but you did so anyway, so your path
has many extra backslashes, making it invalid. Dropping the 'r' prefix
should fix the problem.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWin32 for Python 3.x

2009-03-15 Thread John Machin
On Mar 16, 7:27 am, Tim Golden  wrote:

[snip]

> people take to categorise their packages appropriately. It
> could well be the case that a number of packages will work
> in Python 3.x without modification but their entry probably
> won't reflect that unless their maintainer's gone to the
> trouble to test the package and update it.

Excuse me, but what I read in this newsgroup, supported by my
experience doing a triage port followed by a fullscale practice port
on each of 2 non-trivial packages that I maintain (xlrd and xlwt),
suggests that the likelihood of a pure Python module (let alone
package) working with Python 3.X (even after going through 2to3)
without modification is rather low ... unless it was rather small and
had been written expressly to work unchanged in 2.X and 3.X. [1] It's
been stated authoritatively that the subset of Python that will run
unchanged unported un2to3ed is "crippled". Many packages support old
versions of Python (xlrd back to 2.1; some of the effbot's goodies
(e.g. PIL) run on 1.5.2 even), increasing the effort required to
assess the scope of the port, let alone implement it.

IOW any package that isn't specified as being 3.X-ready is unlikely to
be 3.X-ready. And if it was ready, wouldn't you want to wait till the
maintainer had tested that it was, and published its readyness?

> Obviously, in the case of (Windows) extension modules,
> the module will at the very least need recompiling and
> rebuilding even if the code works without modification.

I could be wrong, but I got the impression that the C-API had changed
significantly from 2.x to 3.X and module initialisation had changed
drastically ... see (for example) 
http://docs.python.org/3.0/howto/cporting.html#cporting-howto
... Looks to me like the chance of any extension (Windows or not) not
requiring changes is zero.

[1]: I've written a pure-Python module for calculating Levenshtein
distance using a bit-parallel algorithm; it will work on 3.x unchanged
because it operates on two sequences which need to support only seq[x]
and len(seq) and whose elements need to be hashable and comparable and
not much else, and it doesn't import anything. This is very small,
recent, and deliberate, hence definitely not the norm.

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


Re: setattr() on "object" instance

2009-03-15 Thread Ahmad Syukri b
On Mar 16, 1:21 pm, Sean DiZazzo  wrote:
> Why is it that you can setattr() on an instance of a class that
> inherits from "object", but you can't on an instance of "object"
> itself?
>
> >>> o = object()
> >>> setattr(o, "x", 1000)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'object' object has no attribute 'x'

I suppose you cannot set attributes to instances of any built-in
classes, i.e. int(), list() etc.

> >>> class Object(object):pass
> ...
> >>> o = Object()
> >>> setattr(o, "x", 1000)
> >>> o.x
>
> 1000
>
> I notice that the first example's instance doesn't have a __dict__.
> Is the second way the idiom?
>
> ~Sean

Since all classes inherit from object, I suppose the definition can be
as simple as 'class Object:pass', and assignment can be as simple as
'o.x = 1000'

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


Problem while copying a file from a remote filer

2009-03-15 Thread venutaurus...@gmail.com
Hi all,
  I have to write an application which does a move and copy of a
file from a remote machine to the local machine. I tried something
like:

file = ur"venuwin2008\\C\\4Folders\\Folder02\\Folder002\
\TextFile_06.txt"
dest = "C:\\test"
shutil.copy(file,dest)

But it is throwing an error:

Traceback (most recent call last):
  File "E:\venu\Testing Team\test.py", line 22, in 
shutil.copy(file,dest)
  File "C:\Python26\lib\shutil.py", line 88, in copy
copyfile(src, dst)
  File "C:\Python26\lib\shutil.py", line 52, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 22] invalid mode ('rb') or filename: u'\\\
\venuwin2008C4FoldersFolder02Folder002\\\
\TextFile_06.txt'

Can some one please help me in this regard.

Thank you
Venu madhav
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Gary Herron

John Posner wrote:

(My apologies if the thread has already covered this.) I believe I understand 
the WHAT in this situation, but I don't understand the WHY ...

Given this class definition:

  class Cls(object):
  x = 345

... I observe the following, using IDLE 2.6.1:

  

inst = Cls()
Cls.x is inst.x


True

  

Cls.x += 1
Cls.x is inst.x


True

  

inst.x += 1
Cls.x is inst.x


False

My question is ... WHY does the interpreter silently create the instance attribute at 
this point, causing a "surprising decoupling" from the class attribute? WHY 
doesn't the interpreter behave as it would with a simple, non-instance variable:

  > python
  Python 2.6.1 ...
  Type "help", "copyright", "credits" or "license" for more information.

  >>> x += 1
  Traceback (most recent call last):
File "", line 1, in 
  NameError: name 'x' is not defined

Is there a beneficial effect of silently creating the instance attribute, which outweighs 
the detrimental effects: (1) inconsistency, (2) the "surprising" decoupling?
  


I wouldn't call it "silently" because "inst.x = ..." is quite explicit 
about "x" being an attribute of "inst".  The rules for creating a 
variable are simple and very consistent.


Each of
 Cls.x = ...
 inst.x = ...
 x = ...
will create a variable (if it does not already exist) in a class, 
instance or local name space respectively. 

Retrieving a value is more complex as Python may look through several 
namespaces in succession to find a value:  (For example, inst.x will 
check the instance , then the class ...)


The problem here is that
 inst.x += 1
is really
 inst.x = inst.x+1
which according to those rules, (if inst.x is not yet defined)
has both an instance and a class reference in the same statement.

After that, x.inst is defined in the instance, so both sides refer to that.



Gary Herron





Tx,
John


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


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


Re: PyWin32 for Python 3.x

2009-03-15 Thread John Nagle

Tim Golden wrote:

John Nagle wrote:

   Well, of some other packages I use:

MySQLdb: "Python versions 2.3-2.5 are supported."
Ref: http://sourceforge.net/projects/mysql-python
M2Crypto: Latest version is for Python 2.6.
Ref: http://chandlerproject.org/bin/view/Projects/MeTooCrypto

Somebody who's into tracking might want to maintain a big cross-reference
table of "what packages work with what versions".



I'm inclined to agree. I remember some discussion about adding
a Wiki page for this, but searching quickly what I've come up
with is a suggestion in the Py3k/FAQ page:

 http://wiki.python.org/moin/Python3000/FAQ

which points towards a PyPI query listing packages which have
Python :: 3 tagged:

 http://pypi.python.org/pypi?:action=browse&c=533

It doesn't seem an entirely unreasonable approach. It falls
short of a researched / edited page (even a Wiki one) but
that would be a lot of work. I'm not sure how many Python
packages don't make into PyPI, nor am I sure how much effort
people take to categorise their packages appropriately.


At least there's a place to put the information.  But the
data isn't there.  The short list of 40 packages listed as working with
Python 3.0 contains mostly minor, special-purpose packages.

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


Re: Integer arithmetic in hardware descriptions

2009-03-15 Thread bearophileHUGS
JanC:
> In most "modern" Pascal dialects the overflow checks can be (locally)
> enabled or disabled with compiler directives in the source code,

I think that was possible in somewhat older versions of Pascal-like
languages too (like old Delphi versions, and maybe TurboPascals too).


>so the "speed issue" is not a real issue in practice...<

How can I help Walter (the designer and writer of the D language)
understand this? Do you have articles or other ways that support this
point of view?
Patching the D compiler to re-run programs and benchmarks with such
controls present isn't something I can do yet, probably :o)
(Despite there's a LLVM-based D compiler too now, named LDC, and it
already supports the LLVM intrinsics to perform overflow checks).

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


Re: multiprocessing.sharedctypes and built-in locks

2009-03-15 Thread Ahmad Syukri b
On Mar 15, 6:19 am, Aaron Brady  wrote:
>
> Your code hung on my machine.  The call to 'main()' should be in an
> 'if __name__' block:
>
> if __name__== '__main__':
>     main()
>
> Is it possible you are just seeing the effects of the non-atomic
> '__iadd__' operation?  That is, the value is read, added, and written
> at different times, between which other processes might have
> intervened.

I've forgotten to remove ' gl.append(mp.Lock()) ' from the second
code.

Anyways if what you said is true, then why doesn't the documentation
say so? I also realized that the created lock's release and acquire
methods are also imbued to the created shared object, and this is also
undocumented.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Machin
On Mar 16, 3:08 pm, a...@pythoncraft.com (Aahz) wrote:
> In article ,
> Roy Smith   wrote:
>
> >In article ,
> > Chris Rebert  wrote:
>
> >> Besides your behavior, one could equally well argue that a 31st repeat
> >> on months without a 31st should just be dropped, or that it should
> >> carry over onto the 1st of the next month (ignoring the complications
> >> of February). Which behavior one needs is completely
> >> context-dependent.
>
> >Indeed.  For example, my wife started her current job on a Feb 29th.  There
> >are significant financial events that happen on various anniversaries of
> >her employment (vesting of stock and retirement benefits).  It really is
> >important that everybody know exactly what is meant by "10 years from Feb
> >29th, on a given year", and what it means in one context may not mean what
> >it means in another.
>
> Because I'm well-aware of such issues, I would have asked to make my
> official start date March 1.  ;-)

Which means that any goodies accruing after 4, 8, etc years are
granted on 1 March instead of the (obvious?) 29 February.

What you want is an agreement that the anniversary of commencement in
any year is the last day of February.


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


setattr() on "object" instance

2009-03-15 Thread Sean DiZazzo
Why is it that you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself?

>>> o = object()
>>> setattr(o, "x", 1000)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'object' object has no attribute 'x'

>>> class Object(object):pass
...
>>> o = Object()
>>> setattr(o, "x", 1000)
>>> o.x
1000

I notice that the first example's instance doesn't have a __dict__.
Is the second way the idiom?

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


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
what is I just set
"colors": self.opt['arg_opts_options']['imp_colors']

then they are both pointing to the same place, correct?

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 11:16 PM, alex goretoy
wrote:

> i did this because this will read colors into a nested variable
>
> How would i make this work the way you suggest? I already have it working
> now :)
>
> Not able to set to dict value with setattr, how to do this too(sorry if off
> subject)?
>
> I can set it like this:
>
> for i in self.opt['properties'].keys():
> self.opt[i] =
> getattr(self.opt['properties_object'], i)
> but not like this:
> for i in self.opt['properties'].keys():
> setattr(self, opt[i],
> getattr(self.opt['properties_object'], i))
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 6:41 PM, MRAB  wrote:
>
>> alex goretoy wrote:
>>
>>> ok now for the final result, i decided to split options out to a separate
>>> dict of lists, does this look right to every one, I currently have error
>>> somewhere else in my code so can't test this right now, Is this a good
>>> method to do this? or is there another option?
>>>
>>>  [snip]
>> First of all, *don't use "is" and "is not" to test for equality*; use "=="
>> and "!=".
>>
>> When you split the options out like that you get duplication.
>>
>> You have, for example:
>>
>>...
>>"colors": ["c", "cl", "col", ...]
>>...
>>
>> and:
>>
>>...
>>"imp_colors": ["c", "cl", "col", ...]
>>...
>>
>> Couldn't you put them into one dict, something like:
>>
>>   ...
>>   "colors": ("imp_colors", ["c", "cl", "col", ...])
>>   ...
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
i did this because this will read colors into a nested variable

How would i make this work the way you suggest? I already have it working
now :)

Not able to set to dict value with setattr, how to do this too(sorry if off
subject)?

I can set it like this:

for i in self.opt['properties'].keys():
self.opt[i] = getattr(self.opt['properties_object'],
i)
but not like this:
for i in self.opt['properties'].keys():
setattr(self, opt[i],
getattr(self.opt['properties_object'], i))
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 6:41 PM, MRAB  wrote:

> alex goretoy wrote:
>
>> ok now for the final result, i decided to split options out to a separate
>> dict of lists, does this look right to every one, I currently have error
>> somewhere else in my code so can't test this right now, Is this a good
>> method to do this? or is there another option?
>>
>>  [snip]
> First of all, *don't use "is" and "is not" to test for equality*; use "=="
> and "!=".
>
> When you split the options out like that you get duplication.
>
> You have, for example:
>
>...
>"colors": ["c", "cl", "col", ...]
>...
>
> and:
>
>...
>"imp_colors": ["c", "cl", "col", ...]
>...
>
> Couldn't you put them into one dict, something like:
>
>   ...
>   "colors": ("imp_colors", ["c", "cl", "col", ...])
>   ...
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python not return first line?

2009-03-15 Thread John Machin
On Mar 16, 11:25 am, Gilles Ganault  wrote:
> On Mon, 16 Mar 2009 01:14:00 +0100, Gilles Ganault 
> wrote:
>
> >I'm stuck at why Python doesn't return the first line in this simple
> >regex
>
> Found it: Python does extract the token, but displaying it requires
> removing hidden chars:
>
> =
> response = "Address :\r\t\t\r\t\t\t3 Abbey Road,
> St Johns Wood \r\t\t\tLondon, NW8 9AY\t\t"
>
> re_address = re.compile('Address
> :.+?(.+?)',re.I | re.S | re.M)
>
> address = re_address.search(response)
> if address:
>         address = address.group(1).strip()

When in doubt, use the repr() function (2.X) or the ascii() function
(3.X); it will show you unambiguously exactly what you have in a
string; in this case:

'3 Abbey Road, St Johns Wood \r\t\t\tLondon, NW8 9AY'

>
>         #Important!
>         for item in ["\t","\r"," "]:
>                 address = address.replace(item,"")
>
>         print "address is %s" % address

and the result is:

3 Abbey Road, St Johns WoodLondon, NW8 9AY

WoodLondon ??

Consider the possibility that whether the webpage originated on *x or
not, the author inserted that "" with beneficial intent i.e. not
just to annoy you. You may wish to replace it with something instead
of discarding it.

If you really want the address to look tidy, you could do something
like this:

def norm_space(s):
return ' '.join(s.split())

tidy = ", ".join([norm_space(x) for x in address.replace('',
',').strip(' ,').split(',')])

Perhaps the "http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Aahz
In article ,
Roy Smith   wrote:
>In article ,
> Chris Rebert  wrote:
>>
>> Besides your behavior, one could equally well argue that a 31st repeat
>> on months without a 31st should just be dropped, or that it should
>> carry over onto the 1st of the next month (ignoring the complications
>> of February). Which behavior one needs is completely
>> context-dependent.
>
>Indeed.  For example, my wife started her current job on a Feb 29th.  There 
>are significant financial events that happen on various anniversaries of 
>her employment (vesting of stock and retirement benefits).  It really is 
>important that everybody know exactly what is meant by "10 years from Feb 
>29th, on a given year", and what it means in one context may not mean what 
>it means in another.

Because I'm well-aware of such issues, I would have asked to make my
official start date March 1.  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Adopt A Process -- stop killing all your children!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Tim Wintle
On Mon, 2009-03-16 at 04:02 +, Tim Wintle wrote:
> On Sun, 2009-03-15 at 10:39 -0700, John Posner wrote:

Doh, reply out of thread there - I meant to reply to Rhodi's comment
further down.
> Is there any actual advantage to self.attribute picking up
> Class.attribute instead of raising a NameError?


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


Re: Style question - defining immutable class data members

2009-03-15 Thread Tim Wintle
On Sun, 2009-03-15 at 10:39 -0700, John Posner wrote:
> (My apologies if the thread has already covered this.) I believe I understand 
> the WHAT in this situation, but I don't understand the WHY ...

> Is there a beneficial effect of silently creating the instance attribute, 
> which outweighs the detrimental effects: (1) inconsistency, (2) the 
> "surprising" decoupling?

>From an end-user point of view (rather than the point of accessing class
methods others mentioned), here are two more reasons:

1) To save memory - there's only one object stored, where an instance
variable will require the same memory every instance (normally)


2) referencing Zope objects (although any persistent object storage will
have the same argument):

(Zope is a web framework that stores data as instances of python classes
in a persistent database.)

let's say you have the class (missing all the boilerplate)

{{{
class ZMyUser():
def __init__(self):
self.lookuplanguage = {\
"EN": "English"
}
self.language = "EN"

def get_friendly_name(self):
return self.lookuplanguage.get(self.language,"--")
}}}

And you create loads of these objects. But then you want to add French
as an option. How do you do that? All the objects have already been
created, so you could either: 

 * Run through every object in the database one by one and update the
dict as a one-off task (potentially taking a very long time as you force
the computer to pull the entire database off disk)

 * Have written  lookuplanguage as a class property, so re-initialising
the class will update the definition without any extra overhead.




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


Re: PyPy Progress (and Psyco)

2009-03-15 Thread JanC
andrew cooke wrote:

> Fuzzyman wrote:
>> On Mar 15, 3:46 pm, Gerhard Häring  wrote:
> [...]
>>> Me too. I doubt it, though. From an outside view, the project seems to
>>> lack focus. To me, it looks like a research platform, and producing a
>>> successor to CPython seems to be just one out of a dozen projects.
> [...]
>> Well, I know the guys involved and they are focused on making PyPy a
>> practical (and importantly a faster) alternative to CPython. It has
>> just taken a long time - but is finally showing real progress.
>>
>> They did get distracted along the way, but one of things that happened
>> last year was a culling of a lot of the side projects that made it
>> harder to make progress on the core goals.
>
> This is so good to hear.  I had exactly the same concerns as Gerhard. 
> Thanks for posting some information.

I think the period as a research platform (IIRC the project was funded by a
research grant from the EU after all[*]) was maybe necessary to get where
they are now...?


[*] I'm happy to see at least this part of my taxes being spent for
something good...  ;-)

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


Re: Integer arithmetic in hardware descriptions

2009-03-15 Thread JanC
bearophileh...@lycos.com wrote:

> Some C# designers come from Pascal (where overflow is considered an
> important thing), and they have added to dotnet ways to find when an
> overflow occurs, globally in a program, locally in a piece of code, or
> even in a single part of an expression. This is much better than
> nothing.

> I'm fighting against the C/C++ crowd to add C#-like integer overflows
> to the D2 language, but with not much luck so far, all they (Walter,
> mostly) see is the "lower performance" it may lead.

In most "modern" Pascal dialects the overflow checks can be (locally)
enabled or disabled with compiler directives in the source code, so the
"speed issue" is not a real issue in practice...



This allows you to disable those checks in e.g. a very speed-sensitive piece
of code (that you must check for correctness yourself then of course, but
that's better than having to check *all* code).


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


Re: Style question - defining immutable class data members

2009-03-15 Thread Rhodri James
On Sun, 15 Mar 2009 23:26:04 -, Aaron Brady   
wrote:



On Mar 15, 1:50 pm, "Rhodri James" 
wrote:

On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady   
wrote:

> On Mar 15, 12:39 pm, John Posner  wrote:
>> (My apologies if the thread has already covered this.) I believe I  
>> understand the WHAT in this situation, but I don't understand the >>  
WHY  

[snip]

> Yes.  If you access an attribute, you want the search to go like this:

> - check instance for attribute
> - check class for attribute
> - check base classes for attribute

But do you, though?  The only occasion I can think of that I'd want
the search to go past the instance is this "auto-initialisation",
and frankly I'd rather do that in an __init__ anyway.  Perhaps
static methods or class methods work that way, I don't know how
the innards of the interpreter handle that.


As Bruno stated, yes, for resolving 'self.method', and other
descriptors.  You acknowledge that 'foo.jam' would need to identify
itself as coming from an instance, class, or base, since the only
entries in 'foo's dictionary are those attributes which are particular
to 'foo'.


No, I don't acknowledge that.  (Note that John's original question
was *WHY*, and you effectively gave him a *HOW* answer by asserting
that it's what he wants.  I'm playing Devil's Advocate to an extent.)

"self.method" is not the same object as "Class.method"; one's bound
and the other isn't, for starters.  It's therefore by no means
obvious that method lookup isn't being done via the instance's
dictionary.  After all, some kind of binding has to be done at
instance creation time.  If you're telling me that it's time-
efficient (or at least space-efficient and not horribly time-
inefficient) to use the class dictionary and magically know to
wrapper the call, then we've that makes things different and
gives us a reason for wanting that search order.

It's the same story with descriptors; in fact they mask rather
more of the detail of what they're doing and look at first glance
more tightly bound to the instance than the class.  Further steps
get you to the same "why" answer, but they are further steps.


Class attributes are grouped together in the class dictionary,
instance attributes are grouped together in the instance dictionary,
and instances need to see both.


True, but they don't need to see both with instance attribute
syntax.  That they can is what we're trying to justify here.


If you have a counter-proposal, either for a wishlist for behavior, or
a way of arranging its implementation, I for one would entertain it,
even on the c-l-python newsgroup, and even though it wouldn't have
much of a chance of making it in to Python.


Nope, no proposal.  Mildly considering one, but I thought I'd try
understanding why what happens is considered a good thing before I
let my hare-brainedness off the leash.


As a side note, this argument of 'whose methods am I seeing?' has an
inconvenient artifact: the behavior of 'foo.method'.  'foo.method'
needs to refer to an instance method, due to not needing the 'self'
attribute respecified; while 'foo.__class__.method' needs to refer to
a plain function.  Python's solution is a skeleton type, that just
redirects 'foo.method( )' to an append of the arguments plus call.


As I said, this inconvenient artefact is exactly why I didn't think
assuming instance method lookup happened via the *class* dictionary
was safe!


 Actually what I want is for
the attribute to be stored where I told it, which could well be in
the class.  If the attribute is specified as "self.attribute", then
yes, put it in the instance.


The way C++ works is by allocating storage for the data and method
pointers in a class.

class X {
int foo;
char jam[ 12 ];
int foojam( int y, int z ) { ...; }
};

X requires 20 bytes: 4 for 'foo', 12 for 'jam', and 4 for 'foojam'...
under a 32-bit target.  (The 4 for 'foojam' come from a virtual
function table, for polymorphic objects er, technically.)


I'm sorry, I'm utterly baffled.  Why is this relevant to my bit
of pedantry?


You get what you want: attributes are stored where you tell them.  But
where are they read from?


No, *why*.  These questions aren't about what the search order
is, they're about why there is a search order.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread John Posner

Earlier, I said:

> I'll look into what the standard Python doc set says on this
> matter.
> 

RTFM, in section "Augmented assignment statements" of python301.chm:

---
For targets which are attribute references, the initial value is retrieved with 
a getattr() and the result is assigned with a setattr(). Notice that the two 
methods do not necessarily refer to the same variable. When getattr() refers to 
a class variable, setattr() still writes to an instance variable. For example:

class A:
x = 3# class variable
a = A()
a.x += 1 # writes a.x as 4 leaving A.x as 3
---

So, this case is closed ... almost. I believe a similar explanation, with a 
similar example, should appear in the preceding/parent section, "Assignment 
statements". Here's my proposed example:

   class A:
   x = 3 # class variable
   a = A()
   a.x = a.x + 1 # a.x on RHS gets value of class variable (3)
 # a.x on LHS creates instance variable with
   value of RHS expression (4)

Others' thoughts on this?

-John

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-15 Thread MRAB

Rhodri James wrote:
On Sun, 15 Mar 2009 19:00:43 -, MRAB  
wrote:



Rhodri James wrote:
[snip]

Frankly, I'd much rather fix the locale system and extend
the format syntax to override the default locale.  Perhaps
something like
   financial = Locale(group_sep=",", grouping=[3])
  print("my number is {0:10n:financial}".format(1234567))
 It's hard to think of a way of extending "%" format strings
to cope with this that won't look utterly horrid, though!


The problem with your example is that it magically looks for the locale
name "financial" in the current namespace.


True, to an extent.  The counter-argument of "Is it so much
more magical than '{keyword}' looking up the object in the
parameter list" suggests a less magical approach would be to
make the locale a parameter itself:

  print("my number is {0:10n:{1}}".format(1234567, financial)


The field name can be an integer or an identifier, so the locale could
be too, provided that you know where to look it up!

financial = Locale(group_sep=",", grouping=[3])
print("my number is {0:10n:{fin}}".format(1234567, fin=financial))

Then again, shouldn't that be:

fin = Locale(group_sep=",", grouping=[3])
print("my number is {0:{fin}}".format(1234567, fin=financial))


Perhaps the name should be
registered somewhere like this:

 locale.predefined["financial"] = Locale(group_sep=",", grouping=[3])
 print("my number is {0:10n:financial}".format(1234567))


I'm not sure that I don't think that *more* magical than my
first stab!  Regardless of the exact syntax, do you think
that being able to specify an overriding locale object (and
let's wave our hands over what one of those is too) is the
right approach?



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


Re: Style question - defining immutable class data members

2009-03-15 Thread R. David Murray
John Posner  wrote:
> Summary: I no longer suspect that "Python is broken". I *do* think that
> there's a situation that is potentially quite confusing:
> 
>  * In the statement "self.x = self.x + 1", the two "self.x" names can
>  sometimes refer to different objects.

But this is fundamental to Python.  The name (or slot, in the case of say
a slice assignment) on the left hand side is being given a new binding
by the assignment statement.  So whatever object the 'self.x' on the
left hand side may have pointed to before the statement is executed is
irrelevant (if we ignore '+=' and kin).  That is the essence of assignment
in Python.  If you are surprised by this, then you should probably study
up a bit on the way namespaces work in Python.

What I think you meant is that even though both are represented by the
same token sequence in the source ('self.x'), the two 'x's are actually
located in two different namespaces.  The one on the left hand side of
the assignment is local to the instance, while the one on the right hand
side can cascade upward to the class namespace and resolve to an object
from there.

>  * Even worse, in the equivalent statement "self.x += 1", the single name
>  "self.x" can sometimes refer to two different objects!

Now on this one I'll agree with you about the "worse" part.  Consider:

>>> class A(object):
... x = [1]
... def f(self):
... self.x = self.x + [2]
... print self.x
... 
>>> 
>>> m = A()
>>> m.f()
[1, 2]
>>> A.x
[1]
>>> class B(object):
... x = [1]
... def g(self):
... self.x += [2]
... print self.x
... 
>>> n = B()
>>> n.g()
[1, 2]
>>> B.x
[1, 2]

I'm inclined to call that a problem, myself, even though I understand
why it happens (+= mutates the object pointed to by the class variable
'x', and _then_ the instance variable 'x' is created and pointed at the
same object.  Whereas in the '+' case, a new list is created and the new
'x' instance variable is pointed at that new list.)

There is a somewhat analogous situation with variables in the local scope of
a function and global variables in the module.   For example, we might have:

>>> x = 1
>>> def f():
... print x
... 
>>> f()
1

So, when 'x' isn't found locally, the value gets picked up from the global
namespace.  The difference from the class/instance case is when we try
to assign to it:

>>> def g():
... x = x + 1
... 
>>> g()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment
>>> x = []
>>> def g():
... x += [1]
... 
>>> g()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment

So in this case Python is warning us about the namespace difference.

Why are the two cases handled differently?  To tell you the truth, I'm
not sure.  I've been programming in Python for years and it just seems
to make sense to me to do it that way.  It does allow you to use class
variables as default values for instance variables, as long as you are
careful when using mutable objects.  But you could argue that it should
behave in a way analogous to local/global.  It would be interesting to
see that argument laid out in full, with all the consequences it would
entail examined.

> I think this situation should be handled in documentation. (I'm a tech writer
> in my day job ... oh wait, I forgot ... I got laid off from my day job in
> December.) I'll look into what the standard Python doc set says on this
> matter.

Doc patches are always welcome, and from what I hear easier to get
accepted than code patches ;)

--
R. David Murray   http://www.bitdance.com


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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-15 Thread Rhodri James
On Sun, 15 Mar 2009 19:00:43 -, MRAB   
wrote:



Rhodri James wrote:
[snip]

Frankly, I'd much rather fix the locale system and extend
the format syntax to override the default locale.  Perhaps
something like
   financial = Locale(group_sep=",", grouping=[3])
  print("my number is {0:10n:financial}".format(1234567))
 It's hard to think of a way of extending "%" format strings
to cope with this that won't look utterly horrid, though!


The problem with your example is that it magically looks for the locale
name "financial" in the current namespace.


True, to an extent.  The counter-argument of "Is it so much
more magical than '{keyword}' looking up the object in the
parameter list" suggests a less magical approach would be to
make the locale a parameter itself:

  print("my number is {0:10n:{1}}".format(1234567, financial)


Perhaps the name should be
registered somewhere like this:

 locale.predefined["financial"] = Locale(group_sep=",", grouping=[3])
 print("my number is {0:10n:financial}".format(1234567))


I'm not sure that I don't think that *more* magical than my
first stab!  Regardless of the exact syntax, do you think
that being able to specify an overriding locale object (and
let's wave our hands over what one of those is too) is the
right approach?

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-15 Thread Tim Rowe
2009/3/14 Hendrik van Rooyen :

> No account seems to be taken of the fact that the locale approach
> is a global one that forces uniformity on everything done on a PC
> or by a user.

Not so. Under .NET, for instance, the global settings will give you a
default CultureInfo class, but you can create your own CultureInfo
classes for other cultures in your program and use them in place of
the default.

> So when you want to make a report in a format that would suit
> what your foreign visitors are used to, do you have to change
> your server's locale, and change it back again afterwards, or what ?

No, you create a local locale and use that.

There are essentially three possible levels I can see for this:

- programs that will only ever be used in one locale, known in
advance. They can have the locale hard-wired into the program. No
special support is needed for this. It's pretty easy to write a
function to format a number to a hard-wired locale. I've done it in
Pascal and FORTH and it was easy-peasy, so I can't imagine it's going
to be a big deal in Python. If it's such a big deal for accountants to
write this code, if they ask in this forum how to do it somebody will
almost certainly supply a function that takes a float and returns a
formatted string within a few minutes. It might even be you or me.

- Programs that may be used in any unchanging locale. The existing
locale support is built for this case.

- Programs that nead to operate across locales. This can either be
managed by switching global locales (which you rightly deprecate) or
by managing alternate locales within the program.

> The locale approach has all the disadvantages of global variables.

No, it has all the advantages of global constants used as overridable
defaults for local variables.

> To make software usable by, or expandable to, different languages
> and cultures is a tricky design problem - you have to, at the
> minimum, do things like storing all your text, both for prompts and
> errors, in some kind of database and refer to it by its key, everywhere.
> You cannot simply assume, that because a number represents
> a monetary value, that it is Yen, or Australian Dollar, or whatever -
> you may have to convert it first, from its currency, to the currency
> that you want to display it as, and only then can you worry about
> the format that you want to display it in.

Nothing in the proposal being considered addresses any of that.

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


Re: [ActivePython 2.5.1.1] Why does Python not return first line?

2009-03-15 Thread Benjamin Kaplan
On Sun, Mar 15, 2009 at 8:14 PM, Gilles Ganault  wrote:

> Hello
>
> I'm stuck at why Python doesn't return the first line in this simple
> regex:
>
> ===
> response = "Address :\r\t\t\r\t\t\t3 Abbey Road,
> St Johns Wood \r\t\t\tLondon, NW8 9AY\t\t"
>
> re_address = re.compile('Address
> :.+?(.+?)',re.I | re.S | re.M)
>
> address = re_address.search(response)
> if address:
>address = address.group(1).strip()
>print "address is %s" % address
> else:
>print "address not found"
> ===
> C:\test.py
>London, NW8 9AY
> ===
>
> Could this be due to the non-printable characters like TAB or ENTER?
> FWIW, I think that the original web page I'm trying to parse is from a
> *nix host.
>

Actually, the problem is that the only newlines you have on there are Mac OS
Classic/Commodore newlines. Windows new lines date back to typewriters.
There are two characters in a Windows newline- a carriage return (\r), which
returns the cursor to the beginning of the line, and linefeed (\n) which
moves to the next line. I think what's happening is that Windows tries to
duplicate the commands from the typewritter- it returns to the beginning of
the line at the carriage return, but doesn't move to a new one. The second
half of the text overwrites the first half, and you get the problem you're
seeing. The only way I can think of to fix this is to search for any
carriage return not followed by a linefeed and add a linefeed in.

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Yeung
On Mar 15, 7:26 pm, Chris Rebert  wrote:
> [...] the point is that there are likewise reasonable usecases
> for the other behaviors too and one should refuse to guess in
> the face of ambiguity; the std lib has, merely by default in
> this case, taken this to the extreme of not implementing any
> of them directly.
>
> Somewhat unrelated wish: if only dateutil were in the std
> lib... Alas!

dateutil makes a very clear choice about the behavior of month
arithmetic (namely, the one which the OP was after).  Has it not
"guessed in the face of ambiguity"?

Personally, I don't think OP's original phrasing of the problem was
too ambiguous.  I agree there are other reasonable interpretations,
but I disagree that his intention was unclear.  His intention matches
what I believe to be the prevailing one; thus I don't find dateutil's
choice to be much of a guess.

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Yeung
On Mar 15, 6:25 pm, John Machin  wrote:
> A couple of issues here:
>
> (1) The number of days in a month is not a constant, so "a
> mathematician's sense of logic" is quite irrelevant.

It's relevant in the sense that some commenters on this thread seem to
want to apply some semblance of mathematical logic to the problem.
Also, I referred to *date* math as not always being mathematically
logical, not *month* math (which some might argue is inherently not
subject to mathematical logic; perhaps this is your position, I can't
quite tell if that's the intent of your statement).

> (2) The various *different* LPDMs are quite well established
> and each of them can be reduced to non-ambiguous rules provided
> that the reducer is patient and persistent and avoids terms
> like "ugly", "illogical", "ludicrous" ... early stages of the
> reduction process can produce things like "31 January plus 1
> month -> 3 March (2 March in a leap year)" :-)

I don't know if by "different LPDMs" you mean that "day math" is one
LPDM and "month math" is another, not quite compatible LPDM; or if you
mean there are several well-established meanings for the same verbal
expressions such as "add three months to Feb 28".  If the former, then
I agree in principle, though with different terminology.  If the
latter, I disagree, based on my experience.

I've done a lot of the reduction work you are talking about, and the
same verbal phrases tend to map to the same specific rules in the
end.  Of course, that may not be everyone's experience, but it is
mine.  It is also evidently the experience of dateutil's author and
the developers of all of the date routines and calendar programs I
have personally tried (which, granted, isn't all that many, but
includes extremely popular ones).

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


Re: [ActivePython 2.5.1.1] Why does Python not return first line?

2009-03-15 Thread Gilles Ganault
On Mon, 16 Mar 2009 01:14:00 +0100, Gilles Ganault 
wrote:
>I'm stuck at why Python doesn't return the first line in this simple
>regex

Found it: Python does extract the token, but displaying it requires
removing hidden chars:

=
response = "Address :\r\t\t\r\t\t\t3 Abbey Road,
St Johns Wood \r\t\t\tLondon, NW8 9AY\t\t"

re_address = re.compile('Address
:.+?(.+?)',re.I | re.S | re.M)

address = re_address.search(response)
if address:
address = address.group(1).strip()

#Important!
for item in ["\t","\r"," "]:
address = address.replace(item,"")

print "address is %s" % address
else:
print "address not found"
=

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


[ActivePython 2.5.1.1] Why does Python not return first line?

2009-03-15 Thread Gilles Ganault
Hello

I'm stuck at why Python doesn't return the first line in this simple
regex:

===
response = "Address :\r\t\t\r\t\t\t3 Abbey Road,
St Johns Wood \r\t\t\tLondon, NW8 9AY\t\t"

re_address = re.compile('Address
:.+?(.+?)',re.I | re.S | re.M)

address = re_address.search(response)
if address:
address = address.group(1).strip()
print "address is %s" % address
else:
print "address not found"
===
C:\test.py
London, NW8 9AY
===

Could this be due to the non-printable characters like TAB or ENTER?
FWIW, I think that the original web page I'm trying to parse is from a
*nix host.

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


Re: Correct URL encoding

2009-03-15 Thread mattia
Il Sun, 15 Mar 2009 17:05:16 -0700, Chris Rebert ha scritto:

> On Sun, Mar 15, 2009 at 4:54 PM, gervaz  wrote:
>> On Mar 16, 12:38 am, Graham Breed  wrote:
>>> mattia wrote:
>>> > I'm using urlopen in order to download some web pages. I've always
>>> > to replace some characters that are in the url, so I've come up
>>> > with: url.replace("|", "%7C").replace("/", "%2F").replace(" ",
>>> > "+").replace (":", "%3A")
>>> > There isn't a better way of doing this?
>>>
>>> Yeah, shame there's no function -- called "urlencode" say -- that does
>>> it all for you.
>>>
>>>                        Graham
>>
>> Sorry, but using Python 2.6 and urlencode I've got this error:
>> TypeError: not a valid non-string sequence or mapping object What I was
>> looking for (found in Python3) is: from urllib.parse import quote
>> urlopen(quote(url)).read()
>> but seems there is nothing similar in py2.6
> 
> (*cough*) [Python v2.6.1 documentation] urllib.quote() -
> http://docs.python.org/library/urllib.html#urllib.quote (*cough*)
> 
> - Chris

Ouch! It's time for me to go to sleep ;-) Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Correct URL encoding

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 4:54 PM, gervaz  wrote:
> On Mar 16, 12:38 am, Graham Breed  wrote:
>> mattia wrote:
>> > I'm using urlopen in order to download some web pages. I've always to
>> > replace some characters that are in the url, so I've come up with:
>> > url.replace("|", "%7C").replace("/", "%2F").replace(" ", "+").replace
>> > (":", "%3A")
>> > There isn't a better way of doing this?
>>
>> Yeah, shame there's no function -- called "urlencode" say --
>> that does it all for you.
>>
>>                        Graham
>
> Sorry, but using Python 2.6 and urlencode I've got this error:
> TypeError: not a valid non-string sequence or mapping object
> What I was looking for (found in Python3) is:
> from urllib.parse import quote
> urlopen(quote(url)).read()
> but seems there is nothing similar in py2.6

(*cough*) [Python v2.6.1 documentation] urllib.quote() -
http://docs.python.org/library/urllib.html#urllib.quote (*cough*)

- Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Correct URL encoding

2009-03-15 Thread gervaz
On Mar 16, 12:38 am, Graham Breed  wrote:
> mattia wrote:
> > I'm using urlopen in order to download some web pages. I've always to
> > replace some characters that are in the url, so I've come up with:
> > url.replace("|", "%7C").replace("/", "%2F").replace(" ", "+").replace
> > (":", "%3A")
> > There isn't a better way of doing this?
>
> Yeah, shame there's no function -- called "urlencode" say --
> that does it all for you.
>
>                        Graham

Sorry, but using Python 2.6 and urlencode I've got this error:
TypeError: not a valid non-string sequence or mapping object
What I was looking for (found in Python3) is:
from urllib.parse import quote
urlopen(quote(url)).read()
but seems there is nothing similar in py2.6
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter: loading file before entering mainloop

2009-03-15 Thread John McMonagle
Peter Billam wrote:
> On 2009-03-14, Peter Otten <__pete...@web.de> wrote:
>> Well, I don't know where the ymid[...] values come from. If you can
>> guarantee that ymid[track_num] - ymid[track_num-1] > 50 at some point
>> you could reschedule loadFile() from within loadFile() and return
>> immediately as long as that condition is not met.
> 
> They're multiplied up from
>   canvas_height = self.canvas.winfo_height()
> so I guess mainloop already think it's idle, while grid is still taking
> 10ms to work out what goes where. It's not a specifically canvas thing,
> because to the left of the canvas there is a frame (called trackbar)
> which has the same height, and self.trackbar.winfo_height() gives the
> same effects.
> 
> Your suggestion would also defend me against small screens, or midi-
> -files with large numbers of tracks (I'll impose a max_retries)...
> 
> Thanks,  Regards,  Peter
> 
You need to query the requested width and height for windows which are
not yet realised.

canvas_height = self.canvas.winfo_reqheight()


Regards,

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


is there an easy way to parse a nested list ?

2009-03-15 Thread Stef Mientki

hello,

I need to parse a nested list, given as a string, like this

line = " A  [  B  [ C+2 ] + 3 ] "

( I probably can do it with find, but I guess that's not the most 
elegant way, besides recusrion is not my strongest point)


which should be parsed so I get an list from inner to outer side (don't 
know if these are the correct words),

but I should like to have a list or tuple for tis case:

parsed = [ C+2,  B[C+2]+3,   A  [  B  [ C+2 ] + 3 ] ]
  or (last term is not needed, as well as the constants aren't)
parsed = [ C,  B[C+2] ]

this all, to improve the improved error / exception message even more ;-)

thanks,
Stef




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


Re: how to repeat function definitions less

2009-03-15 Thread MRAB

alex goretoy wrote:
ok now for the final result, i decided to split options out to a 
separate dict of lists, does this look right to every one, I currently 
have error somewhere else in my code so can't test this right now, Is 
this a good method to do this? or is there another option?



[snip]
First of all, *don't use "is" and "is not" to test for equality*; use 
"==" and "!=".


When you split the options out like that you get duplication.

You have, for example:

...
"colors": ["c", "cl", "col", ...]
...

and:

...
"imp_colors": ["c", "cl", "col", ...]
...

Couldn't you put them into one dict, something like:

   ...
   "colors": ("imp_colors", ["c", "cl", "col", ...])
   ...

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


Re: Correct URL encoding

2009-03-15 Thread Graham Breed

mattia wrote:
I'm using urlopen in order to download some web pages. I've always to 
replace some characters that are in the url, so I've come up with:

url.replace("|", "%7C").replace("/", "%2F").replace(" ", "+").replace
(":", "%3A")
There isn't a better way of doing this?


Yeah, shame there's no function -- called "urlencode" say -- 
that does it all for you.



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


[ANN] pxyser --- python xml serialization (beta release 0.1).

2009-03-15 Thread Daniel Molina Wegener
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA512


pxyser --- python xml serialization (beta release 0.1).

pyxser is a C written extension that serializes/deserializes
python objects in XML format. It uses a DTD to create a valid
XML tree under UTF-8 encoding.

the project web page is at:
http://projects.coder.cl/pyxser/

the project repository and download:
https://sourceforge.net/projects/pyxser/

to install, just get the tarball and:

tar xzvf pyxser-1.0-beta.tar.gz
cd pyxser
python ./setup.py build --force
python ./setup.py install

best regards,
- -- 
 .O. | Daniel Molina Wegener   | FreeBSD & Linux
 ..O | dmw [at] coder [dot] cl | Open Standards
 OOO | http://coder.cl/| FOSS Developer

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (FreeBSD)

iQIcBAEBCgAGBQJJvY/WAAoJEHxqfq6Y4O5NMbIP/jiA/j/a6i8ofypV2MGhzK/U
jnWHoYvQ/jelb1Ew5nQWvBFAwoiX4ECq14I5G0dD0D3z3K4LtXItyk1yf8LqltD3
3ORfL9MqNMtTVfi/rm3nxHWiPAZIm/U+dCMLxPMnr2yOh84Wouv1xMeepqwbCMh5
vg6rbPwGjy3vM8PytPsY7A03iMbCCnNsv4fhQ58w0mLHbiTpOMqz81f6RO7/fQ1B
yMmuEnjx5dRfEHXwnPV24k5tgKwCo733la9+dpjQZS/nH7b/csCebt0pZ/gogjyz
XS6VuFo7ZfOXL+bfXSBeiun92cFRTdY2n8UD2Sc66muBf7uxOkrqanKrasR2RZZ3
hzCbFzB1TWaFJvbUcn5KCCuagqQOTR+ALu6fGZ1g1PEUQT/D7cVbpK1qx4fasnsM
loUqheol7XoJ1G+AwiDwydsBF9zxasDnUN9dj+S/OJZdL1Fynf72Zz9DA7QYFqg5
6Mum8zXzcaZ2lNDOZ7bmdiXqDDHZW67YH1jDESpDOSmdcYTtsI5dVU8cG88a3+Xi
UCwB3LCL0LLgELZzE1xGH/4h/kal7Y4n8xifGz2lqXFxyCT56zyxuRIm/lS0/I2r
bpRdu6rvxQcSntaikWDtp2J3h7sKN3OTD7NKPJZnHlH9joaGncMHPP0Ybnh+hIIg
NKReaefYPORclpWs50UD
=jCSj
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: can error messages be improved or can they be overridden ?

2009-03-15 Thread andrew cooke
rdmur...@bitdance.com wrote:
> "andrew cooke"  wrote:
>> rdmur...@bitdance.com wrote:
>> [...]
>> > (You know, I really ought to revisit that routine and make it part
>> > of my standard development toolbox.)
>>
>> please post it
>
> OK.  I dug it up, cut out the stuff that was specific to the application,

i just saw this!  thanks!

andrew

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


Re: Style question - defining immutable class data members

2009-03-15 Thread Aaron Brady
On Mar 15, 1:50 pm, "Rhodri James" 
wrote:
> On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady   
> wrote:
>
> > On Mar 15, 12:39 pm, John Posner  wrote:
> >> (My apologies if the thread has already covered this.) I believe I  
> >> understand the WHAT in this situation, but I don't understand the WHY  
> >> ...
>
> [snip]
>
>
>
> >> My question is ... WHY does the interpreter silently create the  
> >> instance attribute at this point, causing a "surprising decoupling"  
> >> from the class attribute? WHY doesn't the interpreter behave as it  
> >> would with a simple, non-instance variable:
>
> >>   > python
> >>   Python 2.6.1 ...
> >>   Type "help", "copyright", "credits" or "license" for more information.
>
> >>   >>> x += 1
> >>   Traceback (most recent call last):
> >>     File "", line 1, in 
> >>   NameError: name 'x' is not defined
>
> >> Is there a beneficial effect of silently creating the instance  
> >> attribute, which outweighs the detrimental effects: (1) inconsistency,  
> >> (2) the "surprising" decoupling?
>
> > Yes.  If you access an attribute, you want the search to go like this:
>
> > - check instance for attribute
> > - check class for attribute
> > - check base classes for attribute
>
> But do you, though?  The only occasion I can think of that I'd want
> the search to go past the instance is this "auto-initialisation",
> and frankly I'd rather do that in an __init__ anyway.  Perhaps
> static methods or class methods work that way, I don't know how
> the innards of the interpreter handle that.

As Bruno stated, yes, for resolving 'self.method', and other
descriptors.  You acknowledge that 'foo.jam' would need to identify
itself as coming from an instance, class, or base, since the only
entries in 'foo's dictionary are those attributes which are particular
to 'foo'.  Others, such as the entries in 'foo's class, are stored in
a different dictionary.  Changes to that class's dictionary are
visible to all 'foo' instances (as desired), as well that as 'foo'
isn't clogged by copies of entries for all of its class's functions.

Class attributes are grouped together in the class dictionary,
instance attributes are grouped together in the instance dictionary,
and instances need to see both.

If you have a counter-proposal, either for a wishlist for behavior, or
a way of arranging its implementation, I for one would entertain it,
even on the c-l-python newsgroup, and even though it wouldn't have
much of a chance of making it in to Python.

As a side note, this argument of 'whose methods am I seeing?' has an
inconvenient artifact: the behavior of 'foo.method'.  'foo.method'
needs to refer to an instance method, due to not needing the 'self'
attribute respecified; while 'foo.__class__.method' needs to refer to
a plain function.  Python's solution is a skeleton type, that just
redirects 'foo.method( )' to an append of the arguments plus call.

> Is there any actual advantage to self.attribute picking up
> Class.attribute instead of raising a NameError?
>
> > If you write an attribute, you want it stored in the attribute, not
>
>                                                         ^
>
> > the class or base classes.
>
> I think you meant "instance" there :-)

Syntax error line 4!  Gasp!  All hands to battle stations.

> Actually what I want is for
> the attribute to be stored where I told it, which could well be in
> the class.  If the attribute is specified as "self.attribute", then
> yes, put it in the instance.

The way C++ works is by allocating storage for the data and method
pointers in a class.

class X {
int foo;
char jam[ 12 ];
int foojam( int y, int z ) { ...; }
};

X requires 20 bytes: 4 for 'foo', 12 for 'jam', and 4 for 'foojam'...
under a 32-bit target.  (The 4 for 'foojam' come from a virtual
function table, for polymorphic objects er, technically.)

Python can't and won't do that, because you want attributes to be able
to join instances over time.

You get what you want: attributes are stored where you tell them.  But
where are they read from?

>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses

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


Re: Correct URL encoding

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 4:21 PM, mattia  wrote:
> I'm using urlopen in order to download some web pages. I've always to
> replace some characters that are in the url, so I've come up with:
> url.replace("|", "%7C").replace("/", "%2F").replace(" ", "+").replace
> (":", "%3A")
> There isn't a better way of doing this?

I believe you're looking for the aptly-named urlencode() function:
http://docs.python.org/library/urllib.html#urllib.urlencode

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 4:17 PM, Steve Holden  wrote:
> Roy Smith wrote:
>> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk
>> wrote:
>>
>>> I have a date in the form of a datetime object and I want to add (for
>>> example) three months to it.  At the moment I can't see any very
>>> obvious way of doing this.  I need something like:-
>>>
>>>     myDate = datetime.date.today()
>>>     inc = datetime.timedelta(months=3)
>>>     myDate += inc
>>>
>>> but, of course, timedelta doesn't know about months. I had a look at
>>> the calendar object but that didn't seem to help much.
>>
>> Well, before you can "add three months" to something, you need to explain
>> what that means.
>>
>> What is Nov 29th plus 3 months?
>>
>> What is Jan 31st plus 3 months?
>>
>> Months are different lengths.  Asking to "add 3 months" is kind of like
>> asking, "If I'm somewhere in the continental US (east of the Mississippi
>> River) and move three states to the west, how many miles have I moved?"
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> OK, suppose I sign a contract on Nov 30 that requires me to make
> quarterly payments. When is my next payment due?
>
> The use case doesn't seem that unreasonable to me.

Indeed, but the point is that there are likewise reasonable usecases
for the other behaviors too and one should refuse to guess in the face
of ambiguity; the std lib has, merely by default in this case, taken
this to the extreme of not implementing any of them directly.

Somewhat unrelated wish: if only dateutil were in the std lib... Alas!

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Correct URL encoding

2009-03-15 Thread mattia
I'm using urlopen in order to download some web pages. I've always to 
replace some characters that are in the url, so I've come up with:
url.replace("|", "%7C").replace("/", "%2F").replace(" ", "+").replace
(":", "%3A")
There isn't a better way of doing this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Steve Holden
Roy Smith wrote:
> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk 
> wrote:
> 
>> I have a date in the form of a datetime object and I want to add (for
>> example) three months to it.  At the moment I can't see any very
>> obvious way of doing this.  I need something like:-
>>
>> myDate = datetime.date.today()
>> inc = datetime.timedelta(months=3)
>> myDate += inc
>>
>> but, of course, timedelta doesn't know about months. I had a look at
>> the calendar object but that didn't seem to help much.
> 
> Well, before you can "add three months" to something, you need to explain 
> what that means.
> 
> What is Nov 29th plus 3 months?
> 
> What is Jan 31st plus 3 months?
> 
> Months are different lengths.  Asking to "add 3 months" is kind of like 
> asking, "If I'm somewhere in the continental US (east of the Mississippi 
> River) and move three states to the west, how many miles have I moved?"
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
OK, suppose I sign a contract on Nov 30 that requires me to make
quarterly payments. When is my next payment due?

The use case doesn't seem that unreasonable to me.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/

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


Re: can error messages be improved or can they be overridden ?

2009-03-15 Thread Stef Mientki

thanks RDM,
I finally had a case where I really needed it,
so it tried,
works perfect,
except the marked lines should be indented 1 more.
cheers,
Stef

rdmur...@bitdance.com wrote:

"andrew cooke"  wrote:
  

rdmur...@bitdance.com wrote:
[...]


(You know, I really ought to revisit that routine and make it part
of my standard development toolbox.)
  

please post it



OK.  I dug it up, cut out the stuff that was specific to the application,
freshened it up a little, and added a little demo.  I don't claim this
is the best possible way to do this (it certainly could be made smarter,
possibly by using python facilities to actually parse the line; right
now it takes a very brute force approach to trying to find variables),
but it served my purposes and perhaps it will help others.

Oh, yeah, and I just added the globals bit without thoroughly testing
it...I think it probably doesn't help much and may be misleading when
the traceback is thrown in an imported module.

Enjoy.

--RDM

--
from traceback import format_tb, format_exception_only
from sys import exc_info
from re import compile
varsplitter = compile("[^0-9a-zA-Z_]")

def format_exception():
"""
Add a dump of any variables we can identify from the failing program
line to the end of the traceback.  The deep mojo for doing this came
from an example in the Zope core plus documentation in the Python
Quick Reference.
"""
etype, value, tb = exc_info()
plaintb = format_tb(tb)
result=['Traceback (innermost last):']
for line in plaintb:
result.append(line)
f = tb.tb_frame
tb = tb.tb_next
  


* locals=f.f_locals
* vars = varsplitter.split(line.split('\n')[-2])
* dvars = set()
* self = None
* if 'self' in locals: self = locals['self']
* for v in vars:
* if v in dvars: continue
* dvars.add(v)
* if v in locals:
* result.append(' %s: %r\n' % (v,locals[v]))
* if self and hasattr(self, v):
* result.append(' self.%s: %r\n' % (v,getattr(self, v)))
* if v in globals():
* result.append(' (global) %s: %r\n' % (v,globals()[v]))

result.extend(format_exception_only(etype, value))
return ''.join(result)


class Demo:
y = 200
def __init__(self, x):
self.x = x

def bad(self):
x = [1, 2]
y = (5, 9, 9)
y[1] = x[2] + foo

foo = 'a value'

def main():
bar = Demo('some value')
bar.bad()

  
if __name__=='__main__':

try: main()
except Exception:
print format_exception()

--
rdmur...@maestro:~>python tb.py
Traceback (innermost last):  File "tb.py", line 56, in 
try: main()
  File "tb.py", line 52, in main
bar.bad()
  File "tb.py", line 46, in bad
y[1] = x[2] + foo
  y: (5, 9, 9)
  self.y: 200
  x: [1, 2]
  self.x: 'some value'
  (global) foo: 'a value'
IndexError: list index out of range
--

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


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


Re: Style question - defining immutable class data members

2009-03-15 Thread John Posner

Matthew Woodcraft said:

> I doubt it's because anyone particularly wanted this
> behaviour; it just
> falls out of the way '+=' is defined.
> 
> At the point where 'inst.x += 1' is compiled,
> Python doesn't know
> whether 'inst.x' is going to turn out to be a class
> attribute or an
> instance attribute or a property. So really the only thing
> it can do is
> generate code to read inst.x in the usual way and then
> assign to inst.x
> in the usual way (where 'the usual way' for CPython
> is LOAD_ATTR and
> STORE_ATTR).

That sounds reasonable to me.


Matthew Woodcraft also said:

>> Is there any actual advantage to self.attribute picking up
>> Class.attribute instead of raising a NameError?

> You use that any time you call an ordinary method using syntax like
> 'self.foo()'.

Yes, but that's performing a read (and call) operation on an attribute. My 
question concerned itself with potential confusion when you perform a write 
operation on an attribute.


Bruno Desthuilliers said:

>> My question is ... WHY does the interpreter  silently create the
>> instance attribute at this point,

> Becaause that's how you create instance attributes in Python. Why do you
> think 'self' - that is, a reference to some object - is mandatory in
> "methods" (really, functions) arguments list ?

> Or do you mean that the existence of a synonym class attribute should be
> checked on each instance variable assignement ? This would probably be a
> big performance hit, ...

Yes, Bruno, I'm persuaded by this argument. Ideally, I'd like the interpreter 
to prevent the programmer from shooting him/herself in the foot, but it's not 
worth the performance hit.

> and it would make per-instance method overloading
> impossible (remember that OOP is about objects, not classes).

Yes again. While I was writing the above comment ("write operation on an 
attribute"), it *did* cross my mind that you might want to write 
self.attribute, even if it names a method, not a data-item.


Summary: I no longer suspect that "Python is broken". I *do* think that there's 
a situation that is potentially quite confusing:

 * In the statement "self.x = self.x + 1", the two "self.x" names can sometimes 
refer to different objects.

 * Even worse, in the equivalent statement "self.x += 1", the single name 
"self.x" can sometimes refer to two different objects!

I think this situation should be handled in documentation. (I'm a tech writer 
in my day job ... oh wait, I forgot ... I got laid off from my day job in 
December.) I'll look into what the standard Python doc set says on this matter.

-John

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


Re: Get pixel colors from images in Python 3

2009-03-15 Thread Tim Roberts
Cro  wrote:
>
>As the title sais, i am trying to extract pixel colors from images, in
>Python 3.
>...
>Can anyone suggest how to do that ?
>The bigger problem is that i need to extract pixel colors for many
>types of images : JPEG, PNG, BMP, GIF. For this, i might need
>different codecs... I am not good at image formats and codecs.
>
>I just want to know if i can do this in the simple way, or i have to
>beg PIL to implement support for Python 3...

There is no simple way, short of using PIL.  You cannot begin to imagine
the complexity involved in handling all of the strange variations on JPEG,
PNG, and GIF.  You REALLY do not want to try to reimplement all of that.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWin32 for Python 3.x

2009-03-15 Thread Mark Hammond

On 16/03/2009 6:05 AM, John Nagle wrote:

Tim Golden wrote:

John Nagle wrote:

Any idea when PyWin32 will be available for Python 3.x?

John Nagle


Release 213 is out already:

http://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063&release_id=661475


I think it's still considered a little bit beta. There have been a *lot*
of changes involved.


That "wizard" won't even install unless Python 3.0 is "in the
registry", which apparently means "installed as the default Python".
After giving the user an alert box, it dumps you into a dialog which
says "Python 3.0 is required for this package. Select installation to use".
That's blank, and the form fields "Python Directory" and "Installation
Directory" won't accept input, so it can't even be overridden manually.

Lame.


This would be exactly the same for any version of Python; while the 
distutils create UI does suck, the problem has nothing to do with Python 
3.0.


I'm guessing you built it from source?  If so, and as with every version 
of Python, you really just need the 'InstallPath' set appropriately, but 
probably also want the PythonPath to be setup like other versions.


Cheers,

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


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
ok now for the final result, i decided to split options out to a separate
dict of lists, does this look right to every one, I currently have error
somewhere else in my code so can't test this right now, Is this a good
method to do this? or is there another option?

self.opt={}
self.opt['arg_opts_options']={
"imp_src":['ss',"src","source","sources"],
"imp_mod":['m',"mod",'mods',"module","modules"],
"imp_opt":['o',"oo","opt",'opts',"option","options"],
"imp_set":['s','ss',"sss","set","setting","settings"],

"imp_files":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"imp_flavors":["fff","flav","flavor","flavors"],

"imp_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"imp_downloads":["d",'df',"down",'down_file','down_files',"download",

"downloads",'download_file','download_files'],

"imp_colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"imp_properties":["p","prop","property","properties"]
}
self.opt['arg_opts']={
"site_name":["s","sn","site",'sites','site_name','site_names'],
"jar_name":["j","jn","jar",'jars','jar_name','jar_names'],

"file_name":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"verbose":["v","vv","vvv",'verbose','verbosity'],
"flavors":["fff","flav","flavor","flavors"],

"final_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"download_files":["d",'df',"down",'down_file','down_files',"download",
"downloads",'download_file','download_files'],

"colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"options":['o','opt','option',"options"],
"properties":["p","prop","property","properties"]
}

def main(self):
def _set_arg(a,b):
for k,v in self.opt['arg_opts']:

if a in v:
if a in ["colors","flavors",'final_funcs']:
if b is not "":
_b=b.split(',')
for c in range(len(_b)):
_c=_b[c].split(":")
if _c[1] is not "":
setattr(self,
opt['properties']['flavors'][_c[0]], _c[1])
self.soc.debug("%s"%("args "+k+":
",self.opt['properties'][k]))
elif a is "download_files":
if b is not "":
if bool(b):
print ("\nDOWNLOAD FILES",b)
self.opt['properties']['settings'][a] = 1
self.soc.debug( "%s"%("args "+a+":
",self.opt['properties']['settings'][a]) )
if b.find("://") > -1:
_b=b.split(";")
if _b[1] is not "":

self.opt['properties']['file_downloads'][_b[0]]=_b[1]
self.soc.debug( "%s"%("args
file_downloads: ",self.opt['properties']['file_downloads'][_b[0]]) )
elif a is "options":
_b=b.split(",")
for c in range(len(_b)):
_c=_b[c].split(':')
for i,j in self.opt['arg_opts_options']:
if _c[0] in j:
if _c[1] is not "":
self.opt['properties'][j] = _c[1]
self.soc.debug( "%s"%("args imp_src:
",self.opt['properties']['imp_src']) )
else:
if b is not "":
setattr(self, opt['properties'][a], b)
self.soc.debug("%s"%("args "+k+":
",self.opt['properties'][k]))


for _argsi in range(len("".join(self.args).split('='))-1):
_args=self.args[_argsi].split("=")
print ("printing A:",_args)
_set_arg(_arg[0],_arg[1])
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 3:56 PM, alex goretoy
wrote:

> this is the final result of the args i will be parsing for now
>
> d={
> "site_name":["s","sn","site",'sites','site_name','site_names'],
> "jar_name":["j","jn","jar",'jars','jar_name','jar_names'],
>
> "file_name":["f","fn",'file','files','filename','filenames','file_name','file_names'],
> "verbose":["v","vv","vvv",'verbose','verbosity'],
> "flavors":["fff","flav","flavor","flavors"],
>
> "final_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",
>
> 'final_functs',"final_function","final_functions"],
>
> "download_files":["d",'df',"down"

Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Machin
On Mar 16, 6:55 am, John Yeung  wrote:
> On Mar 15, 3:10 pm, Casey Webster  wrote:
>
> > The example you give does have fairly obvious logic. But how does it
> > handle Feb 28th, 2009 + 3 months?  To me, there are two "obvious"
> > answers: May 28th, 2009 or May 31st, 2009.  The question is intent; is
> > Feb 28th an arbitrary day of the month, or is it the last day of the
> > month, which for something like a monthly bill reminder is more likely?
>
> In my experience, unless there is explicit verbiage that says "last
> day of the month", the day of the month is always retained except
> where it would result in an invalid date.  (So May 28 in your
> example.)
>
> I sympathize with anyone who considers "lay person date math" ugly and
> not always logical, in a mathematician's sense of logic.  But the fact
> of the matter is that LPDM is quite well established and not very
> ambiguous at all.

A couple of issues here:

(1) The number of days in a month is not a constant, so "a
mathematician's sense of logic" is quite irrelevant.

(2) The various *different* LPDMs are quite well established and each
of them can be reduced to non-ambiguous rules provided that the
reducer is patient and persistent and avoids terms like "ugly",
"illogical", "ludicrous" ... early stages of the reduction process can
produce things like "31 January plus 1 month -> 3 March (2 March in a
leap year)" :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Machin
On Mar 16, 7:30 am, Roy Smith  wrote:
> In article ,
>  Chris Rebert  wrote:
>
> > Which makes some sense considering a month can range from 28-31 days,
> > which would make the delta oddly fuzzy.
>
> BTW, what date is "One month after August 10, 1752"?  Extra points if you
> refuse the answer the question on the grounds that it's incompletely
> specified :-)

Yup, which calendar, what religion do you follow, where are you (and
if the answer is Sweden, which parish (according to legend)).
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread CM
On Mar 15, 1:28 pm, tinn...@isbd.co.uk wrote:
> I have a date in the form of a datetime object and I want to add (for
> example) three months to it.  At the moment I can't see any very
> obvious way of doing this.  I need something like:-
>
>     myDate = datetime.date.today()
>     inc = datetime.timedelta(months=3)
>     myDate += inc
>
> but, of course, timedelta doesn't know about months. I had a look at
> the calendar object but that didn't seem to help much.
>
> --
> Chris Green

As someone pointed out, dateutil to the rescue:

>>> import datetime
>>> from dateutil.relativedelta import *

>>> now = datetime.date.today()
>>> now
datetime.date(2009, 3, 15)

>>> now+relativedelta(months=+3)
datetime.date(2009, 6, 15)

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Roy Smith
In article ,
 Chris Rebert  wrote:

> Not that that date could even be represented by most programs since
> it's before 1970. Talk about recentism! :-)
> I've always wondered how historians using computers deal with that 
> limitation...

The unix time format it well known for being extremely limited both in 
terms of extent and precision.  Julian Date 
(http://en.wikipedia.org/wiki/Julian_date) is a commonly used time scale 
for working with events far into the past or future.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread R. David Murray
M R A Barnett  wrote:
> Aaron Brady wrote:
> [snip]
> > However, in my (opined) interpretation, 'list.append(...) is an in-
> > place operation' is a factual error.  In-place operations -also-
> > rebind their 'argument' (FLOBW for lack of better words).  'append' is
> > a by-side-effect operation.  However colloquially it's mostly
> > accurate.
> > 
> [snip]
> All the augmented assignments rebind, even for objects which support
> in-place operations. For example:
> 
>  my_list = []
>  my_list += [0]
> 
> rebinds, but the equivalent:
>
>  my_list = []
>  my_list.extend([0])
> 
> doesn't.

Lest someone be mislead by this discussion, how about an example:

>>> a = b = []
>>> a.extend([1])
>>> a
[1]
>>> b
[1]
>>> a += [3]
>>> a
[1, 3]
>>> b
[1, 3]
>>> a = a + [5]
>>> a
[1, 3, 5]
>>> b
[1, 3]

It is technically correct that '+=' bebinds 'a', but what it
rebinds it to is the same object that was just mutated.  Unlike
the '+' case where 'a' is bound to a newly created list object.

Personally I think += and kin were a bad idea and should have been
removed in Python 3.0 :)  Even though I occasionally use them.  (Maybe
I'll stop.)

> Augmented assignments which don't support in-place operations behave
> like normal assignments (binding). For example:
> 
>  my_int = 0
>  my_int += 1
> 
> behaves like:
> 
>  my_int = 0
>  my_int = my_int + 1

--
R. David Murray   http://www.bitdance.com

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


Re: ipython / vs \ in readline on MS Windows (and ipython help grepper)

2009-03-15 Thread Tim Roberts
Jason Scheirer  wrote:
>
>Cygwin does not magically change the platform you are on, the fact
>that you are on Windows is hard-coded into the Python.exe binary. Look
>for references to os.path.sep in IPython. Windows does let you use
>forward slashes as path separators, though, so I am not entirely sure
>what your issue is.

His problem is more or less the opposite of what you just said.  IPython
doesn't know anything about Cygwin, so when its file name completion does
its work, it creates command lines like
ls c:\windows\system32\qqq.dll
but Cygwin parses that like a Unix command line, resulting in
ls c:windowsystem32qqq.dll
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Bruno Desthuilliers

John Posner a écrit :

(My apologies if the thread has already covered this.) I believe I
understand the WHAT in this situation, but I don't understand the WHY
...

Given this class definition:

class Cls(object): x = 345

... I observe the following, using IDLE 2.6.1:


inst = Cls() Cls.x is inst.x

True


Cls.x += 1 Cls.x is inst.x

True


inst.x += 1 Cls.x is inst.x

False

My question is ... WHY does the interpreter  silently create the
instance attribute at this point,


Becaause that's how you create instance attributes in Python. Why do you 
think 'self' - that is, a reference to some object - is mandatory in 
"methods" (really, functions) arguments list ?


Or do you mean that the existence of a synonym class attribute should be 
checked on each instance variable assignement ? This would probably be a 
big performance hit, and it would make per-instance method overloading 
impossible (remember that OOP is about objects, not classes).


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


Re: Style question - defining immutable class data members

2009-03-15 Thread Matthew Woodcraft
"Rhodri James"  writes:

> But do you, though?  The only occasion I can think of that I'd want
> the search to go past the instance is this "auto-initialisation",
> and frankly I'd rather do that in an __init__ anyway.  Perhaps
> static methods or class methods work that way, I don't know how
> the innards of the interpreter handle that.
>
> Is there any actual advantage to self.attribute picking up
> Class.attribute instead of raising a NameError?

You use that any time you call an ordinary method using syntax like
'self.foo()'.

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


Re: Style question - defining immutable class data members

2009-03-15 Thread Bruno Desthuilliers

Rhodri James a écrit :
On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady  
wrote:



On Mar 15, 12:39 pm, John Posner  wrote:

(snip)

Is there a beneficial effect of silently creating the instance 
attribute, which outweighs the detrimental effects: (1) 
inconsistency, (2) the "surprising" decoupling?


Yes.  If you access an attribute, you want the search to go like this:

- check instance for attribute
- check class for attribute
- check base classes for attribute


But do you, though?  The only occasion I can think of that I'd want
the search to go past the instance is this "auto-initialisation",


How would you resolve inst.method, then ?


and frankly I'd rather do that in an __init__ anyway.  Perhaps
static methods or class methods work that way, I don't know how
the innards of the interpreter handle that.

Is there any actual advantage to self.attribute picking up
Class.attribute instead of raising a NameError?


Yes: resolving methods and other descriptors.

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


Re: Style question - defining immutable class data members

2009-03-15 Thread Matthew Woodcraft
John Posner  writes:

> My question is ... WHY does the interpreter silently create the
> instance attribute at this point, causing a "surprising decoupling"
> from the class attribute? WHY doesn't the interpreter behave as it
> would with a simple, non-instance variable:

>   > python
>   Python 2.6.1 ...
>   Type "help", "copyright", "credits" or "license" for more information.
>
>   >>> x += 1
>   Traceback (most recent call last):
> File "", line 1, in 
>   NameError: name 'x' is not defined

> Is there a beneficial effect of silently creating the instance
> attribute, which outweighs the detrimental effects: (1) inconsistency,
> (2) the "surprising" decoupling?

I doubt it's because anyone particularly wanted this behaviour; it just
falls out of the way '+=' is defined.

At the point where 'inst.x += 1' is compiled, Python doesn't know
whether 'inst.x' is going to turn out to be a class attribute or an
instance attribute or a property. So really the only thing it can do is
generate code to read inst.x in the usual way and then assign to inst.x
in the usual way (where 'the usual way' for CPython is LOAD_ATTR and
STORE_ATTR).

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


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this is the final result of the args i will be parsing for now

d={
"site_name":["s","sn","site",'sites','site_name','site_names'],
"jar_name":["j","jn","jar",'jars','jar_name','jar_names'],

"file_name":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"verbose":["v","vv","vvv",'verbose','verbosity'],
"flavors":["fff","flav","flavor","flavors"],

"final_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"download_files":["d",'df',"down",'down_file','down_files',"download",
"downloads",'download_file','download_files'],

"colors":["c","cl","col","colo","color","colors",'reaper','reapers'],
"options":{
"imp_src":['ss',"src","source","sources"],
"imp_mod":['m',"mod",'mods',"module","modules"],

"imp_opt":['o',"oo","opt",'opts',"option","options"],

"imp_set":['s','ss',"sss","set","setting","settings"],

"imp_files":["f","fn",'file','files','filename','filenames','file_name','file_names'],
"imp_flavors":["fff","flav","flavor","flavors"],

"imp_funcs":["ff","finfun",'fin_fun',"final_func",'final_funct',"final_funcs",

'final_functs',"final_function","final_functions"],

"imp_downloads":["d",'df',"down",'down_file','down_files',"download",

"downloads",'download_file','download_files'],

"imp_colors":["c","cl","col","colo","color","colors",'reaper','reapers'],

"imp_properties":["p","prop","property","properties"]

},
"properties":["p","prop","property","properties"]
}

pynutbutter will be really good soon, thx for your help :) I'm glad to be
doing this in python

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 3:30 PM, alex goretoy
wrote:

> Michele I tried your way but I dont seem to have a good grasp on the
> concept yet, will read up more
>
> for now I think I will try to make it work same way as colors only with
> decorator as def inside def instead of @, that doesn't make sense quite yet
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 3:12 PM, alex goretoy  > wrote:
>
>> this is what I did to define all my color functions by color name, but I
>> am still going to need a good solution for args
>>
>> #import functions by color name into current namespace
>>> for color in self.colors.keys():
>>> setattr(self, color,lambda x,y=color,z="INFO":
>>> self._hero(x,y,z) )
>>>
>>
>> Thanks to all of you for helping me learn python
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> this means i have to check if d[i] is list or dict and iterate over
>>> properties
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy <
>>> aleksandr.gore...@gmail.com> wrote:
>>>
 I will also actually need to nest it like so

 d={
"site_name":["s","site",'
>
> sites','site_name','site_names'],
>"jar_name":["j","jar",'jars','jar_name','jar_names'],

 "options":{
 "src_name":["ss","src","source"],
 "mod_name":['m',"mod",'mods',"module","modules"],
 }

 -Alex Goretoy
 http://www.goretoy.com



 On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:

> d={
>>"site_name":["s","site",'sites','site_name','site_names'],
>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>
>

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


Re: PyPy Progress (and Psyco)

2009-03-15 Thread andrew cooke
Fuzzyman wrote:
> On Mar 15, 3:46 pm, Gerhard Häring  wrote:
[...]
>> Me too. I doubt it, though. From an outside view, the project seems to
>> lack focus. To me, it looks like a research platform, and producing a
>> successor to CPython seems to be just one out of a dozen projects.
[...]
> Well, I know the guys involved and they are focused on making PyPy a
> practical (and importantly a faster) alternative to CPython. It has
> just taken a long time - but is finally showing real progress.
>
> They did get distracted along the way, but one of things that happened
> last year was a culling of a lot of the side projects that made it
> harder to make progress on the core goals.

This is so good to hear.  I had exactly the same concerns as Gerhard. 
Thanks for posting some information.

Andrew

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


Re: Set overlapping

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 1:41 PM, mattia  wrote:
> How can I determine the common values found in two differents sets and
> then assign this values?
> E.g.
> dayset = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
> monthset = ["Jan", "Feb", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
> "Oct", "Nov", "Dec"]
> this are the "fixed and standard" sets.
> Then I have others sets that contains one value from the previous sets
> (one for each).
> exset1 = ["SS" ,"33" ,"err" ,"val" ,"Tue" ,"XYZ" ,"40444" ,"Jan" ,"2008"]
> exset2 = ["53" ,"hello" ,"YY" ,"43" ,"2009" ,"Sun" ,"Feb"]
> I want to find:
> day_guess1 = value in dayset that is in exset1
> day_guess2 = value in dayset that is in exset2
> the same with monthset
> For now, I've got:
> for d in dayset:
>    if d in exset1:
>        guess_day = d
>        break
> Is there something better?

Use Python's actual `set` type. You're looking for the 'intersection' operation:

dayset = set(("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
exset1 = set(("SS" ,"33" ,"err" ,"val" ,"Tue" ,"XYZ" ,"40444" ,"Jan" ,"2008"))
exset2 = set(("53" ,"hello" ,"YY" ,"43" ,"2009" ,"Sun" ,"Feb"))
print dayset & exset1 #=> set(['Tue'])
the_value = (dayset & exset1).pop()
print dayset & exset2 #=> set(['Sun'])
other_value = (dayset & exset2).pop()
print the_value, other_value #=> Tue Sun

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 1:30 PM, Roy Smith  wrote:
> In article ,
>  Chris Rebert  wrote:
>
>> Which makes some sense considering a month can range from 28-31 days,
>> which would make the delta oddly fuzzy.
>
> BTW, what date is "One month after August 10, 1752"?  Extra points if you
> refuse the answer the question on the grounds that it's incompletely
> specified :-)

Not that that date could even be represented by most programs since
it's before 1970. Talk about recentism! :-)
I've always wondered how historians using computers deal with that limitation...

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Set overlapping

2009-03-15 Thread mattia
How can I determine the common values found in two differents sets and 
then assign this values? 
E.g.
dayset = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
monthset = ["Jan", "Feb", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
"Oct", "Nov", "Dec"]
this are the "fixed and standard" sets.
Then I have others sets that contains one value from the previous sets 
(one for each).
exset1 = ["SS" ,"33" ,"err" ,"val" ,"Tue" ,"XYZ" ,"40444" ,"Jan" ,"2008"]
exset2 = ["53" ,"hello" ,"YY" ,"43" ,"2009" ,"Sun" ,"Feb"]
I want to find:
day_guess1 = value in dayset that is in exset1
day_guess2 = value in dayset that is in exset2
the same with monthset
For now, I've got:
for d in dayset:
if d in exset1:
guess_day = d
break
Is there something better?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Roy Smith
In article ,
 Chris Rebert  wrote:

> Which makes some sense considering a month can range from 28-31 days,
> which would make the delta oddly fuzzy.

BTW, what date is "One month after August 10, 1752"?  Extra points if you 
refuse the answer the question on the grounds that it's incompletely 
specified :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
Michele I tried your way but I dont seem to have a good grasp on the concept
yet, will read up more

for now I think I will try to make it work same way as colors only with
decorator as def inside def instead of @, that doesn't make sense quite yet

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 3:12 PM, alex goretoy
wrote:

> this is what I did to define all my color functions by color name, but I am
> still going to need a good solution for args
>
> #import functions by color name into current namespace
>> for color in self.colors.keys():
>> setattr(self, color,lambda x,y=color,z="INFO":
>> self._hero(x,y,z) )
>>
>
> Thanks to all of you for helping me learn python
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy  > wrote:
>
>> this means i have to check if d[i] is list or dict and iterate over
>> properties
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy <
>> aleksandr.gore...@gmail.com> wrote:
>>
>>> I will also actually need to nest it like so
>>>
>>> d={
>>>"site_name":["s","site",'

 sites','site_name','site_names'],
"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>
>>> "options":{
>>> "src_name":["ss","src","source"],
>>> "mod_name":['m',"mod",'mods',"module","modules"],
>>> }
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:
>>>
 d={
>"site_name":["s","site",'sites','site_name','site_names'],
>"jar_name":["j","jar",'jars','jar_name','jar_names'],


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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Roy Smith
In article ,
 Chris Rebert  wrote:

> Besides your behavior, one could equally well argue that a 31st repeat
> on months without a 31st should just be dropped, or that it should
> carry over onto the 1st of the next month (ignoring the complications
> of February). Which behavior one needs is completely
> context-dependent.

Indeed.  For example, my wife started her current job on a Feb 29th.  There 
are significant financial events that happen on various anniversaries of 
her employment (vesting of stock and retirement benefits).  It really is 
important that everybody know exactly what is meant by "10 years from Feb 
29th, on a given year", and what it means in one context may not mean what 
it means in another.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWin32 for Python 3.x

2009-03-15 Thread Tim Golden

John Nagle wrote:

   Well, of some other packages I use:

MySQLdb: "Python versions 2.3-2.5 are supported."
Ref: http://sourceforge.net/projects/mysql-python
M2Crypto: Latest version is for Python 2.6.
Ref: http://chandlerproject.org/bin/view/Projects/MeTooCrypto

Somebody who's into tracking might want to maintain a big cross-reference
table of "what packages work with what versions".



I'm inclined to agree. I remember some discussion about adding
a Wiki page for this, but searching quickly what I've come up
with is a suggestion in the Py3k/FAQ page:

 http://wiki.python.org/moin/Python3000/FAQ

which points towards a PyPI query listing packages which have
Python :: 3 tagged:

 http://pypi.python.org/pypi?:action=browse&c=533

It doesn't seem an entirely unreasonable approach. It falls
short of a researched / edited page (even a Wiki one) but
that would be a lot of work. I'm not sure how many Python
packages don't make into PyPI, nor am I sure how much effort
people take to categorise their packages appropriately. It
could well be the case that a number of packages will work
in Python 3.x without modification but their entry probably
won't reflect that unless their maintainer's gone to the
trouble to test the package and update it.

Obviously, in the case of (Windows) extension modules,
the module will at the very least need recompiling and
rebuilding even if the code works without modification.


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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Roy Smith
In article <49bd4252$0$512$bed64...@news.gradwell.net>, tinn...@isbd.co.uk 
wrote:
 
> > Well, before you can "add three months" to something, you need to explain 
> > what that means.
> [...]
> No, it's perfectly possible applying simple logic.

I didn't say it was not possible.  I just said that a precursor to doing it 
is understand what you mean by "add three months".  There is no universal 
definition for what that means.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWin32 for Python 3.x

2009-03-15 Thread John Nagle

Tim Golden wrote:

John Nagle wrote:

   That "wizard" won't even install unless Python 3.0 is "in the
registry", which apparently means "installed as the default Python".


No, it just means "installed somewhere". I have 6 different
versions of Python installed on this box. The choice of
which is "the default" is mine, either by selection at
installation or by later manipulation of associations,
path etc.



After giving the user an alert box, it dumps you into a dialog which
says "Python 3.0 is required for this package.  Select installation to 
use".

That's blank, and the form fields "Python Directory" and "Installation
Directory" won't accept input, so it can't even be overridden manually.


I agree that this is annoying.



While I don't feel strongly about the matter -- I have no particular
need to use Python 3.x for now, altho' I'm tracking it -- I think
that you're making quite a far-reaching statement on scant evidence. Fair
enough, you couldn't do a quick-and-dirty install of pywin32-213
for Python 3.x without having Python 3.x installed and in the
registry. To go from that to claiming that Python 3.x is a long
way from prime time seems at the very least to ignore the legions
of non-Windows users who neither know nor care about pywin32.


   Well, of some other packages I use:

MySQLdb: "Python versions 2.3-2.5 are supported."
Ref: http://sourceforge.net/projects/mysql-python
M2Crypto: Latest version is for Python 2.6.
Ref: http://chandlerproject.org/bin/view/Projects/MeTooCrypto

Somebody who's into tracking might want to maintain a big cross-reference
table of "what packages work with what versions".

John Nagle




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


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this is what I did to define all my color functions by color name, but I am
still going to need a good solution for args

#import functions by color name into current namespace
> for color in self.colors.keys():
> setattr(self, color,lambda x,y=color,z="INFO":
> self._hero(x,y,z) )
>

Thanks to all of you for helping me learn python

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:05 PM, alex goretoy
wrote:

> this means i have to check if d[i] is list or dict and iterate over
> properties
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy  > wrote:
>
>> I will also actually need to nest it like so
>>
>> d={
>>"site_name":["s","site",'
>>>
>>> sites','site_name','site_names'],
>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>
>> "options":{
>> "src_name":["ss","src","source"],
>> "mod_name":['m',"mod",'mods',"module","modules"],
>> }
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Sun, Mar 15, 2009 at 10:51 AM, MRAB wrote:
>>
>>> d={
"site_name":["s","site",'sites','site_name','site_names'],
"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


ANN: OpenOpt 0.23 - free numerical optimization framework

2009-03-15 Thread dmitrey
Hi all,
OpenOpt 0.23, a free numerical optimization framework (license: BSD)
with some own
solvers and connections to tens of 3rd party ones, has been released.

Our new homepage:
http://openopt.org

Introduction to the framework:
http://openopt.org/Foreword

All release details are here:
http://openopt.org/Changelog
or
http://forum.openopt.org/viewtopic.php?id=58

Special thanks to Stepan Hlushak for writing GLP (global) solver
"de" ("differential evolution").

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread John Yeung
On Mar 15, 3:10 pm, Casey Webster  wrote:
> The example you give does have fairly obvious logic. But how does it
> handle Feb 28th, 2009 + 3 months?  To me, there are two "obvious"
> answers: May 28th, 2009 or May 31st, 2009.  The question is intent; is
> Feb 28th an arbitrary day of the month, or is it the last day of the
> month, which for something like a monthly bill reminder is more likely?

In my experience, unless there is explicit verbiage that says "last
day of the month", the day of the month is always retained except
where it would result in an invalid date.  (So May 28 in your
example.)

I sympathize with anyone who considers "lay person date math" ugly and
not always logical, in a mathematician's sense of logic.  But the fact
of the matter is that LPDM is quite well established and not very
ambiguous at all.

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


Re: Is this type of forward referencing possible?

2009-03-15 Thread Kooks are people too
On Mar 15, 9:22 am, Miles  wrote:
>(I
> suspect the OP neglected to point out that A and B likely both inherit
> from db.Model).
> -Miles

yes, I did neglect to state that A and B inherit from db.Model.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Casey Webster
On Mar 15, 2:00 pm, tinn...@isbd.co.uk wrote:
> No, it's perfectly possible applying simple logic.  My reminder
> program manages it perfectly well.  I have, for example, two sets of
> three monthly reminders.
>
>     One starts on Jan 19th and repeats three monthly, that means Jan
>     19th, April 19th, July 19th and October 19th.  Very simple.
>
>     The other is a little more difficult, it starts on December 31st
>     and repeats three monthly.  So that one is on December 31st, March
>     31st, June 30th and September 30th.
>
> The calendar program manages it perfectly well using what seems to me
> fairly obvious logic, what I want is to be able to do the same in
> Python.

The example you give does have fairly obvious logic. But how does it
handle Feb 28th, 2009 + 3 months?  To me, there are two "obvious"
answers: May 28th, 2009 or May 31st, 2009.  The question is intent; is
Feb 28th an arbitrary day of the month, or is it the last day of the
month, which for something like a monthly bill reminder is more likely?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-15 Thread MRAB

Rhodri James wrote:
[snip]

Frankly, I'd much rather fix the locale system and extend
the format syntax to override the default locale.  Perhaps
something like

  financial = Locale(group_sep=",", grouping=[3])
  print("my number is {0:10n:financial}".format(1234567))

It's hard to think of a way of extending "%" format strings
to cope with this that won't look utterly horrid, though!


The problem with your example is that it magically looks for the locale
name "financial" in the current namespace. Perhaps the name should be
registered somewhere like this:

locale.predefined["financial"] = Locale(group_sep=",", grouping=[3])
print("my number is {0:10n:financial}".format(1234567))
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyPy Progress (and Psyco)

2009-03-15 Thread Fuzzyman
On Mar 15, 3:46 pm, Gerhard Häring  wrote:
> andrew cooke wrote:
> > This looks very promising -
> >http://www.voidspace.org.uk/python/weblog/arch_d7_2009_03_14.shtml#e1063
>
> > I am really looking forwards to PyPy having a final release.  I hope it
> > happens.
>
> Me too. I doubt it, though. From an outside view, the project seems to
> lack focus. To me, it looks like a research platform, and producing a
> successor to CPython seems to be just one out of a dozen projects.
>
> -- Gerhard

Well, I know the guys involved and they are focused on making PyPy a
practical (and importantly a faster) alternative to CPython. It has
just taken a long time - but is finally showing real progress.

They did get distracted along the way, but one of things that happened
last year was a culling of a lot of the side projects that made it
harder to make progress on the core goals.

At the moment PyPy is the best hope for a native implementation of
Python with an effective JIT.

Michael Foord
--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Rhodri James
On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady   
wrote:



On Mar 15, 12:39 pm, John Posner  wrote:
(My apologies if the thread has already covered this.) I believe I  
understand the WHAT in this situation, but I don't understand the WHY  
...


[snip]

My question is ... WHY does the interpreter silently create the  
instance attribute at this point, causing a "surprising decoupling"  
from the class attribute? WHY doesn't the interpreter behave as it  
would with a simple, non-instance variable:


  > python
  Python 2.6.1 ...
  Type "help", "copyright", "credits" or "license" for more information.

  >>> x += 1
  Traceback (most recent call last):
    File "", line 1, in 
  NameError: name 'x' is not defined

Is there a beneficial effect of silently creating the instance  
attribute, which outweighs the detrimental effects: (1) inconsistency,  
(2) the "surprising" decoupling?


Yes.  If you access an attribute, you want the search to go like this:

- check instance for attribute
- check class for attribute
- check base classes for attribute


But do you, though?  The only occasion I can think of that I'd want
the search to go past the instance is this "auto-initialisation",
and frankly I'd rather do that in an __init__ anyway.  Perhaps
static methods or class methods work that way, I don't know how
the innards of the interpreter handle that.

Is there any actual advantage to self.attribute picking up
Class.attribute instead of raising a NameError?


If you write an attribute, you want it stored in the attribute, not

   ^

the class or base classes.


I think you meant "instance" there :-)  Actually what I want is for
the attribute to be stored where I told it, which could well be in
the class.  If the attribute is specified as "self.attribute", then
yes, put it in the instance.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWin32 for Python 3.x

2009-03-15 Thread Tim Golden

John Nagle wrote:

   That "wizard" won't even install unless Python 3.0 is "in the
registry", which apparently means "installed as the default Python".


No, it just means "installed somewhere". I have 6 different
versions of Python installed on this box. The choice of
which is "the default" is mine, either by selection at
installation or by later manipulation of associations,
path etc.



After giving the user an alert box, it dumps you into a dialog which
says "Python 3.0 is required for this package.  Select installation to 
use".

That's blank, and the form fields "Python Directory" and "Installation
Directory" won't accept input, so it can't even be overridden manually.


I agree that this is annoying.



   Lame.

   And no, I don't want to build it from source.  I'm just checking to
see how close Python 3.x is getting to prime time.  Looks like it's
still a long way off.



While I don't feel strongly about the matter -- I have no particular
need to use Python 3.x for now, altho' I'm tracking it -- I think
that you're making quite a far-reaching statement on scant evidence. Fair
enough, you couldn't do a quick-and-dirty install of pywin32-213
for Python 3.x without having Python 3.x installed and in the
registry. To go from that to claiming that Python 3.x is a long
way from prime time seems at the very least to ignore the legions
of non-Windows users who neither know nor care about pywin32.


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


Re: PyWin32 for Python 3.x

2009-03-15 Thread John Nagle

Tim Golden wrote:

John Nagle wrote:

   Any idea when PyWin32 will be available for Python 3.x?

John Nagle


Release 213 is out already:

http://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063&release_id=661475 



I think it's still considered a little bit beta. There have been a *lot*
of changes involved.


   That "wizard" won't even install unless Python 3.0 is "in the
registry", which apparently means "installed as the default Python".
After giving the user an alert box, it dumps you into a dialog which
says "Python 3.0 is required for this package.  Select installation to use".
That's blank, and the form fields "Python Directory" and "Installation
Directory" won't accept input, so it can't even be overridden manually.

   Lame.

   And no, I don't want to build it from source.  I'm just checking to
see how close Python 3.x is getting to prime time.  Looks like it's
still a long way off.

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-15 Thread Rhodri James
On Sat, 14 Mar 2009 08:20:21 -, Hendrik van Rooyen  
 wrote:



"Tim Rowe"  wrote:

8< -


. If "Finance users and non-professional
programmers find the locale approach to be frustrating, arcane and
non-obvious" then by all means propose a way of making it simpler and
clearer, but not a bodge that will increase the amount of bad software
in the world.


I do not follow the reasoning behind this.

It seems to be based on an assumption that the locale approach
is some sort of holy grail that solves these problems, and that
anybody who does not like or use it is automatically guilty of
writing crap code.

No account seems to be taken of the fact that the locale approach
is a global one that forces uniformity on everything done on a PC
or by a user.


Like unicode, locales should make using your computer with your own
cultural settings a one-time configuration, and make using your
computer in another setting possible.  By and large they do this.

Like unicode, locales fail in as much as they make cross-cultural
usage difficult.  Unlike unicode, there is a lot of failure in the
standard locale library, which is almost entirely the fault of the
standard C locale library it uses.

Nobody's defending the implementation, as far as I've noticed
(which isn't saying much at the moment, but still...).  A bit of
poking around in the cheese shop suggests that Babel
(http://www.babel.edgewall.org/) would be better, and Babel with
a context manager would be better yet.


On the other hand, we have a small addition to format strings.
Unfortunately it's a small addition that doesn't feel terribly
natural in a mini-language that already runs the risk of looking
like line noise when you pull the stops out.  Not meaning the
term particularly unkindly, it is a bodge; it's quick and dirty,
syntactic saccharin rather than sugar for doing one particular
thing for one particular interest group, and which looks
deceptively like the right thing to do for everyone else.

That's a bad thing to do.  If we ever do get round to fixing
localisation (i.e. making overriding bits of locales easy), it
becomes a feature that's automatically present that we have
to discourage normal programmers from using despite it's
apparent usefulness.


Frankly, I'd much rather fix the locale system and extend
the format syntax to override the default locale.  Perhaps
something like

  financial = Locale(group_sep=",", grouping=[3])
  print("my number is {0:10n:financial}".format(1234567))

It's hard to think of a way of extending "%" format strings
to cope with this that won't look utterly horrid, though!

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Ned Deily
In article <49bd42ac$0$512$bed64...@news.gradwell.net>,
 tinn...@isbd.co.uk wrote:
> I was just hoping there was some calendar object in Python which could
> do all that for me (I need the handling of 31st and February etc.)

Whatever your requirement, chances are dateutil will be of help:



-- 
 Ned Deily,
 n...@acm.org

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 11:00 AM,   wrote:
> Roy Smith  wrote:
>> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk
>> wrote:
>>
>> > I have a date in the form of a datetime object and I want to add (for
>> > example) three months to it.  At the moment I can't see any very
>> > obvious way of doing this.  I need something like:-
>> >
>> >     myDate = datetime.date.today()
>> >     inc = datetime.timedelta(months=3)
>> >     myDate += inc
>> >
>> > but, of course, timedelta doesn't know about months. I had a look at
>> > the calendar object but that didn't seem to help much.
>>
>> Well, before you can "add three months" to something, you need to explain
>> what that means.
>>
>> What is Nov 29th plus 3 months?
>>
>> What is Jan 31st plus 3 months?
>>
>> Months are different lengths.  Asking to "add 3 months" is kind of like
>> asking, "If I'm somewhere in the continental US (east of the Mississippi
>> River) and move three states to the west, how many miles have I moved?"
>
> No, it's perfectly possible applying simple logic.  My reminder
> program manages it perfectly well.  I have, for example, two sets of
> three monthly reminders.
>
>    One starts on Jan 19th and repeats three monthly, that means Jan
>    19th, April 19th, July 19th and October 19th.  Very simple.
>
>    The other is a little more difficult, it starts on December 31st
>    and repeats three monthly.  So that one is on December 31st, March
>    31st, June 30th and September 30th.
>
> The calendar program manages it perfectly well using what seems to me
> fairly obvious logic, what I want is to be able to do the same in
> Python.
>
> I.e. in simple terms I want the "same day N months hence" and, if it
> doesn't exist then the nearest possible.

But that's not what you said originally; you now fleshed out important
details. Your original question was simpler and more ambiguous.
The problem here is that there are multiple ways to handle the
ambiguous situations and there's no objective, obvious right choice.
Thus, though one must implement it by oneself, one gets exactly the
behavior one desires.
Besides your behavior, one could equally well argue that a 31st repeat
on months without a 31st should just be dropped, or that it should
carry over onto the 1st of the next month (ignoring the complications
of February). Which behavior one needs is completely
context-dependent.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Andre Engels
On Sun, Mar 15, 2009 at 7:00 PM,   wrote:
> Roy Smith  wrote:
>> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk
>> wrote:
>>
>> > I have a date in the form of a datetime object and I want to add (for
>> > example) three months to it.  At the moment I can't see any very
>> > obvious way of doing this.  I need something like:-
>> >
>> >     myDate = datetime.date.today()
>> >     inc = datetime.timedelta(months=3)
>> >     myDate += inc
>> >
>> > but, of course, timedelta doesn't know about months. I had a look at
>> > the calendar object but that didn't seem to help much.
>>
>> Well, before you can "add three months" to something, you need to explain
>> what that means.
>>
>> What is Nov 29th plus 3 months?
>>
>> What is Jan 31st plus 3 months?
>>
>> Months are different lengths.  Asking to "add 3 months" is kind of like
>> asking, "If I'm somewhere in the continental US (east of the Mississippi
>> River) and move three states to the west, how many miles have I moved?"
>
> No, it's perfectly possible applying simple logic.  My reminder
> program manages it perfectly well.  I have, for example, two sets of
> three monthly reminders.
>
>    One starts on Jan 19th and repeats three monthly, that means Jan
>    19th, April 19th, July 19th and October 19th.  Very simple.
>
>    The other is a little more difficult, it starts on December 31st
>    and repeats three monthly.  So that one is on December 31st, March
>    31st, June 30th and September 30th.
>
> The calendar program manages it perfectly well using what seems to me
> fairly obvious logic, what I want is to be able to do the same in
> Python.
>
> I.e. in simple terms I want the "same day N months hence" and, if it
> doesn't exist then the nearest possible.

Well, that's one way of defining it, but it does have some
consequences you have to watch out for. In particular, it means that
the following equalities do not necessarily hold:

Date + 2 months = Date + 1 month + 1 month
Date = Date + 1 month - 1 month

not to mention anything where you use days or weeks in combination
with months...

-- 
André Engels, andreeng...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
this means i have to check if d[i] is list or dict and iterate over
properties
-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 1:03 PM, alex goretoy
wrote:

> I will also actually need to nest it like so
>
> d={
>"site_name":["s","site",'
>>
>> sites','site_name','site_names'],
>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>
> "options":{
> "src_name":["ss","src","source"],
> "mod_name":['m',"mod",'mods',"module","modules"],
> }
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Sun, Mar 15, 2009 at 10:51 AM, MRAB  wrote:
>
>> d={
>>>"site_name":["s","site",'sites','site_name','site_names'],
>>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread tinnews
Chris Rebert  wrote:
> On Sun, Mar 15, 2009 at 10:28 AM,   wrote:
> > I have a date in the form of a datetime object and I want to add (for
> > example) three months to it.  At the moment I can't see any very
> > obvious way of doing this.  I need something like:-
> >
> >    myDate = datetime.date.today()
> >    inc = datetime.timedelta(months=3)
> >    myDate += inc
> >
> > but, of course, timedelta doesn't know about months.
> 
> Which makes some sense considering a month can range from 28-31 days,
> which would make the delta oddly fuzzy.
> 
> Here's one approach:
> myDate = datetime.date.today()
> newYear = myDate.year
> newMonth = myDate.month + 3
> if newMonth > 12:
> newYear += 1
> newMonth -= 12
> inThreeMonths = datetime.date(newYear, newMonth, myDate.day)
> #add extra analogous logic if you have to deal with February or 31st days.
> 
I was just hoping there was some calendar object in Python which could
do all that for me (I need the handling of 31st and February etc.)

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread tinnews
Roy Smith  wrote:
> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk 
> wrote:
> 
> > I have a date in the form of a datetime object and I want to add (for
> > example) three months to it.  At the moment I can't see any very
> > obvious way of doing this.  I need something like:-
> > 
> > myDate = datetime.date.today()
> > inc = datetime.timedelta(months=3)
> > myDate += inc
> > 
> > but, of course, timedelta doesn't know about months. I had a look at
> > the calendar object but that didn't seem to help much.
> 
> Well, before you can "add three months" to something, you need to explain 
> what that means.
> 
> What is Nov 29th plus 3 months?
> 
> What is Jan 31st plus 3 months?
> 
> Months are different lengths.  Asking to "add 3 months" is kind of like 
> asking, "If I'm somewhere in the continental US (east of the Mississippi 
> River) and move three states to the west, how many miles have I moved?"

No, it's perfectly possible applying simple logic.  My reminder
program manages it perfectly well.  I have, for example, two sets of
three monthly reminders.

One starts on Jan 19th and repeats three monthly, that means Jan
19th, April 19th, July 19th and October 19th.  Very simple.

The other is a little more difficult, it starts on December 31st
and repeats three monthly.  So that one is on December 31st, March
31st, June 30th and September 30th.

The calendar program manages it perfectly well using what seems to me
fairly obvious logic, what I want is to be able to do the same in
Python. 

I.e. in simple terms I want the "same day N months hence" and, if it
doesn't exist then the nearest possible.

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


Re: how to repeat function definitions less

2009-03-15 Thread alex goretoy
I will also actually need to nest it like so

d={
   "site_name":["s","site",'
>
> sites','site_name','site_names'],
>"jar_name":["j","jar",'jars','jar_name','jar_names'],

"options":{
"src_name":["ss","src","source"],
"mod_name":['m',"mod",'mods',"module","modules"],
}

-Alex Goretoy
http://www.goretoy.com



On Sun, Mar 15, 2009 at 10:51 AM, MRAB  wrote:

> d={
>>"site_name":["s","site",'sites','site_name','site_names'],
>>"jar_name":["j","jar",'jars','jar_name','jar_names'],
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Aaron Brady
On Mar 15, 12:39 pm, John Posner  wrote:
> (My apologies if the thread has already covered this.) I believe I understand 
> the WHAT in this situation, but I don't understand the WHY ...
>
> Given this class definition:
>
>   class Cls(object):
>       x = 345
>
> ... I observe the following, using IDLE 2.6.1:
>
> >>> inst = Cls()
> >>> Cls.x is inst.x
>
> True
>
> >>> Cls.x += 1
> >>> Cls.x is inst.x
>
> True
>
> >>> inst.x += 1
> >>> Cls.x is inst.x
>
> False
>
> My question is ... WHY does the interpreter silently create the instance 
> attribute at this point, causing a "surprising decoupling" from the class 
> attribute? WHY doesn't the interpreter behave as it would with a simple, 
> non-instance variable:
>
>   > python
>   Python 2.6.1 ...
>   Type "help", "copyright", "credits" or "license" for more information.
>
>   >>> x += 1
>   Traceback (most recent call last):
>     File "", line 1, in 
>   NameError: name 'x' is not defined
>
> Is there a beneficial effect of silently creating the instance attribute, 
> which outweighs the detrimental effects: (1) inconsistency, (2) the 
> "surprising" decoupling?
>
> Tx,
> John

Yes.  If you access an attribute, you want the search to go like this:

- check instance for attribute
- check class for attribute
- check base classes for attribute

If you write an attribute, you want it stored in the attribute, not
the class or base classes.

...unless you're just picking on the augmented ops, in which case the
tradeoff is more subtle than stated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Roy Smith
In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk 
wrote:

> I have a date in the form of a datetime object and I want to add (for
> example) three months to it.  At the moment I can't see any very
> obvious way of doing this.  I need something like:-
> 
> myDate = datetime.date.today()
> inc = datetime.timedelta(months=3)
> myDate += inc
> 
> but, of course, timedelta doesn't know about months. I had a look at
> the calendar object but that didn't seem to help much.

Well, before you can "add three months" to something, you need to explain 
what that means.

What is Nov 29th plus 3 months?

What is Jan 31st plus 3 months?

Months are different lengths.  Asking to "add 3 months" is kind of like 
asking, "If I'm somewhere in the continental US (east of the Mississippi 
River) and move three states to the west, how many miles have I moved?"
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Vlastimil Brom
2009/3/15  :
> I have a date in the form of a datetime object and I want to add (for
> example) three months to it.  At the moment I can't see any very
> obvious way of doing this.  I need something like:-
>
>    myDate = datetime.date.today()
>    inc = datetime.timedelta(months=3)
>    myDate += inc
>
> but, of course, timedelta doesn't know about months. I had a look at
> the calendar object but that didn't seem to help much.
>
> --
> Chris Green
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I guess, one can simply do this manually:

>>> td = datetime.date.today()
>>> td
datetime.date(2009, 3, 15)
>>> td_plus_3_months = datetime.date(td.year, td.month+3, td.day)
>>> td_plus_3_months
datetime.date(2009, 6, 15)


however, one have to check for non existing dates:
>>> datetime.date(td.year, td.month+10, td.day)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: month must be in 1..12
>>>

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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Chris Rebert
On Sun, Mar 15, 2009 at 10:28 AM,   wrote:
> I have a date in the form of a datetime object and I want to add (for
> example) three months to it.  At the moment I can't see any very
> obvious way of doing this.  I need something like:-
>
>    myDate = datetime.date.today()
>    inc = datetime.timedelta(months=3)
>    myDate += inc
>
> but, of course, timedelta doesn't know about months.

Which makes some sense considering a month can range from 28-31 days,
which would make the delta oddly fuzzy.

Here's one approach:
myDate = datetime.date.today()
newYear = myDate.year
newMonth = myDate.month + 3
if newMonth > 12:
newYear += 1
newMonth -= 12
inThreeMonths = datetime.date(newYear, newMonth, myDate.day)
#add extra analogous logic if you have to deal with February or 31st days.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread John Posner

(My apologies if the thread has already covered this.) I believe I understand 
the WHAT in this situation, but I don't understand the WHY ...

Given this class definition:

  class Cls(object):
  x = 345

... I observe the following, using IDLE 2.6.1:

>>> inst = Cls()
>>> Cls.x is inst.x
True

>>> Cls.x += 1
>>> Cls.x is inst.x
True

>>> inst.x += 1
>>> Cls.x is inst.x
False

My question is ... WHY does the interpreter silently create the instance 
attribute at this point, causing a "surprising decoupling" from the class 
attribute? WHY doesn't the interpreter behave as it would with a simple, 
non-instance variable:

  > python
  Python 2.6.1 ...
  Type "help", "copyright", "credits" or "license" for more information.

  >>> x += 1
  Traceback (most recent call last):
File "", line 1, in 
  NameError: name 'x' is not defined

Is there a beneficial effect of silently creating the instance attribute, which 
outweighs the detrimental effects: (1) inconsistency, (2) the "surprising" 
decoupling?

Tx,
John


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


Re: Style question - defining immutable class data members

2009-03-15 Thread M R A Barnett

Aaron Brady wrote:
[snip]

However, in my (opined) interpretation, 'list.append(...) is an in-
place operation' is a factual error.  In-place operations -also-
rebind their 'argument' (FLOBW for lack of better words).  'append' is
a by-side-effect operation.  However colloquially it's mostly
accurate.


[snip]
All the augmented assignments rebind, even for objects which support
in-place operations. For example:

my_list = []
my_list += [0]

rebinds, but the equivalent:

my_list = []
my_list.extend([0])

doesn't.

Augmented assignments which don't support in-place operations behave
like normal assignments (binding). For example:

my_int = 0
my_int += 1

behaves like:

my_int = 0
my_int = my_int + 1
--
http://mail.python.org/mailman/listinfo/python-list


How to add months to a date (datetime object)?

2009-03-15 Thread tinnews
I have a date in the form of a datetime object and I want to add (for
example) three months to it.  At the moment I can't see any very
obvious way of doing this.  I need something like:-

myDate = datetime.date.today()
inc = datetime.timedelta(months=3)
myDate += inc

but, of course, timedelta doesn't know about months. I had a look at
the calendar object but that didn't seem to help much.

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


Re: Style question - defining immutable class data members

2009-03-15 Thread Aaron Brady
On Mar 15, 8:56 am, "Rhodri James" 
wrote:
> On Sun, 15 Mar 2009 13:26:17 -, Matthew Woodcraft  
>
>  wrote:
>
> [snip Gary Herron's explanation of instance attribute lookup
> falling back to class attribute lookup]
>
> > It seems clear to me that Maxim understood all this when he asked his
> > original question (you need to understand this subtlety to know why
> > the trick he was asking about only works for immutable values).
>
> It seems equally clear to me that Maxim didn't understand any of this
> when he asked his original question, since he appeared to view class
> attributes purely as initialisers.
>
> Given that either of us could be right, Gary's assumption of less
> understanding rather than more is clearly the safer one to take.
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses

It's interesting Rhodri chose the safety dimension as the deciding
factor: Gary's assumption might have other faults, but it's safer, and
(by Grice's maxim of quantity,) therefore better.  In it's form:

M: Safer is better.
m: Gary's assumption is safer.
C: Gary's assumption is better.

There are two empirical claims, specifically the major and minor
premises.  It's not clear that either is true, but I think it's a
mistake to make a blanket judgment of net safety between competing
goods.

Long story short, it's safe for our pride, by cutting down outsiders,
but it's not safe for our publicity.

As for the discussion, Gary said it: 'self.list = self.list + [i]' is
a private write, but has other dangers such as running time and stored
references.

However, in my (opined) interpretation, 'list.append(...) is an in-
place operation' is a factual error.  In-place operations -also-
rebind their 'argument' (FLOBW for lack of better words).  'append' is
a by-side-effect operation.  However colloquially it's mostly
accurate.

And to the OP, your method works for immutable class members, and even
certain uses of mutable ones.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question - defining immutable class data members

2009-03-15 Thread Bruno Desthuilliers

Maxim Khitrov a écrit :

On Sat, Mar 14, 2009 at 2:07 PM, Gary Herron  wrote:

Maxim Khitrov wrote:

Very simple question on the preferred coding style. I frequently write
classes that have some data members initialized to immutable values.
For example:

class Test(object):
   def __init__(self):
   self.some_value = 0
   self.another_value = None

Similar effect can be achieved by defining some_value and
another_value for the entire class, like so:

class Test(object):
   some_value = 0
   another_value = None

The advantage of doing this is that the assignments are evaluated once
and thus the creation of that class is a bit faster. Access is still
performed through self.some_value and self.another_value. Is there a
reason to prefer the first style over the second?

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


Such things are often called class attributes, and the are fine.  If you
look through Python's standard library,  you will find many examples of
class attributes.

However, you appear to have either a misuse or misconception of the word
"immutable' here.   Whether the value you assign to a class attribute is
mutable or immutable is irrelevant.   Also whether you plan on leaving the
value constant or not is also not relevant.
What does matter is this:  If every instance wants access to a single value
(immutable or not), use a class attribute, otherwise use an instance
attribute.

Gary Herron


Perhaps a different example would help explain what I'm trying to do:

class Case1(object):
def __init__(self):
self.count = 0
self.list  = []

def inc(self):
self.count += 1
self.list.append(self.count)

def val(self):
return (self.count, self.list)

class Case2(object):
count = 0
list  = []

def inc(self):
self.count += 1


This above statement does 3 things:

1/ read "self.count", which, *the first time this method is called*, 
resolves to self.__class__.count since by that time, there's no instance 
attribute named 'count'


2/ add one to the int object returned by looking up 'self.count'

3/ store the result as instance attribute named 'count'.

IOW, the first calls to the method reads the class 'count' attribute and 
creates the instance 'count' attribute. Subsequent calls will resolve 
'self.count' as the instance attribute since it now exists.




self.list.append(self.count)


And this statement:

1/ read 'self.list', which resolves to self.__class__.list (the class 
attribute) since there's no instance attribute named 'list'


2/ mutate the class attribute



The only difference between Case1 and Case2 classes is where the count
and list attributes are defined. You will notice that for an immutable
type (count), this doesn't matter.


cf above.


On the last line, v1 == v2 is
always True. When the type is mutable (list), you must define it in
__init__.


Try rebinding self.list instead of mutating it, and you'll find out that 
it's not related to immutable/mutable types, but to how Python's object 
model works wrt/ attribute lookup and attribute binding.


An simple example being worth a thousand words:

class Case3(object):
count = 0
list  = []

def inc(self):
print self.__dict__
self.count += 1
self.list = self.list + [self.count]
print self.__dict__

def val(self):
return (self.count, self.list)

>>> c = Case3()
>>> print c.__dict__
{}
>>> print c.__class__.__dict__
{'count': 0, '__module__': '__main__', 'val': 0xb7c7bd4c>, 'list': [], '__dict__': objects>, '__weakref__': , 
'__doc__': None, 'inc': }

>>> c.inc()
{}
{'count': 1, 'list': [1]}
>>> print c.__dict__
{'count': 1, 'list': [1]}
>>> print c.__class__.__dict__
{'count': 0, '__module__': '__main__', 'val': 0xb7c7bd4c>, 'list': [], '__dict__': objects>, '__weakref__': , 
'__doc__': None, 'inc': }

>>>



This isn't about class attributes or shared instance
attributes/constants.


Yes, it is.


This is about a small optimization in defining
per-instance variables. This optimization only applies to immutable
types.


Wrong conclusions, sorry.

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


  1   2   >