Re: Unix-head needs to Windows-ize his Python script (II)
In message , Tim Golden wrote: > If you were to rename the .py to a .pyw it would run without a console > window showing up. Presumably the “w” stands for “window”. Wouldn’t it be less confusing if it was the other way round? -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
In message <[email protected]>, Peter Pearson wrote: > Is it important to let "a" range all the way up to b, instead of > stopping at b-1? (tongue in cheek) Makes no difference. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix-head needs to Windows-ize his Python script (II)
On Sat, Oct 23, 2010 at 12:32 AM, Lawrence D'Oliveiro wrote: > In message , Tim Golden > wrote: > >> If you were to rename the .py to a .pyw it would run without a console >> window showing up. > > Presumably the “w” stands for “window”. Why not "windowless"? - Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for comments on a design
TomF wrote: > I have a program that manipulates lots of very large indices, which I > implement as bit vectors (via the bitarray module). These are too > large to keep all of them in memory so I have to come up with a way to > cache and load them from disk as necessary. I've been reading about > weak references and it looks like they may be what I want. > > My idea is to use a WeakValueDictionary to hold references to these > bitarrays, so Python can decide when to garbage collect them. I then > keep a key-value database of them (via bsddb) on disk and load them > when necessary. The basic idea for accessing one of these indexes is: > > _idx_to_bitvector_dict = weakref.WeakValueDictionary() In a well written script that cache will be almost empty. You should compare the weakref approach against a least-recently-used caching strategy. In newer Pythons you can use collections.OrderedDict to implement an LRU cache or use the functools.lru_cache decorator. > def retrieve_index(idx): > if idx in _idx_to_bitvector_dict and _idx_to_bitvector_dict[idx] is > not None: > return _idx_to_bitvector_dict[idx] In a multi-threaded environment the above may still return None or raise a KeyError. > else: # it's been gc'd > bv_str = bitvector_from_db[idx]# Load from bsddb > bv = cPickle.loads(bv_str)# Deserialize the string > _idx_to_bitvector_dict[idx] = bv # Re-initialize the weak > dict element > return bv > > Hopefully that's not too confusing. Comments on this approach? I'm > wondering whether the weakref stuff isn't duplicating some of the > caching that bsddb might be doing. Even if the raw value is cached somewhere you save the overhead of deserialisation. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
:-0
very interesting!
I've tried to run something like this:
.
class en_property(property):
ptr_pget = None
ptr_pset = None
def pset(self, _class, value):
if (self.ptr_pset is None or type(value) == tuple):
self.ptr_pset = value[1]
self.ptr_pget = value[0]
else:
self.ptr_pset(self, _class, value)
def pget(self, _class):
return self.ptr_pget(self, _class)
def __init__(self, pget, pset):
property.__init__(self, self.pget, self.pset)
self.ptr_pget = pget
self.ptr_pset = pset
class segment():
def __new__(self):
class _segment():
def min_set(prop, self, p_min):
if (self.v_max is not None) and (p_min > self.v_max):
raise AttributeError('It must be: "min < max"')
else:
prop.v_min = p_min
def min_get(prop, self):
if 'v_min' in dir(prop):
return prop.v_min
def max_set(prop, self, p_max):
if (self.v_min is not None) and (p_max < self.v_min):
raise AttributeError('It must be: "min < max"')
else:
prop.v_max = p_max
def max_get(prop, self):
if 'v_max' in dir(prop):
return prop.v_max
def class_set(prop, self, value):
raise AttributeError('Cannot change "__class__"')
def class_get(prop, self):
class segment():
v_min, v_max = None, None
return segment
v_min = en_property(min_get, min_set)
v_max = en_property(max_get, max_set)
__class__ = en_property(class_get, class_set)
del min_get, min_set, max_get, max_set, class_get,
class_set
obj = _segment()
return obj
.
>>> s = segment()
>>> t = segment()
>>> s.v_min, s.v_max = -1, 1
>>> t.v_min, t.v_max = 10, 20
.
I've even override attribute __class__ (it is an property),
and code "s.__class__.v_min.v_min" raises an exception.
but we still can change the value of property using direct link:
>>> type(s).v_min.v_min = 10
I think I'm being realized that Python allows to do everything.
Maybe I will not try to find "really hidden encapsulation". :)
p.s. what do you think about the presence of two fields v_min (in
first message):
“s.__dict__['v_min']” and “s.v_min”?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Has Next in Python Iterators
Hello,
On Thu, Oct 21, 2010 at 12:26:50PM +, Steven
D'Aprano wrote:
> I know what you're thinking: "it's easy to cache
> the next result, and return it on the next
> call". But iterators can also be dependent on
> the time that they are called, like in this
> example:
>
> def evening_time():
> while 1:
> yield time.strftime("%H:%m") # e.g. "23:20"
When working with things like this you should
anyway use some lock/sync/transaction, so that
prefetching iterator will most probably be OK
unless you've fundamentally screwed your code's
logics.
WRT the prefetcher, I'd use smth like this:
> def rand_gen():
> x = random.random()
> while x < 0.9:
> yield x
> x = random.random()
>
> class prefetcher:
> def __init__(self, i):
> self.i = i
> self.s = False
> self._prefetch()
> def _prefetch(self):
> try: self.n = self.i.next()
> except StopIteration: self.s = True
> def has_next(self): return not self.s
> def next(self):
> if self.s: raise StopIteration()
> else:
> n = self.n
> self._prefetch()
> return n
> def __iter__(self): return self
>
> rand_pre = prefetcher(rand_gen())
> while rand_pre.has_next(): print rand_pre.next()
--
With best regards,
xrgtn
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unix-head needs to Windows-ize his Python script (II)
In message , Chris Rebert wrote: > On Sat, Oct 23, 2010 at 12:32 AM, Lawrence D'Oliveiro > wrote: > >> In message , Tim >> Golden wrote: >> >>> If you were to rename the .py to a .pyw it would run without a console >>> window showing up. >> >> Presumably the “w” stands for “window”. > > Why not "windowless"? Why mention the fact that you don’t have something? “This car is the “D” model, the “D” standing for “Deluxeless”.” -- http://mail.python.org/mailman/listinfo/python-list
mro() or __mro__?
The documentation of the mro() method on the class object says: class.mro() This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__. Am I interpreting it correctly that the "__mro__" attribute is intended to be used directly, while the "mro" method is intended to be optionally overridden by the metaclass implementor? If that is the case, it sounds exactly the opposite to the normal python convention that __methods__ are part of the protocol, and underscore-less functions or methods are meant to be called by the end user of the class. -- http://mail.python.org/mailman/listinfo/python-list
ANN: Shed Skin 0.6
Hi all, I have just released Shed Skin 0.6, an optimizing (restricted-)Python-to-C++ compiler. Most importantly, this release comes with a substantial scalability improvement. It should now be possible to compile programs into several thousands of lines, as shown by the new Commodore 64 emulator example (around 2000 lines, sloccount). Please see my blog for the full announcement: http://shed-skin.blogspot.com Or go straight to the homepage: http://shedskin.googlecode.com Please have a look at the tutorial, try it out, and report issues at the homepage. Thanks, Mark Dufour -- http://www.youtube.com/watch?v=E6LsfnBmdnk -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix-head needs to Windows-ize his Python script (II)
On 2:59 PM, Lawrence D'Oliveiro wrote: In message, Tim Golden wrote: If you were to rename the .py to a .pyw it would run without a console window showing up. Presumably the “w” stands for “window”. Wouldn’t it be less confusing if it was the other way round? Presumably the original pythonw.exe was called that because it's marked as a windows-app. In win-speak, that means it has a gui. Applications that are not so-marked are console-apps, and get a console created if they weren't already started from one. That's where stdin/stdout/stderr get pointed. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: A good decorator library
On Oct 22, 10:42 pm, Felipe Bastos Nunes wrote: > Hi! I was looking for a good decorator library to study and make my > own decorators. I've read the Bruce Eckel's blog at artima dot com. > But I need some more examples. I'm building a WSN simulator like SHOX > is in java, but programming it in python. I'd like to use decorators > to set methods that would be logged as statistics and some more > funcionalities like check a method to check the params' types. > > Thanks in advance, and (at least here) good night eheh > -- > Felipe Bastos Nunes My own decorator module seems to be quite popular nowadays, by judging by the number of downloads. Even if you end up not using it, the documentation is quite pedagogic and intended for beginners, so you may want to look at it: http://pypi.python.org/pypi/decorator -- http://mail.python.org/mailman/listinfo/python-list
How to make a method into a property without using the @property decorator
Pythonistas: Here's the property decorator: @property def foo(self): return 'bar' If I generate foo dynamically, how to I make it a property? setattr(self, 'foo', property(lambda: 'bar')) Variations of that are apparently not working. (I'm heading for a proxy pattern, where if you never call the generated prop, you never hit the database to load it into memory.) -- Phlip http://zeekland.zeroplayer.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a method into a property without using the @property decorator
Phlip wrote: > Pythonistas: > > Here's the property decorator: > >@property >def foo(self): return 'bar' > > If I generate foo dynamically, how to I make it a property? > > setattr(self, 'foo', property(lambda: 'bar')) > > Variations of that are apparently not working. You have to put the property descriptor into the class, not an instance: >>> class A(object): ... pass ... >>> a = A() >>> setattr(type(a), "foo", property(lambda self: "FOO")) >>> a.foo 'FOO' >>> A().foo 'FOO' > (I'm heading for a proxy pattern, where if you never call the > generated prop, you never hit the database to load it into memory.) You may be better off with __getattr__(). Peter -- http://mail.python.org/mailman/listinfo/python-list
==Get an Internship in the United States ==
==Get an Internship in the United States == Internships are practical experiences that bridge the gap between the educational world and the real world allowing students to understand what is really like to work in the industry of their choice. International internships offer much more than the usual internship you would conduct in your country. These types of internships will open your eyes to new ways and new personal and professional relationships, will provide you with new settings and a new culture and expand your opportunities. Here is a small summary on how to get internships in the United States. read more http://studyabrods.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: mro() or __mro__?
Hrvoje Niksic wrote: > The documentation of the mro() method on the class object says: > > class.mro() > This method can be overridden by a metaclass to customize the method > resolution order for its instances. It is called at class > instantiation, and its result is stored in __mro__. > > Am I interpreting it correctly that the "__mro__" attribute is intended > to be used directly, while the "mro" method is intended to be optionally > overridden by the metaclass implementor? Looks like you're right: >>> class T(type): ... def mro(self): ... r = type.mro(self) ... print r ... return r[::-1] ... >>> class A: ... __metaclass__ = T ... [, ] >>> A.__mro__ (, ) > If that is the case, it sounds exactly the opposite to the normal python > convention that __methods__ are part of the protocol, and > underscore-less functions or methods are meant to be called by the end > user of the class. While I'm not aware of any cases where obj.foo() translates to obj.__foo__() internally make_mro() might still have been a more appropriate name. Peter -- http://mail.python.org/mailman/listinfo/python-list
measuring python code efficiency
Hi all, I use to program in many languages ,currently i 'm working in python ,i wonder if their is any way-program to measure my code , for example memory usage , cpu speed - because of the ability to write one program in many ways , how i can evaluate my code? Many thanks, n.a.s -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE debugger questions
Thanks for that info, Ned, I can now get the sys.argv[] list I need, that's a big help! However, is there any other way to set a breakpoint in idle that will work on Mac OS X, maybe entering a manual command somewhere with a specified line number? Inability to set a breakpoint is an absolute showstopper for me, the code I am trying to debug loops way too much to be manually steppable in a human time frame. I also spent a couple of hours trying to get ddd to work, and oddly enough encountered a similar problem there. After downloading and installing pydb I was able to get things to start up OK. You can set a breakpoint, meaning that you can click on the source line and the little stop sign icon pops up right there as expected, but when you run the code the debugger just blows right by it like it's not even there. Does anyone out there have a fix for this? It sounds like ddd Python support is highly problematic at the moment, supposedly it works only with pydb but pydb's author has apparently moved on to a different debugger project (pydbgr?) that I suspect has little chance of working with ddd just yet. If anyone has evidence to the contrary please let me know! Are there any Python debuggers with a decent GUI out there at all that will work on a Mac with the following features: (i) ability to pass in a sys.srgv[] list that the program would otherwise see without the debugger, (ii) display local variables, (iii) single-step through the source code, and (iv) set a breakpoint? I think I can live without anything else for the moment. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: "Strong typing vs. strong testing" [OT]
Steven D'Aprano writes: > Well, what is the definition of pi? Is it: > > the ratio of the circumference of a circle to twice its radius; > the ratio of the area of a circle to the square of its radius; > 4*arctan(1); > the complex logarithm of -1 divided by the negative of the complex square > root of -1; > any one of many, many other formulae. > > None of these formulae are intuitively correct; the formula C = 2πr isn't > a definition in the same sense that 1+1=2 defines 2. The point that I was > trying to get across is that, until somebody proved the formula, it > wasn't clear that the ratio was constant. There are several possible definitions of `2'. You've given a common one (presumably in terms of a purely algebraic definition of the integers as being the smallest nontrivial ring with characteristic 0). Another can be given in terms of Peano arithmetic, possibly using an encoding of Peano arithmetic using only the Zermelo-- Fraenkel axioms of set theory: at this point one has only a `successor' operation and must define addition; the obvious definition of 1 and 2 are s(0) and s(s(0)) respectively, and one then has an obligation to prove that s(0) + s(0) = s(s(0)), though this isn't very hard. I think my preferred definition of `pi' goes like this (following Lang's /Analysis I/). Suppose that there exist real functions s and c, such that s' = c and c' = -s, with s(0) = 0 and c(0) = 1. One can prove that a pair of such functions is unique, and periodic. Define pi to be half the (common) period of these functions. (Now we notice that they factor through the quotient ring R/(2 pi) and define `sin' and `cos' to be the induced functions on the quotient ring.) Would the world be a better place if we had a name for 2 pi rather than pi itself? -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib - Did the whole file get sent?
On Oct 22, 10:48 pm, Steven D'Aprano wrote: > On Fri, 22 Oct 2010 22:03:38 -0700, Sean DiZazzo wrote: > > How can I assure him (and the client) that the transfer completed > > successfully like my log shows? > > "It has worked well for many years, there are no reported bugs in the ftp > code > [...] Thanks for your advice Steven. I agree with you,and did take that approach to start with. Then the request for the actual FTP "ack" caught me off guard. I had to break out Wireshark and run a few tests just to make sure I knew exactly what I was talking about. I think I will try to explain that asking for the "ack" is not really a valid request. Something like this: "Technically, these messages are used only on the lowest level of the FTP protocol itself. Any client or library implementing FTP would be sending these messages under the covers...in this case I think its done in the socket library. It is possible that there is a bug in the Python FTP library, just like it's possible there is a bug in any other FTP client. Considering how long this library has been around (~15-20 years), and how often it is used, it is very unlikely that a bug causing a partial transfer but showing a success has managed to stick around for so long." Does that make sense? > > Is ftplib reliable enough to say that if an exception is not thrown, > > that the file was transferred in full? > > Python 2.4 is pretty old. Have you checked the bug tracker to see if > there are any reported bugs in ftplib that might be relevant? Or the > What's New for 2.5, 2.6 and 2.7? The source code for ftplib seems fairly > straightforward to me -- if there was an error, I can't see that it could > have been suppressed. > > But really, unless you can reproduce the error, I'd say the error lies > elsewhere. > > -- > Steven I'll check bugs and whats new before sending any response. The more I think about this, I am beginning to think that he is just trying to find someone to blame for a problem, and has chosen me. Thanks again. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: measuring python code efficiency
Theres the time module and the timeit() function to evaluate time to execute. For memory usage and cpu usage i can't remember exactly. I read the profile and cprofile documentation, and, in my opinion, help in somethings you wanna do. 2010/10/23, n.a.s : > Hi all, > I use to program in many languages ,currently i 'm working in python ,i > wonder if their is any way-program to measure my code , for example memory > usage , cpu speed - because of the ability to write one program in many ways > , how i can evaluate my code? > > Many thanks, > n.a.s > -- Felipe Bastos Nunes -- http://mail.python.org/mailman/listinfo/python-list
Re: pywebkit - python bindings for webkit DOM (alpha)
Okay found the instruction to build the project on the site http://www.gnu.org/software/pythonwebkit/ Not sure how to apply the patch. I already have an installation of pythonwebkit. Should I uninstall it, download the source from http://code.google.com/p/pywebkitgtk and then apply the patch. I've tried applying the patch when python webkit was installed itself. I don't think I could get the get_dom_document() on the WebFrame. --deostroll On Oct 22, 8:39 pm, deostroll wrote: > Hi, > > Any instructions on how to get started with the source code? > > --deostroll > On Oct 8, 1:57 am, lkcl wrote: > > > apologies for the 3 copies of the post: mail.python.org's SMTP service > > was offline yesterday. > > > just a quick update: XMLHttpRequest support has been fixed today, and > > the correct version of libsoup discovered which actually works. that > > puts PythonWebkit into a "useful and useable" state, despite being > > only 15 days old. further development is still needed, but it's still > > pretty exciting to be back to where the original python webkit > > bindings code was, from 2008, minus the cruft from the intermediate > > glib/gobject layer, in such a short amount of time. > > > l. -- http://mail.python.org/mailman/listinfo/python-list
MATLAB:matplotlib::Mathematica::???
Is there anything that does for Mathematica what matplotlib does for MATLAB? matplotlib, even in its underlying so-called "OO mode", follows MATLAB's graphics model, which, in my very subjective opinion, is vastly inferior to Mathematica's. The latter allows for a clean separation between the textual specification of a graphic object (which can be very complex), and its graphic representation. Furthermore, it is general enough to allow for the composition of graphic objects within other graphic objects, to arbitrary depth levels. This readily allows for the representation of complex composite figures that are common in scientific publishing today, where figures not only routinely consist of several subfigures, but the subfigures themselves contain mutliple sub-subfigures, and so on. (In contrast, matplotlib supports at most two levels of composition [a two-dimensional array of sub-plots], which is both too inflexible and too limited.) More generally, despite its usefulness, I find MATLAB in the end to be one big ugly hack, so, as a developer, I would prefer to stay clear of anything that is modeled after MATLAB, however loosely. Any pointers to something more Mathematica-like in Python would be appreciated. TIA! kj -- http://mail.python.org/mailman/listinfo/python-list
Re: measuring python code efficiency
Thanks Felipe , sure i will search for that.. Bests, n.a.s On Sat, Oct 23, 2010 at 7:11 PM, Felipe Bastos Nunes < [email protected]> wrote: > Theres the time module and the timeit() function to evaluate time to > execute. For memory usage and cpu usage i can't remember exactly. I > read the profile and cprofile documentation, and, in my opinion, help > in somethings you wanna do. > > 2010/10/23, n.a.s : > > Hi all, > > I use to program in many languages ,currently i 'm working in python ,i > > wonder if their is any way-program to measure my code , for example > memory > > usage , cpu speed - because of the ability to write one program in many > ways > > , how i can evaluate my code? > > > > Many thanks, > > n.a.s > > > > > -- > Felipe Bastos Nunes > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a method into a property without using the @property decorator
On Oct 23, 8:01 am, Peter Otten <[email protected]> wrote: > You may be better off with __getattr__(). Ayup, thanks. (Maybe I should have googled for "python equivalent of ruby method_missing", hmm?;) -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: PYBAG v0.4.0
This is first PYBAG announce on comp.lang.python. PYBAG implements a portable bag and is intended for fast synchronization and backup. It lets you use a portable digital storage device to carry your electronic documents similar to the way you can use a bag to carry paper documents. You can synchronize the bag with your original files easily. If a synchronization conflict occurs, it will be reported. You can specify rules for automatic conflict resolution. With PYBAG, you can backup files and synchronize any changes made to the original files with the bag. The synchronization process will only copy changed files. The program is cross-platform and independent from the OS and filesystem. You may easily synchronize files between Windows and Linux, for example. Symbolic links are supported on all systems (if the OS or filesystem does not support symlinks, then they are emulated). This program has a GUI and a command line interface. Home page: http://pybag.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: 64 bit offsets?
Am 07.10.2010 23:20, schrieb MRAB:
> On 07/10/2010 20:12, jay thompson wrote:
>> I'm not sure if it is limited to 32 bit addresses or if it's only
>> re.start() that is limited to 'em.
>>
>> jt
>>
> From what I can tell, Microsoft compilers (I'm assuming you're using
> Windows) have a 32-bit 'int' type for both 32-bit and 64-bit builds,
> and the re module uses Py_BuildValue("i", ...), which according to the
> docs uses the C 'int' type, so yes, it's 32 bits even in 64-bit Python.
> :-(
It would be easy enough to change this to PyInt_FromSsize_t.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list
Re: Request for comments on a design
On 2010-10-23 01:50:53 -0700, Peter Otten said: TomF wrote: I have a program that manipulates lots of very large indices, which I implement as bit vectors (via the bitarray module). These are too large to keep all of them in memory so I have to come up with a way to cache and load them from disk as necessary. I've been reading about weak references and it looks like they may be what I want. My idea is to use a WeakValueDictionary to hold references to these bitarrays, so Python can decide when to garbage collect them. I then keep a key-value database of them (via bsddb) on disk and load them when necessary. The basic idea for accessing one of these indexes is: _idx_to_bitvector_dict = weakref.WeakValueDictionary() In a well written script that cache will be almost empty. You should compare the weakref approach against a least-recently-used caching strategy. In newer Pythons you can use collections.OrderedDict to implement an LRU cache or use the functools.lru_cache decorator. I don't know what your first sentence means, but thanks for pointers to the LRU stuff. Maintaining my own LRU cache might be a better way to go. At least I'll have more control. Thanks, -Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
dmytro starosud writes:
>
> I think I'm being realized that Python allows to do everything.
> Maybe I will not try to find "really hidden encapsulation". :)
I think it's a wise decision :)
Just to challenge you a bit, here is another (doomed) attempt at having
private attributes for object instances:
def private_maker():
class Private: pass
privmap = {}
def private(f):
def wrapper(self, *args, **kwargs):
priv = privmap.setdefault(self, Private())
return f(self, priv, *args, **kwargs)
return wrapper
return private
private = private_maker()
class A:
@private
def __init__(self, private, x):
private.x = x
@property
@private
def x(self, private):
return private.x
del private
a = A(2)
Can you change the value of a.x?
(Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3)
> p.s. what do you think about the presence of two fields v_min (in
> first message):
> “s.__dict__['v_min']” and “s.v_min”?
Are you referring to the fact that in Python, if an attribute is a
property, the __dict__ lookup on the instance is not performed? As in:
>>> class A:
... @property
... def x(self): return 42
...
>>> a = A()
>>> a.__dict__['x'] = 24
>>> a.x
42
>>> a.__dict__['x']
24
This is documented, but I actually don't know the reason for it.
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
TRANSFER 300$ To Your EFT Account By Just ONE CLICK From OTHER Account
The FORM is in the IMAGE below the SEARCH BOX...CLICK on the IMAGE for the FORM of TRANSFERhttp://moneymaking.en.st -- http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
On 10/23/2010 11:51 AM Arnaud Delobelle said...
Just to challenge you a bit, here is another (doomed) attempt at having
private attributes for object instances:
def private_maker():
class Private: pass
privmap = {}
def private(f):
def wrapper(self, *args, **kwargs):
priv = privmap.setdefault(self, Private())
return f(self, priv, *args, **kwargs)
return wrapper
return private
private = private_maker()
class A:
@private
def __init__(self, private, x):
private.x = x
@property
@private
def x(self, private):
return private.x
del private
a = A(2)
Can you change the value of a.x?
(Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3)
I'm obviously missing something:
ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def private_maker():
... class Private: pass
... privmap = {}
... def private(f):
... def wrapper(self, *args, **kwargs):
... priv = privmap.setdefault(self, Private())
... return f(self, priv, *args, **kwargs)
... return wrapper
... return private
...
>>> private = private_maker()
>>>
>>> class A:
... @private
... def __init__(self, private, x):
... private.x = x
... @property
... @private
... def x(self, private):
... return private.x
...
>>> del private
>>>
>>> a = A(2)
>>>
>>>
>>> a.x
2
>>> a.x=3
>>> a.x
3
>>>
Emile
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
Emile van Sebille writes:
> On 10/23/2010 11:51 AM Arnaud Delobelle said...
>>
>> Just to challenge you a bit, here is another (doomed) attempt at having
>> private attributes for object instances:
[...]
> I'm obviously missing something:
>
> ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
> Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
def private_maker():
> ... class Private: pass
> ... privmap = {}
> ... def private(f):
> ... def wrapper(self, *args, **kwargs):
> ... priv = privmap.setdefault(self, Private())
> ... return f(self, priv, *args, **kwargs)
> ... return wrapper
> ... return private
> ...
private = private_maker()
class A:
> ... @private
> ... def __init__(self, private, x):
> ... private.x = x
> ... @property
> ... @private
> ... def x(self, private):
> ... return private.x
> ...
del private
a = A(2)
a.x
> 2
a.x=3
a.x
> 3
>
>
> Emile
Sorry, I forgot to mention that this is Python 3 code. In Python 2.X,
the "class A:" statement makes the class old-style. To try this in
Python 2.X, replace
class A:
...
with
class A(object):
...
to make the class new-style.
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
On 10/23/2010 3:34 AM, Lawrence D'Oliveiro wrote: In message<[email protected]>, Peter Pearson wrote: Is it important to let "a" range all the way up to b, instead of stopping at b-1? (tongue in cheek) Makes no difference. :) The difference is that before one writes the restricted range, one must stop and think of the proof that a==b is not possible for a pythagorean triple a,b,c. (If a==b, c==sqrt(2)*a and the irrationality of sqrt(2) implies that c is also irrational and therefore not integral). The OP asked for how to translate the problem description into two loops, one nested inside the other, and I gave the simplest, obviously correct, brute-force search answer. If the problem specification had asked for primitive triples (no common factors), an additional filter would be required. Another respondent referred, I believe, to Euclid's formula https://secure.wikimedia.org/wikipedia/en/wiki/Pythagorean_triple However, it is not well suited to the problem specified. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
On 10/23/2010 11:51 AM Arnaud Delobelle said... Can you change the value of a.x? (Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3) A.x,a.x = a.x,3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python has a "really hidden encapsulation"?
Emile van Sebille writes: > On 10/23/2010 11:51 AM Arnaud Delobelle said... >> >> Can you change the value of a.x? >> >> (Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3) > > A.x,a.x = a.x,3 I knew that was going to come next! That'll teach me not to specify the problem precisely :) The challenge is to actually change the value of the private 'x', so that 'a.x' will evaluate to 3 with neither 'A' nor 'a' being tampered with. Changing 'A.x' breaks every instance of 'A': >>> a, b = A(2), A(40) >>> A.x, a.x = a.x, 3 >>> b.x 3 So it is not a very robust solution :) It is possible to do this: >>> a, b = A(2), A(40) >>> [some expression] = 3 >>> a.x, b.x (3, 40) >>> a.__class__ == b.__class__ == A True Everything works as before, only the private 'x' of 'a' has been changed to 3. I wanted to illustrate that it is very difficult (impossible?) to hide objects in Python. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
inline for and if
Hello, I would get : db.table.field1, db.table.field2, etc. Inside a python instruction : db().select(HERE) It is web2py query actually. But I can't do this : db().select(for f in db['table'].fields: if f not in fieldsBlackList: db['table'][f],) Any idea? -- http://mail.python.org/mailman/listinfo/python-list
yield all entries of an iterable
Hi, Is there a simpler way to yield all elements of a sequence than this? for x in xs: yield x I tried googling but fond only the other direction (turning a generator into a list with "list(my_generator())". Sebastian -- http://mail.python.org/mailman/listinfo/python-list
Perforce integrate using p4 module
Does anyone have any example with perforce integrate command? Please help —Code Snippet— import P4 ##set p4.port, p4.client p4c = P4.P4() p4c.connect() view = “//depot/meta/project/frombranch/...//depot/meta/project/ tobranch/..." p4c.run(“integ –n”,view) —Getting— return P4API.P4Adapter.run(self, *self.__flatten(args)) P4.P4Exception: [P4#run] Errors during command execution( "p4 integ - n //depot/meta/project/frombranch/...//depot/meta/project/ tobranch/..." ) [Error]: Unknown command. Try 'p4 help' for info. -- http://mail.python.org/mailman/listinfo/python-list
A question I have...
I'm trying to make a sports simulation program and so far everything has worked until I try entering: Score1 = (Team1Off + Team2Def)/2 I get the error: TypeError: unsupported operand type(s) for /: 'str' and 'int' Can someone please explain to me what this means, why it doesn't work and what I can do to make it work? Thanks, Best Wishes, Joe Shoulak -- http://mail.python.org/mailman/listinfo/python-list
Re: inline for and if
On Wed, Oct 20, 2010 at 11:28 AM, Guy Doune wrote: > Hello, > I would get : > db.table.field1, db.table.field2, etc. > Inside a python instruction : > db().select(HERE) > It is web2py query actually. > > But I can't do this : > db().select( > for f in db['table'].fields: > if f not in fieldsBlackList: > db['table'][f], > ) > > Any idea? Generator expression (http://www.python.org/dev/peps/pep-0289/ ): db().select(db['table'][f] for f in db['table'].fields if f not in fieldsBlackList) Disclaimer: Never used web2py. I'm going by syntax alone here. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: yield all entries of an iterable
On Wed, Oct 20, 2010 at 3:27 PM, Sebastian wrote: > Hi, > Is there a simpler way to yield all elements of a sequence than this? > for x in xs: > yield x Not presently. There's a related PEP under discussion though: PEP 380: Syntax for Delegating to a Subgenerator http://www.python.org/dev/peps/pep-0380/ It would let you write: yield from xs Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A question I have...
On Thu, Oct 21, 2010 at 7:25 PM, Joe Shoulak wrote:
> I'm trying to make a sports simulation program and so far everything has
> worked until I try entering:
>
> Score1 = (Team1Off + Team2Def)/2
>
> I get the error:
>
> TypeError: unsupported operand type(s) for /: 'str' and 'int'
>
> Can someone please explain to me what this means, why it doesn't work and
> what I can do to make it work?
It means that your team names are strings and that dividing strings by
a number doesn't make sense.
>>> ('apple' + 'orange')/2
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Geremy Condra
--
http://mail.python.org/mailman/listinfo/python-list
Re: A question I have...
2010/10/22 Joe Shoulak : > I'm trying to make a sports simulation program and so far everything has > worked until I try entering: > > Score1 = (Team1Off + Team2Def)/2 > > I get the error: > > TypeError: unsupported operand type(s) for /: 'str' and 'int' > > Can someone please explain to me what this means, why it doesn't work and > what I can do to make it work? > > Thanks, > Best Wishes, > Joe Shoulak > > > -- > http://mail.python.org/mailman/listinfo/python-list > > The error message says, that the division operator "/" was applied between string and integer number, which obviously don't work. As the previous addition (Team1Off + Team2Def) didn't failed, both of these items are probably strings. If they are number literals, you can simply use int(Team1Off) + int(Team2Def) Also note, that "/" means integer division by default (until python 2) - i.e. the remainder would be discarded; you can enforce float division by making at least one operand floating point number: some_int/2.0 hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: A question I have...
On Thu, Oct 21, 2010 at 7:25 PM, Joe Shoulak wrote: > I'm trying to make a sports simulation program and so far everything has > worked until I try entering: > > Score1 = (Team1Off + Team2Def)/2 > > I get the error: > > TypeError: unsupported operand type(s) for /: 'str' and 'int' > > Can someone please explain to me what this means, why it doesn't work and > what I can do to make it work? Team1Off and Team2Def are strings (i.e. text); Python's string type is called "str". Adding two strings concatenates them; e.g. "abc" + "def" == "abcdef". "int" is the name of Python's integer type. 2 is the integer in question. You're trying to divide a string (the concatenation of Team1Off and Team2Def) by an integer (2), which is nonsensical (What would it mean to divide "The quick brown fox" by the number 2?); hence, Python raises an error (TypeError) to inform you of this. You need to convert Team1Off and Team2Def to numbers instead of strings so you can do calculations involving them. This can be done by writing: Team1Off = int(Team1Off) assuming Team1Off is a string representing a decimal integer; e.g. "12345". If it instead represents a floating-point number (i.e. has a decimal point; e.g. "1.23"), substitute "float" for "int". You will of course need to also convert Team2Def using the same technique. Note that ValueError will be raised if the string doesn't represent a number. You may also want to add the following to the start of your code so that the results of divisions are what you expect: from __future__ import division If you haven't already, you should read the Python tutorial: http://docs.python.org/tutorial/ Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Background image with Tkinter
Hello All, I know this is pretty easy to do, but I was not able to to do it because I am new to GUI and Python. I am using grid to manager my layout and I would like to add background image to one of my cells (say row=1 column=3), I intend to have a label (text ) written on top of the image. For now, I would like to stick with Tkinter, I checked out PIL. It seems like support for Python27 is jet to be included. Regards, Emeka -- *Satajanus Nig. Ltd * -- http://mail.python.org/mailman/listinfo/python-list
A Unique XML Parsing Problem
I must quickly and efficiently parse some data contained in multiple XML files in order to perform some learning algorithms on the data. Info: I have thousands of files, each file corresponds to a single song. Each XML file contains information extracted from the song (called features). Examples include tempo, time signature, pitch classes, etc. An example from the beginning of one of these files looks like: -60.000 -59.897 0.589 0.446 0.518 1.000 0.850 0.414 0.326 0.304 0.415 0.566 0.353 0.350 I am a statistician and therefore used to data being stored in CSV- like files, with each row being a datapoint, and each column being a feature. I would like to parse the data out of these XML files and write them out into a CSV file. Any help would be greatly appreciated. Mostly I am looking for a point in the right direction. I have heard about Beautiful Soup but never used it. I am currently reading Dive Into Python's chapters on HTML and XML parsing. And I am also more concerned about how to use the tags in the XML files to build feature names so I do not have to hard code them. For example, the first feature given by the above code would be "track duration" with a value of 29.12331 Thanks, -Devon -- http://mail.python.org/mailman/listinfo/python-list
Re: A Unique XML Parsing Problem
On Sat, Oct 23, 2010 at 4:40 PM, Devon wrote: > I must quickly and efficiently parse some data contained in multiple > XML files in order to perform some learning algorithms on the data. > Info: > > I have thousands of files, each file corresponds to a single song. > Each XML file contains information extracted from the song (called > features). Examples include tempo, time signature, pitch classes, etc. > An example from the beginning of one of these files looks like: > > > startOfFadeOut="29.12331" loudness="-12.097" tempo="71.031" > tempoConfidence="0.386" timeSignature="4" > timeSignatureConfidence="0.974" key="11" keyConfidence="1.000" > mode="0" modeConfidence="1.000"> > > > > > > > > > -60.000 > -59.897 > > > 0.589 > 0.446 > 0.518 > 1.000 > 0.850 > 0.414 > 0.326 > 0.304 > 0.415 > 0.566 > 0.353 > 0.350 > > I am a statistician and therefore used to data being stored in CSV- > like files, with each row being a datapoint, and each column being a > feature. I would like to parse the data out of these XML files and > write them out into a CSV file. Any help would be greatly appreciated. > Mostly I am looking for a point in the right direction. ElementTree is a good way to go for XML parsing: http://docs.python.org/library/xml.etree.elementtree.html http://effbot.org/zone/element-index.htm http://codespeak.net/lxml/ And for CSV writing there's obviously: http://docs.python.org/library/csv.html > And I am also more > concerned about how to use the tags in the XML files to build feature > names so I do not have to hard code them. For example, the first > feature given by the above code would be "track duration" with a value > of 29.12331 You'll probably want to look at namedtuple (http://docs.python.org/library/collections.html#collections.namedtuple ) or the "bunch" recipe (google for "Python bunch"). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
Jonathan Hartley wrote: One common way to store delayed actions is as a lambda (an anonymous function.) Although note that you don't have to use 'lambda' in particular -- functions defined with 'def' can be used the same way. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
numpad in idle
hi, here's my problem: I'm running IDLE in Ubuntu. For some reason numpad buttons do not work. I'm kinda used to this layout. Doesn anyone have an idea on how to switch it on? cheers, Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix-head needs to Windows-ize his Python script (II)
In message , Dave Angel wrote: > Presumably the original pythonw.exe was called that because it's marked > as a windows-app. In win-speak, that means it has a gui. Applications > that are not so-marked are console-apps, and get a console created if > they weren't already started from one. That's where stdin/stdout/stderr > get pointed. Which is completely backwards, isn’t it? -- http://mail.python.org/mailman/listinfo/python-list
Re: A Unique XML Parsing Problem
In message <0af3e9b1-8d3d-4efd-99d6-ca033204e...@n26g2000yqh.googlegroups.com>, Devon wrote: > I have heard about Beautiful Soup but never used it. BeautifulSoup is intended for HTML parsing. It is, or was, particularly good at dealing with badly-formed HTML, as commonly found on lots of websites. I think more recently some libraries changed out from under it, so I’m not sure if this is still true. XML is (officially) much more anal in its compliance, so you shouldn’t need to bend over backwards to parse it. -- http://mail.python.org/mailman/listinfo/python-list
Re: numpad in idle
On Oct 23, 7:41 pm, Jah_Alarm wrote: > here's my problem: I'm running IDLE in Ubuntu. For some reason numpad > buttons do not work. I'm kinda used to this layout. Doesn anyone have > an idea on how to switch it on? Sure, look directly above the number pad and you will see a button labeled "NumLock". Press that button and you should be golden! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
Baba wrote: > >i need a hint regarding the following exercise question: > >"Write a program that generates all Pythagorean triples whose small >sides are no larger than n. >Try it with n <= 200." > >what is "n" ? i am guessing that it is a way to give a bound to the >triples to be returned but i can't figure out where to fit in "n". Yes. That's saying your program should read a value for N, check that N is not larger then 200, then generate the Pythagorean triples where A and B are less than N. >a^a + b^b = c^c is the condition to satisfy No, it's not. It's a^2 + b^2 = c^2, where a, b, and c are integers. Perhaps you meant a*a + b*b = c*c. >and i need to use loops >and "n" will be an upper limit of one (or more?) of the loops but i am >a bit lost. Please help me get thinking about this right. The simplest (but not most efficient) method is brute force, using three loops, one each for a, b, and c. You can compute the largest "c" you will need by computing the square root of a*a+b*b. -- Tim Roberts, [email protected] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: A good decorator library
Felipe Bastos Nunes wrote: > >Hi! I was looking for a good decorator library to study and make my >own decorators. I've read the Bruce Eckel's blog at artima dot com. >But I need some more examples. I'm building a WSN simulator like SHOX >is in java, but programming it in python. I'd like to use decorators >to set methods that would be logged as statistics and some more >funcionalities like check a method to check the params' types. Be careful with this. Decorators have their uses, but it is very easy to make a program completely unreadable through the unjudicious use of decorators. It is not good programming to use a language freature just because it is there. -- Tim Roberts, [email protected] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: numpad in idle
On 24 окт, 16:44, rantingrick wrote: > On Oct 23, 7:41 pm, Jah_Alarm wrote: > > > here's my problem: I'm running IDLE in Ubuntu. For some reason numpad > > buttons do not work. I'm kinda used to this layout. Doesn anyone have > > an idea on how to switch it on? > > Sure, look directly above the number pad and you will see a button > labeled "NumLock". Press that button and you should be golden! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Get 899$ To Your PAYPAL Account ( There is a FORM )
CLICK on the IMAGE below the SEARCH BOX for the FORMhttp://moneymaking.en.st -- http://mail.python.org/mailman/listinfo/python-list
Python 2.7 parser bug on syntax for set literals ?
Hello,
This looks like a parser bug, but it's so basic I'm in doubt. Can
anyone confirm ?
>>> import sys
>>> sys.version
'2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]'
>>> ({'', 1}.items())
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'set' object has no attribute 'items'
Thanks!
--
Howe
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
On Sun, Oct 24, 2010 at 12:40 AM, Steve Howe wrote:
> Hello,
>
> This looks like a parser bug, but it's so basic I'm in doubt. Can
> anyone confirm ?
>
import sys
sys.version
> '2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]'
({'', 1}.items())
> Traceback (most recent call last):
> File "", line 1, in
> AttributeError: 'set' object has no attribute 'items'
I don't see anything in the docs that indicates that set objects have
a .items() method. http://docs.python.org/library/stdtypes.html#set
Python 3.1 is the same.
--
Jerry
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
On Sat, Oct 23, 2010 at 9:40 PM, Steve Howe wrote:
> Hello,
>
> This looks like a parser bug, but it's so basic I'm in doubt. Can
> anyone confirm ?
>
import sys
sys.version
> '2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]'
({'', 1}.items())
> Traceback (most recent call last):
> File "", line 1, in
> AttributeError: 'set' object has no attribute 'items'
I'm not clear on what the bug is supposed to be, as this looks right
to me. Or are you trying to make a dictionary and getting thrown by
the set syntax?
Geremy Condra
--
http://mail.python.org/mailman/listinfo/python-list
Exception Handling in Python 3
I was somewhat surprised to discover that Python 3 no longer allows an
exception to be raised in an except clause (or rather that it reports it
as a separate exception that occurred during the handling of the first).
So the following code:
>>> d = {}
>>> try:
... val = d['nosuch']
... except:
... raise AttributeError("No attribute 'nosuch'")
...
Give the traceback I expected and wanted in Python 2:
Traceback (most recent call last):
File "", line 4, in
AttributeError: No attribute 'nosuch'
but in Python 3.1 the traceback looks like this:
Traceback (most recent call last):
File "", line 2, in
KeyError: 'nosuch'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 4, in
AttributeError: No attribute 'nosuch'
Modifying the code a little allows me to change the error message, but
not much else:
>>> d = {}
>>> try:
... val = d['nosuch']
... except KeyError as e:
... raise AttributeError("No attribute 'nosuch'") from e
...
Traceback (most recent call last):
File "", line 2, in
KeyError: 'nosuch'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "", line 4, in
AttributeError: No attribute 'nosuch'
>>>
In a class's __getattr__() method this means that instead of being able
to say
try:
value = _attrs[name]
except KeyError:
raise AttributeError ...
I am forced to write
if name not in _attrs:
raise AttributeError ...
value = _attrs[name]
which requires an unnecessary second lookup on the attribute name. What
is the correct paradigm for this situation?
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: numpad in idle
thanks, but this doesn't solve the problem, because I need to use the numpad as a cursor, not to enter numbers. cheers, Alex On 24 окт, 16:44, rantingrick wrote: > On Oct 23, 7:41 pm, Jah_Alarm wrote: > > > here's my problem: I'm running IDLE in Ubuntu. For some reason numpad > > buttons do not work. I'm kinda used to this layout. Doesn anyone have > > an idea on how to switch it on? > > Sure, look directly above the number pad and you will see a button > labeled "NumLock". Press that button and you should be golden! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception Handling in Python 3
On Sat, Oct 23, 2010 at 10:01 PM, Steve Holden wrote: > I was somewhat surprised to discover that Python 3 no longer allows an > exception to be raised in an except clause (or rather that it reports it > as a separate exception that occurred during the handling of the first). > Give the traceback I expected and wanted in Python 2: > > Traceback (most recent call last): > File "", line 4, in > AttributeError: No attribute 'nosuch' > > but in Python 3.1 the traceback looks like this: > > Traceback (most recent call last): > File "", line 2, in > KeyError: 'nosuch' > > During handling of the above exception, another exception occurred: > > Traceback (most recent call last): > File "", line 4, in > AttributeError: No attribute 'nosuch' > > Modifying the code a little allows me to change the error message, but > not much else: > What > is the correct paradigm for this situation? There doesn't seem to be one at the moment, although the issue isn't very serious. Your Traceback is merely being made slightly longer/more complicated than you'd prefer; however, conversely, what if a bug was to be introduced into your exception handler? Then you'd likely very much appreciate the "superfluous" Traceback info. Your quandary is due to the unresolved status of the "Open Issue: Suppressing Context" in PEP 3141 (http://www.python.org/dev/peps/pep-3134/ ). I guess you could start a discussion about closing that issue somehow. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
Hello Geremy, The whole point is, is not supposed to be a set; a set literal would end with "})". As you can see, there is no such construct in the string. It's just a dict inside parentheses. Somehow, the parser seems to think it's a set. -- Howe [email protected] On Sun, Oct 24, 2010 at 2:58 AM, geremy condra wrote: > On Sat, Oct 23, 2010 at 9:40 PM, Steve Howe wrote: >> Hello, >> >> This looks like a parser bug, but it's so basic I'm in doubt. Can >> anyone confirm ? >> > import sys > sys.version >> '2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]' > ({'', 1}.items()) >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'set' object has no attribute 'items' > > I'm not clear on what the bug is supposed to be, as this looks right > to me. Or are you trying to make a dictionary and getting thrown by > the set syntax? > > Geremy Condra > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
Ok, forget, I found the problem: bad sleeping. Thanks. -- Howe [email protected] On Sun, Oct 24, 2010 at 3:31 AM, Steve Howe wrote: > Hello Geremy, > > The whole point is, is not supposed to be a set; a set literal would > end with "})". As you can see, there is no such construct in the > string. > It's just a dict inside parentheses. Somehow, the parser seems to > think it's a set. > > -- > Howe > [email protected] > > > > On Sun, Oct 24, 2010 at 2:58 AM, geremy condra wrote: >> On Sat, Oct 23, 2010 at 9:40 PM, Steve Howe wrote: >>> Hello, >>> >>> This looks like a parser bug, but it's so basic I'm in doubt. Can >>> anyone confirm ? >>> >> import sys >> sys.version >>> '2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]' >> ({'', 1}.items()) >>> Traceback (most recent call last): >>> File "", line 1, in >>> AttributeError: 'set' object has no attribute 'items' >> >> I'm not clear on what the bug is supposed to be, as this looks right >> to me. Or are you trying to make a dictionary and getting thrown by >> the set syntax? >> >> Geremy Condra >> > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
Geremy and the parser are correct - it *is* a set. It would only be a dict if you changed the comma to a colon. regards Steve On 10/24/2010 1:31 AM, Steve Howe wrote: > Hello Geremy, > > The whole point is, is not supposed to be a set; a set literal would > end with "})". As you can see, there is no such construct in the > string. > It's just a dict inside parentheses. Somehow, the parser seems to > think it's a set. > > -- > Howe > [email protected] > > > > On Sun, Oct 24, 2010 at 2:58 AM, geremy condra wrote: >> On Sat, Oct 23, 2010 at 9:40 PM, Steve Howe wrote: >>> Hello, >>> >>> This looks like a parser bug, but it's so basic I'm in doubt. Can >>> anyone confirm ? >>> >> import sys >> sys.version >>> '2.7.0+ (r27:82500, Sep 15 2010, 18:14:55) \n[GCC 4.4.5]' >> ({'', 1}.items()) >>> Traceback (most recent call last): >>> File "", line 1, in >>> AttributeError: 'set' object has no attribute 'items' >> >> I'm not clear on what the bug is supposed to be, as this looks right >> to me. Or are you trying to make a dictionary and getting thrown by >> the set syntax? >> >> Geremy Condra >> -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 parser bug on syntax for set literals ?
In article
,
Steve Howe wrote:
> The whole point is, is not supposed to be a set; a set literal would
> end with "})". As you can see, there is no such construct in the
> string.
> It's just a dict inside parentheses. Somehow, the parser seems to
> think it's a set.
>>> type({'', 1})
>>> type({'': 1})
--
Ned Deily,
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Exception Handling in Python 3
On 10/24/2010 1:26 AM, Chris Rebert wrote: >> I was somewhat surprised to discover that Python 3 no longer allows an >> > exception to be raised in an except clause (or rather that it reports it >> > as a separate exception that occurred during the handling of the first). > [snip] >> > What >> > is the correct paradigm for this situation? > There doesn't seem to be one at the moment, although the issue isn't > very serious. Your Traceback is merely being made slightly longer/more > complicated than you'd prefer; however, conversely, what if a bug was > to be introduced into your exception handler? Then you'd likely very > much appreciate the "superfluous" Traceback info. > > Your quandary is due to the unresolved status of the "Open Issue: > Suppressing Context" in PEP 3141 > (http://www.python.org/dev/peps/pep-3134/ ). I guess you could start a > discussion about closing that issue somehow. You're right about the issue not being serious, (and about the possible solution, though I don't relish a lengthy discussion on python-dev) but it does seem that there ought to be some way to suppress that __context__. From the user's point of view the fact that I am raising AttributeError because of some implementation detail of __getattr__() is exposing *way* too much information. I even tried calling sys.exc_clear(), but alas that doesn't help :( regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception Handling in Python 3
In message , Steve Holden wrote: > I was somewhat surprised to discover that Python 3 no longer allows an > exception to be raised in an except clause (or rather that it reports it > as a separate exception that occurred during the handling of the first). So what exactly is the problem? Exceptions are so easy to get wrong, it’s just trying to report more info in a complicated situation to help you track down the problem. Why is that bad? > In a class's __getattr__() method this means that instead of being able > to say > > try: > value = _attrs[name] > except KeyError: > raise AttributeError ... > > I am forced to write > > if name not in _attrs: > raise AttributeError ... > value = _attrs[name] I don’t see why. Presumably if you caught the exception in an outer try- except clause, you would pick up your AttributeError, not the KeyError, right? Which is what you want, right? -- http://mail.python.org/mailman/listinfo/python-list
