Re: Flexible string representation, unicode, typography, ...
On Wed, 29 Aug 2012 08:43:05 -0700, wxjmfauth wrote: > I can hit the nail a little more. > I have even a better idea and I'm serious. > > If "Python" has found a new way to cover the set of the Unicode > characters, why not proposing it to the Unicode consortium? Because the implementation of the str datatype in a programming language has nothing to do with the Unicode consortium. You might as well propose it to the International Union of Railway Engineers. > Unicode has already three schemes covering practically all cases: memory > consumption, maximum flexibility and an intermediate solution. And Python's solution uses those: UCS-2, UCS-4, and UTF-8. The only thing which is innovative here is that instead of the Python compiler declaring that "all strings will be stored in UCS-2", the compiler chooses an implementation for each string as needed. So some strings will be stored internally as UCS-4, some as UCS-2, and some as ASCII (which is a standard, but not the Unicode consortium's standard). (And possibly some as UTF-8? I'm not entirely sure from reading the PEP.) There's nothing radical here, honest. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I get logging.FileHandler to close the file on each emit?
rikardhul...@gmail.com writes: > I use logging.FileHandler (on windows) and I would like to be able to delete > the file while the process is running and have it create the file again on > next log event. > > On windows (not tried linux) this is not possible because the file is locked > by the process, can I get it to close the file after each log event? > > If not, would the correct thing to do be to write my own LogHandler with this > behavior? Zope is using Python's "logging" module and wants to play well with log rotating (start a new logfile, do something with the old log file (compress, rename, remove)). It does this by registering a signal handler which closes its logfiles when the corresponding signal is received. Maybe, you can do something like this. Signal handling under Windows is limited, but maybe you find a usable signal under Windows (Zope is using "SIGUSR1"). -- http://mail.python.org/mailman/listinfo/python-list
Re: Are the property Function really useful?
writes: > Are the property Function really useful? Someone invested time to implement/document/test it. Thus, there are people who have use cases for it... > Where can i use the property function? You can use it when you have parameterless methods which you want to access as if they were simple attributes: i.e. "obj.m" instead of "obj.m()". To phrase is slightly differently: the "property" function allows you to implement "computed" (rather than "stored") attributes. You may find this feature uninteresting: fine, do not use it... However, there are cases where it is helpful, e.g.: You have a base class "B" with an attribute "a". Now, you want to derive a class "D" from "B" where "a" is not fixed but must be computed from other attributes. The "Eiffel" programming language even stipulates that attributes and parameterless methods are essentially the same and application of the "property" function is implicit in "Eiffel" for parameterless methods: to hide implementation details. As you see, "property" can be highly valued ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: [pyxl] xlrd-0.8.0 .xlsx formatting_info=True not implemented
On 30/08/2012 03:57, python-ex...@raf.org wrote: hopefully the intention that xlrd not support formats in xlsx files will change one day into an intention to support them. :-) The intention is there, sadly the time to work on it is not. John Machin would be the person best placed to do the work, if anyone fancies sponsoring the work, he might be able to direct more time to it.. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: How to program test(expr) ?
Am 29.08.2012 17:04, schrieb Franck Ditter: I use Python 3.2.3 + Idle. Is it possible to program test(e) which takes an expression e and whose execution produces at the toplevel an echo of e and the effects and result of its evaluation ? Yes, the key to this is using a lambda expression. # file foo.py def foo(x) : print('x =',x) return x+1 test(foo(5)) def test(exp): global print print_saved = print print = my_print res = exp() print = print_saved return res test(lambda: foo(5)) The idea is to run the callable expression inside a modified environment, in the sketch above it intercepts the calles to print() using a separate my_print() function. Note that the calling syntax is slightly different than the one you would have wanted, don't know if that is important. Things I'll leave to you: - exception handling - exception forwarding - intercepting other environment accesses - putting all that into a context manager :) Good luck! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
Le jeudi 30 août 2012 08:55:01 UTC+2, Steven D'Aprano a écrit : You are right. But as soon as you introduce artificially a "latin-1" bottleneck, all this machinery just become useless. This flexible representation is working absurdly. It optimizes the characters you are not using (in one sense), it defaults to a non optimized form for the characters you wish to use. Pick up a random text and see the probability this text match the most optimized case 1 char / 1 byte, practically never. If a user will use exclusively latin-1, she/he is better served by using a dedicated tool for "latin-1" If a user will comfortably work with Unicode, she/he is better served by using one of this tools which is using properly one of the available Unicode schemes. In a funny way, this is what Python was doing and it performs better! (Enough for today, *I* should spend my spare time to toy with Go, this discussion gave *me* the wish to dive in it again). jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
On Thu, Aug 30, 2012 at 6:51 PM, wrote: > Pick up a random text and see the probability this > text match the most optimized case 1 char / 1 byte, > practically never. Only if you talk about a huge document. Try, instead, every string ever used in a Python script. Practically always. But I'm wasting my time saying this again. It's been said by multiple people multiple times. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Python Logging: Specifying converter attribute of a log formatter in config file
I'd like to have all timestamps in my log file to be UTC timestamp. When specified through code, this is done as follows: myHandler = logging.FileHandler('mylogfile.log', 'a') formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-15s:%(lineno)4s: %(message)-80s') formatter.converter = time.gmtime myLogger = logging.getLogger('MyApp') myLogger.addHandler(myHandler) I'd like to move away from the above 'in-code' configuration to a config file based mechanism. Here's the config file section for the formatter: [handler_MyLogHandler] args=("mylogfile.log", "a",) class=FileHandler level=DEBUG formatter=simpleFormatter Now, how do I specify the converter attribute (time.gmtime) in the above section? -- http://mail.python.org/mailman/listinfo/python-list
class object's attribute is also the instance's attribute?
when i write code like this: class A(object): d = 'it is a doc.' t = A() print t.__class__.d print t.d the output is same. so it means class object's attribute is also the instance's attribute. is it right? i can not understand it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
In article <503f0e45$0$9416$c3e8da3$76491...@news.astraweb.com>, Steven D'Aprano wrote: > The only thing which is innovative here is that instead of the Python > compiler declaring that "all strings will be stored in UCS-2", the > compiler chooses an implementation for each string as needed. So some > strings will be stored internally as UCS-4, some as UCS-2, and some as > ASCII (which is a standard, but not the Unicode consortium's standard). Is the implementation smart enough to know that x == y is always False if x and y are using different internal representations? -- http://mail.python.org/mailman/listinfo/python-list
Re: Are the property Function really useful? yes.
On 08/29/2012 07:46 AM, Dave Angel wrote: > On 08/29/2012 06:32 AM, levinie...@gmail.com wrote: > > I was trying to point out that your question was empty (no content in the message). Mark also apparently saw an empty message. However, now that Dieter has responded, with apparent quotes from your message, i see what the problem was. You composed an html message and sent it to a text forum. Many people make that mistake, and the problem it usually causes is that source code indentation is messed up. However, most mail programs send a text part as well, and that's what we see. In your case, the text part was empty, so I saw nothing but the subject line. Please tell your mail program to compose TEXT message, not html, or this problem could occur again. Now to your question. >> >> Where can i use the property function? In some languages, you get computed properties by writing getter and setter functions, with names to match. Python lets you hide the fact that the "property" is hidden, by letting you use ordinary syntax to access it. For example, suppose you had a Point class, which stored the x and y coordinates of a point on a plane. Suppose also that sometimes you wanted to use polar coordinates. You might like the user of the class to just interchangeably use the real attributes and the computed ones, without having to use parentheses on some of them. (untested) class Point(object): def __init__(self, x, y): self.x = x self.y = y @property def radius(self): return self.sqrt(self.x * self.x, self.y * self.y) @property def theta(self): return math.atan(self.x, self.y) Now, once you have a Point instance, you can use all four attributes pretty much interchangeably. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 08/30/2012 06:55 AM, 陈伟 wrote: > when i write code like this: > > class A(object): > > d = 'it is a doc.' > > > t = A() > > print t.__class__.d > print t.d > > the output is same. > > so it means class object's attribute is also the instance's attribute. is it > right? i can not understand it. In your example, you have no instance attribute. So when you use the syntax to fetch one, the interpreter looks first at the instance, doesn't find it, then looks in the class, and does. That is documented behavior. Some people use it to provide a kind of default value for instances, which can be useful if most instances need the same value, but a few want to overrride it. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Beginners question
Hello I'm slowly teaching myself python so apologies if this is a dumb question. but something has confused me with the os.stat() function: >>> s = os.stat(".") >>> print s posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, st_u id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, st _ctime=1346327754) What sort of object is posix.stat_result? Its not a dictionary or list or a class object as far as I can tell. Thanks for any help. B2003 -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On 30/08/2012 12:54, boltar2003@boltar.world wrote: Hello I'm slowly teaching myself python so apologies if this is a dumb question. but something has confused me with the os.stat() function: s = os.stat(".") print s posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, st_u id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, st _ctime=1346327754) What sort of object is posix.stat_result? Its not a dictionary or list or a class object as far as I can tell. Thanks for any help. What don't you ask Python? I'm sure you'' get something like this: >>> type(s) In other words, it's an instance of the class "stat_result" as defined in the file "posix.py". On my system I get "" because I'm using Windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
Am 30.08.2012 12:55, schrieb 陈伟: class A(object): d = 'it is a doc.' t = A() print t.__class__.d print t.d the output is same. You could go even further: print id(t.__class__.d) print id(t.d) which should show you that they are not just equal but identical. so it means class object's attribute is also the instance's attribute.is it right? Yes. This is even useful sometimes: class Point(object): x = 0 y = 0 This will cause every Point to have two attributes x and y that have a default value 0. Note that setting this attribute on an instance does not change the class' attribute, just in that that was what confused you. However, if the attribute references a mutable type (e.g. a list) this can cause problems because the instance (see id() above) is the same and thus modifications affect both the class and all instances. Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
In article , MRAB wrote: > What don't you ask Python? I'm sure you'' get something like this: > > >>> type(s) > BTW, this points out one of the really powerful aspects of Python. The combination of introspection and a handy interactive interpreter makes it easy to "just ask the computer". It's often faster to play around with dir(), type(), and pprint() than to find what you're looking for in the docs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thursday, August 30, 2012 1:54:08 PM UTC+2, (unknown) wrote: > Hello > > > > I'm slowly teaching myself python so apologies if this is a dumb question. > > but something has confused me with the os.stat() function: > > > > >>> s = os.stat(".") > > >>> print s > > posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, > st_u > > id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, > st > > _ctime=1346327754) > > > > What sort of object is posix.stat_result? Its not a dictionary or list or a > > class object as far as I can tell. Thanks for any help. > > > > B2003 Hi, So let's try to figure this out. First of all, we can ask Python what object it is. >>> s = os.stat('.') >>> type(s) posix.stat_result So it seems to be a custom type. However types can inherit from builtins like list, tuple and dict, so maybe it still is a dict or a tuple. Let's ask Python again: >>> isinstance(s, dict) False >>> isinstance(s, (tuple, list)) False Ok. So it is neither a list (tuple) nor a dict. So without reverting to the source code, it is probably save to say that the result is a custom class where the attributes can be accessed by the dot '.' notation. This is confirmed when you do: >>> dir(s) .. '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields', 'st_atime', 'st_blksize', 'st_blocks', 'st_ctime', 'st_dev', 'st_gid', 'st_ino', 'st_mode', 'st_mtime', 'st_nlink', 'st_rdev', 'st_size', 'st_uid'] For example: >>> print s.st_size 4096 In case of Linux I think that the result of os.stat(..) is a wrapping of a C struct (a class with only attributes and no methods). A small additional remark. Besides being a real dict or list (by means of inheritance), custom class can also implement the interface (__getitem__ etc.). If you want to know if an object implements this interface you could use the types defined in the 'abc' and 'collections' standard modules. So instead of checking if a type is a dict like this: >>> isinstance(s, dict) you could also check if it implements the dict interface: >>> isinstance(s, collections.MutableMapping) # or similar Regards, Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On 08/30/2012 07:54 AM, boltar2003@boltar.world wrote: > Hello > > I'm slowly teaching myself python so apologies if this is a dumb question. > but something has confused me with the os.stat() function: > s = os.stat(".") print s > posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, > st_u > id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, > st > _ctime=1346327754) > > What sort of object is posix.stat_result? Its not a dictionary or list or a > class object as far as I can tell. Thanks for any help. > posix.stat_result is a class, and s is an instance of that class. You can see that by typing type(s). But you're wondering how print generated all that stuff about the s instance. You can start to learn that with dir(s), which shows the available attributes. All those attributes that have leading and trailing double-underscores are called "special attributes," or "special methods." In particular notice __str__(), which is a method provided for your convenience. print will call that if it's available, when you try to print an instance.It also masquerades as a tuple using __getitem__() and other special methods. Normal use of the instance is done by the attributes like s.st_atime and s.st_size, or by using the object as a tuple. (using the square brackets to fetch individual items or a range of items) You can get more documentation directly from s by simply typing help(s) and/or help(os.stat) Or you can go to the web docs, http://docs.python.org/library/os.html and search downward for os.stat (this link is currently for Python 2.7.3) -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, Aug 30, 2012 at 9:54 PM, wrote: > What sort of object is posix.stat_result? Its not a dictionary or list or a > class object as far as I can tell. Thanks for any help. There's some cool things you can do here. (Note that I'm testing this on a Windows box, so it's marginally different.) >>> import os >>> st=os.stat(".") >>> st nt.stat_result(st_mode=16895, st_ino=36873221949168842, st_dev=0, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1346329853, st_mtime=1311543704, st_ctime=1306188101) >>> help(st) You'll get a couple of pages of help text about the object class that the stat object is. You can do this with any object at all. Notably in this case: | This object may be accessed either as a tuple of |(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) | or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on. So, for instance: >>> st[0] 16895 >>> st.st_mode 16895 Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On Thursday, August 30, 2012 12:55:25 PM UTC+2, 陈伟 wrote: > when i write code like this: > > > > class A(object): > > > > d = 'it is a doc.' > > > > > > t = A() > > > > print t.__class__.d > > print t.d > > > > the output is same. > > > > so it means class object's attribute is also the instance's attribute. is it > right? i can not understand it. I think the best way is to think of it as a global attribute restricted to the class A. Note that you even don't need an instance to get the value of the attribute. You can directly get it from the class itself. >>> class A(object): d = 'my attribute' >>> A.d 'my attribute' >>> aobj = A() >>> aobj.d 'my attribute' Note that if you change 'd' it will change for all instances! >>> bobj = A() >>> bobj.d 'my attribute' >>> A.d = 'oops...attribute changed' >>> aobj.d 'oops...attribute changed' >>> bobj.d 'oops...attribute changed' If you want attributes to be local to the instance, you have to define them in the __init__ section of the class like this: class A(object): def __init__(self): d = 'my attribute' >>> aobj = A() >>> bobj = A() >>> aobj.d 'my attribute' >>> bobj.d 'my attribute' >>> aobj.d = 'oops...attribute changed' >>> aobj.d 'oops...attribute changed' >>> bobj.d 'my attribute' Regards, Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On Thu, 30 Aug 2012 05:34:51 -0700 (PDT), Marco Nawijn wrote: If you want attributes to be local to the instance, you have to define them in the __init__ section of the class like this: class A(object): def __init__(self): d = 'my attribute' Except that in this case you'd need to do: self.d = 'my attribute' Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
在 2012年8月30日星期四UTC+8下午7时54分35秒,Dave Angel写道: > On 08/30/2012 06:55 AM, 陈伟 wrote: > > > when i write code like this: > > > > > > class A(object): > > > > > > d = 'it is a doc.' > > > > > > > > > t = A() > > > > > > print t.__class__.d > > > print t.d > > > > > > the output is same. > > > > > > so it means class object's attribute is also the instance's attribute. is > > it right? i can not understand it. > > > > In your example, you have no instance attribute. So when you use the > > syntax to fetch one, the interpreter looks first at the instance, > > doesn't find it, then looks in the class, and does. That is documented > > behavior. Some people use it to provide a kind of default value for > > instances, which can be useful if most instances need the same value, > > but a few want to overrride it. > > > > -- > > > > DaveA thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, 30 Aug 2012 13:14:57 +0100 MRAB wrote: >On 30/08/2012 12:54, boltar2003@boltar.world wrote: >> Hello >> >> I'm slowly teaching myself python so apologies if this is a dumb question. >> but something has confused me with the os.stat() function: >> > s = os.stat(".") > print s >> posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, >st_u >> id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, >st_mtime=1346327754, st >> _ctime=1346327754) >> >> What sort of object is posix.stat_result? Its not a dictionary or list or a >> class object as far as I can tell. Thanks for any help. >> >What don't you ask Python? I'm sure you'' get something like this: > > >>> type(s) > Umm , no I don't. >>> s = os.stat(".") >>> print s posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, st_u id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, st _ctime=1346327754) >>> type(s) Which isn't terrible helpful. >In other words, it's an instance of the class "stat_result" as defined >in the file "posix.py". If its a class , why is it when I create my own class I get a completely different output with print and type? >>> >>> class foo(object): .. def __init__(self): .. pass .. >>> f=foo() >>> print f <__main__.foo object at 0xb743956c> >>> type(f) B2003 -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Thursday, August 30, 2012 12:55:14 AM UTC-4, Dennis Lee Bieber wrote: > > How many bytes did it claim to send? > 11, which is what I expected. But I changed the byte value to 16 (because I was having trouble getting single digit hex values working in the command) and sent this command: >>> for x in range(0,500): ep.write(b'\x16\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF') it respond with 500 17's and prints a black bar! So it looks like whatever concern you had with using encode was coming to fruition. > > That's the easy one -- \x in a string introduces an 8-bit byte value > > -- so only two hex digits well be read. The "A" is interpreted as > > regular text. Interesting, so what if I only wanted to send 4bits as a hex value? Also can I somehow throw in some binary alongside of hex? At some point in my program I'm going to need to send some commands preferably in hex along with the binary image data. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, 30 Aug 2012 08:25:33 -0400 Dave Angel wrote: >You can get more documentation directly from s by simply typing >help(s) and/or help(os.stat) I didn't know about help(). Thanks! B2003 -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, Aug 30, 2012 at 10:50 PM, wrote: > On Thu, 30 Aug 2012 13:14:57 +0100 > MRAB wrote: >>What don't you ask Python? I'm sure you'' get something like this: >> >> >>> type(s) >> > > Umm , no I don't. > type(s) > > > Which isn't terrible helpful. That's actually the same thing, except for a slight difference between Python 2 and Python 3. > If its a class , why is it when I create my own class I get a completely > different output with print and type? > class foo(object): > .. def __init__(self): > .. pass > .. f=foo() print f > <__main__.foo object at 0xb743956c> type(f) > Yep, you're using Python 2. A few things are subtly different. Unless you have good reason not to, do consider moving to Python 3; all sorts of things are easier. Python 2 is basically not being developed any more. http://www.python.org/dev/peps/pep-0404/ Alternatively, accept that what people are going to quote to you here may be slightly different from what you see. In any case, Python's introspection facilities and help() features are available on both branches, so most of what has been said in this thread still applies. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
Am 30.08.2012 13:54, schrieb boltar2003@boltar.world: s = os.stat(".") print s posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, st_u id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, st _ctime=1346327754) What sort of object is posix.stat_result? Use the type() function to find out. I guess that this is a named tuple, which is a tuple where the attributes are not indexed but have a name, see the documentation for the namedtuple() function from the collections library. Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On 08/30/2012 08:50 AM, boltar2003@boltar.world wrote: > On Thu, 30 Aug 2012 13:14:57 +0100 > MRAB wrote: > > If its a class , why is it when I create my own class I get a completely > different output with print and type? > class foo(object): > .. def __init__(self): > .. pass > .. f=foo() print f > <__main__.foo object at 0xb743956c> You get that because you didn't provide a __str__() method in your class. As i said in my other message, posix.stat_result is providing that capability for your debugging convenience. There's no requirement to provide it, but that's why the difference. type(f) > > > > I haven't discovered why sometimes the type output shows type instead of class. There are other ways of defining classes, however, and perhaps this is using one of them. Still, it is a class, and stat() is returning an instance of that class. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, 30 Aug 2012 23:06:34 +1000 Chris Angelico wrote: >Yep, you're using Python 2. A few things are subtly different. Unless >you have good reason not to, do consider moving to Python 3; all sorts Noted. Thanks. B2003 -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 30/08/12 14:34:51, Marco Nawijn wrote: > Note that if you change 'd' it will change for all instances! That depends on how you change it. bobj = A() bobj.d > 'my attribute' > A.d = 'oops...attribute changed' Here you change the attribute on the class. That will affect all instances: aobj.d > 'oops...attribute changed' > bobj.d > 'oops...attribute changed' You can also set the attribute on an instance: >>> bobj.d = 'For bobj only' >>> bobj.d 'For bobj only' aobj.d > 'oops...attribute changed' So, if you specifically change it on one instance, thenit won't change on other instances of the same class. > If you want attributes to be local to the instance, you have > to define them in the __init__ section of the class like this: That's a good idea, but it's not required. You can set them later, as shown above. > class A(object): > >def __init__(self): > d = 'my attribute' That will just set the global variable d. You want to set the instance attribute: self.d = 'my attribute' aobj = A() bobj = A() > aobj.d > 'my attribute' Note that aobj.d will not find the global variable d, if neither the instance, nor the class nor any of the base classes have that attribute. I don't know where this 'my attribute' comes from, but it's not the instance attribute you tried to set in the __init__ method. Maybe your class A still has a class attribute with that value from an earlier experiment. Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thursday, August 30, 2012 3:15:03 PM UTC+2, Ulrich Eckhardt wrote: > Am 30.08.2012 13:54, schrieb boltar2003@boltar.world: > > s = os.stat(".") > > print s > > > posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, > > st_u > > > id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, > > st_mtime=1346327754, st > > > _ctime=1346327754) > > > > > > What sort of object is posix.stat_result? > > > > Use the type() function to find out. I guess that this is a named tuple, > > which is a tuple where the attributes are not indexed but have a name, > > see the documentation for the namedtuple() function from the collections > > library. > > > > Uli It is not a namedtuple. Because a namedtuple "is" a tuple and therefore isinstance(s, tuple) would have returned True. >>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') >>> p = Point(10,2) >>> isinstance(p, tuple) True -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On Thu, 30 Aug 2012 09:23:03 -0400, Dave Angel wrote: I haven't discovered why sometimes the type output shows type instead of class. There are other ways of defining classes, however, and perhaps this is using one of them. Still, it is a class, and stat() is returning an instance of that class. Builtin types show as type and classes defined in python show as class (even if they inherit from builtin types). Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote: > On 30/08/12 14:34:51, Marco Nawijn wrote: > > > > > Note that if you change 'd' it will change for all instances! > > > > That depends on how you change it. > > > > bobj = A() > > bobj.d > > > 'my attribute' > > > > > A.d = 'oops...attribute changed' > > > > Here you change the attribute on the class. > > That will affect all instances: > > > > aobj.d > > > 'oops...attribute changed' > > > > > bobj.d > > > 'oops...attribute changed' > > > > You can also set the attribute on an instance: > > > > >>> bobj.d = 'For bobj only' > > >>> bobj.d > > 'For bobj only' > > aobj.d > > > 'oops...attribute changed' > > > > So, if you specifically change it on one instance, thenit won't > > change on other instances of the same class. > > > > > If you want attributes to be local to the instance, you have > > > to define them in the __init__ section of the class like this: > > > > That's a good idea, but it's not required. You can set them > > later, as shown above. > > > > > > > class A(object): > > > > > >def __init__(self): > > > d = 'my attribute' > > > > That will just set the global variable d. > > You want to set the instance attribute: > > > > self.d = 'my attribute' > > > > aobj = A() > > bobj = A() > > > > > aobj.d > > > 'my attribute' > > > > Note that aobj.d will not find the global variable d, > > if neither the instance, nor the class nor any of the > > base classes have that attribute. > > > > I don't know where this 'my attribute' comes from, but > > it's not the instance attribute you tried to set in the > > __init__ method. Maybe your class A still has a class > > attribute with that value from an earlier experiment. > > > > > > Hope this helps, > > > > -- HansM Learned my lesson today. Don't assume you know something. Test it first ;). I have done quite some programming in Python, but did not know that class attributes are still local to the instances. It is also a little surprising I must say. I always considered them like static variables in C++ (not that I am an expert in C++). I knew of course that you don't have to define a local attribute in the __init__ method of a class, but I consider it good style and since the OP is a self claimed newbie I left out the other option. The missing "self" in the code below was a typo class A(object): def __init__(self): d = 'my attribute' # should be self.d Regards, Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 08/30/2012 10:11 AM, Marco Nawijn wrote: > On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote: >> >> > Learned my lesson today. Don't assume you know something. Test it first ;). I > have done quite some programming in Python, but did not know that class > attributes are still local to the instances. They're not. They're just visible to the instances, except where the instance has an instance attribute of the same name. Don't be confused by dir(), which shows both instance and class attributes. Please show me an example where you think you observe each instance getting a copy of the class attribute. There's probably some other explanation. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On Thursday, August 30, 2012 4:30:59 PM UTC+2, Dave Angel wrote: > On 08/30/2012 10:11 AM, Marco Nawijn wrote: > > > On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote: > > >> > > >> > > > Learned my lesson today. Don't assume you know something. Test it first ;). > > I have done quite some programming in Python, but did not know that class > > attributes are still local to the instances. > > > > They're not. They're just visible to the instances, except where the > > instance has an instance attribute of the same name. Don't be confused > > by dir(), which shows both instance and class attributes. > > > > Please show me an example where you think you observe each instance > > getting a copy of the class attribute. There's probably some other > > explanation. I don't have an example. It was just what I thought would happen. Consider the following. In a class declaration like this: class A(object): attr_1 = 10 def __init__(self): self.attr_2 = 20 If I instantiated it twice: obj_1 = A() obj_2 = A() For both obj_1 and obj_2 attr_1 equals 10. What I thought would happen after the following statement: obj_1.attr_1 = 12 is that obj_2.attr_1 also equals 12. This is what surprised me a little, that's all. Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
gmail.com> writes: > > Pick up a random text and see the probability this > text match the most optimized case 1 char / 1 byte, > practically never. Funny that you posted a text which does just that: http://mail.python.org/pipermail/python-list/2012-August/629554.html > In a funny way, this is what Python was doing and it > performs better! I honestly suggest you shut up until you have a clue. Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 08/30/2012 10:48 AM, Marco Nawijn wrote: > On Thursday, August 30, 2012 4:30:59 PM UTC+2, Dave Angel wrote: >> On 08/30/2012 10:11 AM, Marco Nawijn wrote: >> >>> On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote: >> >> >> >>> Learned my lesson today. Don't assume you know something. Test it first ;). >>> I have done quite some programming in Python, but did not know that class >>> attributes are still local to the instances. >> >> >> >> They're not. They're just visible to the instances, except where the >> >> instance has an instance attribute of the same name. Don't be confused >> >> by dir(), which shows both instance and class attributes. >> >> >> >> Please show me an example where you think you observe each instance >> >> getting a copy of the class attribute. There's probably some other >> >> explanation. > > I don't have an example. It was just what I thought would happen. Consider > the following. In a class declaration like this: > > class A(object): > attr_1 = 10 > > def __init__(self): >self.attr_2 = 20 > > If I instantiated it twice: > > obj_1 = A() > obj_2 = A() > > For both obj_1 and obj_2 attr_1 equals 10. What I thought would happen after > the following statement: > > obj_1.attr_1 = 12 > > is that obj_2.attr_1 also equals 12. This is what surprised me a little, > that's all. > > Marco > That statement only adds an instance attribute, not modifying the class attribute of the same name. But it does "hide" it from that particular instance. The thing that can be surprising is that if the class attribute is mutable, and you mutate it, rather than assigning it. So for example: class A(object): attr_1 = [10, 9] def __init__(self): self.attr_2 = 20 obj_1 = A() obj_2 = A() obj_1.attr_1.append(3) Then I believe you'll see [10, 9, 3] from both instances. print obj_1.attr_1 print obj_2.attr_1 -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
Am 30.08.2012 15:27, schrieb Marco Nawijn: On Thursday, August 30, 2012 3:15:03 PM UTC+2, Ulrich Eckhardt wrote: Am 30.08.2012 13:54, schrieb boltar2003@boltar.world: What sort of object is posix.stat_result? [...] I guess that this is a named tuple, which is a tuple where the attributes are not indexed but have a name, see the documentation for the namedtuple() function from the collections library. It is not a namedtuple. Because a namedtuple "is" a tuple and therefore isinstance(s, tuple) would have returned True. from collections import namedtuple Point = namedtuple('Point', 'x y') p = Point(10,2) isinstance(p, tuple) True Hi Marco, I don't find anything wrong with what you say, the output formatting from using a type created by namedtuple would have been slightly different indeed. However, I also don't understand the point you're trying to make, in particular why it matters that a namedtuple type is derived from tuple, other than perhaps that access by name is available in addition to access by index. Greetings! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 30/08/12 16:48:24, Marco Nawijn wrote: > On Thursday, August 30, 2012 4:30:59 PM UTC+2, Dave Angel wrote: >> On 08/30/2012 10:11 AM, Marco Nawijn wrote: >>> On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote: >>> Learned my lesson today. Don't assume you know something. Test it first ;). A very important lesson. Next week's lesson will be: if you test it first, then paste it into a message for this forum, then tweak just one unimportant detail, you'll need to test it again. >>> I have done quite some programming in Python, but did not know that class >>> attributes are still local to the instances. >> They're not. They're just visible to the instances, except where the >> instance has an instance attribute of the same name. Don't be confused >> by dir(), which shows both instance and class attributes. >> >> Please show me an example where you think you observe each instance >> getting a copy of the class attribute. There's probably some other >> explanation. > > I don't have an example. It was just what I thought would happen. > Consider the following. In a class declaration like this: > > class A(object): > attr_1 = 10 > > def __init__(self): >self.attr_2 = 20 > > If I instantiated it twice: > > obj_1 = A() > obj_2 = A() > > For both obj_1 and obj_2 attr_1 equals 10. What I thought would happen after > the following statement: > > obj_1.attr_1 = 12 > > is that obj_2.attr_1 also equals 12. This is what surprised me a little, > that's all. The trick is to look at obj_1.__dict__ to see what is defined locally: >>> obj_1 = A() >>> obj_1.__dict__ {'attr_2': 20} >>> obj_1.attr_1 = 12 >>> obj_1.__dict__ {'attr_2': 20, 'attr_1': 12} Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On 30/08/12 14:49:54, Ulrich Eckhardt wrote: > Am 30.08.2012 13:54, schrieb boltar2003@boltar.world: > s = os.stat(".") > print s >> posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, >> st_nlink=2, st_u >> id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, >> st_mtime=1346327754, st >> _ctime=1346327754) >> >> What sort of object is posix.stat_result? > > Use the type() function to find out. I guess that this is a named tuple, > which is a tuple where the attributes are not indexed but have a name, > see the documentation for the namedtuple() function from the collections > library. Named tuples were invented to do this kind of thing. However, stat_result is fairly old, and named tuples had not been invented back then. If named tuples had been invented first, then os.stat would probably have used them. Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Built-in open() with buffering > 1
On 08/26/2012 10:25 AM, Hans Mulder wrote: The algorithm is explained at http://docs.python.org/library/io.html#io.DEFAULT_BUFFER_SIZE Thanks ;) In other words: open() tries to find a suitable size by calling os.stat(your_file).st_blksize and if that fails, it uses io.DEFAULT_BUFFER_SIZE, which is 8192 on my box. Yes, when the parameter `buffering` is a negative integer that is right Whether you call open with buffering=2 or any larger number, does not matter: the buffer size will be the outcome of this algorithm. Mmm, I think it is not right, because in this case the buffer size is not computed but it is the value you assign to the buffering parameter. In fact: >>> f = open('myfile', 'w', buffering=2) >>> f._CHUNK_SIZE = 1 >>> f.write('ab') 2 >>> open('myfile').read() Now two bytes are in the buffer and the buffer is full. If you write another byte, it will not be written in the buffer, because the bytes in the queue will be transferred into the buffer only when they are more than f._CHUNK_SIZE: >>> f.write('c') 1 >>> open('myfile').read() Now, if you write another byte 'd', the chunk 'cd' will be transferred to the buffer, but because it is full, its content 'ab' will be transferred to the disk, and after 'cd' written to the buffer, that still full: >>> f.write('d') 1 >>> open('myfile').read() 'ab' So, the buffer is really of size 2 -- http://mail.python.org/mailman/listinfo/python-list
Basic Question. Deploy new Master/Slave (M/S) datastore
Hi, I had an old and deprecated Master/Slave (M/S) datastore and I trying to pass its content to a new Master/Slave (M/S) datastore as is expained here : https://developers.google.com/appengine/docs/adminconsole/migration#Deploying_Your_New_HRD_Application Where it say I have to : "appcfg.py update myapp/" where have I to type that ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
On Thu, 30 Aug 2012 07:02:24 -0400, Roy Smith wrote: > In article <503f0e45$0$9416$c3e8da3$76491...@news.astraweb.com>, > Steven D'Aprano wrote: > >> The only thing which is innovative here is that instead of the Python >> compiler declaring that "all strings will be stored in UCS-2", the >> compiler chooses an implementation for each string as needed. So some >> strings will be stored internally as UCS-4, some as UCS-2, and some as >> ASCII (which is a standard, but not the Unicode consortium's standard). > > Is the implementation smart enough to know that x == y is always False > if x and y are using different internal representations? But x and y are not necessarily always False just because they have different representations. There may be circumstances where two strings have different internal representations even though their content is the same, so it's an unsafe optimization to automatically treat them as unequal. The closest existing equivalent here is the relationship between ints and longs in Python 2. 42 == 42L even though they have different internal representations and take up a different amount of space. My expectation is that the initial implementation of PEP 393 will be relatively unoptimized, and over the next few releases it will get more efficient. That's usually the way these things go. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexible string representation, unicode, typography, ...
On Thu, Aug 30, 2012 at 2:51 AM, wrote: > But as soon as you introduce artificially a "latin-1" > bottleneck, all this machinery just become useless. How is this a bottleneck? If you removed the Latin-1 encoding altogether and limited the flexible representation to just UCS-2 / UCS-4, I doubt very much that you would see any significant speed gains. The flexibility is the part that makes string creation slower, not the Latin-1 option in particular. > This flexible representation is working absurdly. > It optimizes the characters you are not using (in one > sense), it defaults to a non optimized form for the > characters you wish to use. I'm sure that if you wanted to you could patch Python to use Latin-9 instead. Just be prepared for it to be slower than UCS-2, since it would mean having to encode the code points rather than merely truncating them. > Pick up a random text and see the probability this > text match the most optimized case 1 char / 1 byte, > practically never. Pick up a random text and see that this text matches the next most optimized case, 1 char / 2 bytes: practically always. > If a user will use exclusively latin-1, she/he is better > served by using a dedicated tool for "latin-1" Speaker as a user who almost exclusively uses Latin-1, I strongly disagree. What you're describing is Python 2.x. The user is always almost better served by not having to worry about the full extent of the character set their program might use. That's why we moved to Unicode strings in Python 3 in the first place. > If a user will comfortably work with Unicode, she/he is > better served by using one of this tools which is using > properly one of the available Unicode schemes. > > In a funny way, this is what Python was doing and it > performs better! Seriously, please show us just one *real world* benchmark in which Python 3.3 performs demonstrably worse than Python 3.2. All you've shown so far is this one microbenchmark of string creation that is utterly irrelevant to actual programs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Question. Deploy new Master/Slave (M/S) datastore
On 30/08/2012 16:51, Ylodis wrote: Hi, I had an old and deprecated Master/Slave (M/S) datastore and I trying to pass its content to a new Master/Slave (M/S) datastore as is expained here : https://developers.google.com/appengine/docs/adminconsole/migration#Deploying_Your_New_HRD_Application Where it say I have to : "appcfg.py update myapp/" where have I to type that ? The facetious answer is the keyboard as this isn't really a Python question :) I haven't looked at the link but I assume you need a console or terminal window for your OS, that's cmd for Windows for which you might need administrator privileges as I've no idea what you're doing. -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Question. Deploy new Master/Slave (M/S) datastore
I am trying to use a Google public storage that is managed in python. I do web developement, I have very litle idea about python, english is not my natural language and as you can see, I am very lost. I do not even now which group cold help me. The details of what I want to do are in the link. -- http://mail.python.org/mailman/listinfo/python-list
mailbox.mbox Status/X-Status flags RFC?
Playing around with mailbox.mbox, I noticed the flag get split across Status/X-Status headers. I dug into the source and read at [1] to see the *how* but I'm curious as to the *why*. When I pulled up RFC-4155[2] (mbox), it didn't seem to mention anything about the Status/X-Status stuff, and the MaildirMessage stores flags differently (and with different meanings). Anybody have some insight (or an RFC document) that would help this make sense to me? Thanks, -tkc [1] http://docs.python.org/library/mailbox.html#mboxmessage [2] http://tools.ietf.org/html/rfc4155 -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
On 30 August 2012 15:11, Marco Nawijn wrote: > > > Learned my lesson today. Don't assume you know something. Test it first > ;). I have done quite some programming in Python, but did not know that > class attributes are still local to the instances. It is also a little > surprising I must say. I always considered them like static variables in > C++ (not that I am an expert in C++). > Class attributes are analogous to static variables in C++ provided you only ever assign to them as an attribute of the class. >>> class A(object): ... static = 5 ... >>> a = A() >>> a.static 5 >>> A.static 5 >>> b = A() >>> b.static 5 >>> A.static = 10 >>> a.static 10 >>> b.static 10 An instance attribute with the same name as a class attribute hides the class attribute for that instance only. >>> b.static = -1 >>> a.static 10 >>> b.static -1 >>> del b.static >>> b.static 10 This is analogous to having a local variable in a function that hides a module level variable with the same name: x = 10 def f1(): x = 4 print(x) def f2(): print(x) f2() # 10 f1() # 4 f2() # still 10 If you want f1 to modify the value of x seen by f2 then you should explicitly declare x as global in f1. Likewise if you want to modify an attribute for all instances of a class you should explicitly assign to the class attribute rather than an instance attribute. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Question. Deploy new Master/Slave (M/S) datastore
On 8/30/2012 11:51 AM, Ylodis wrote: Hi, I had an old and deprecated Master/Slave (M/S) datastore and I trying to pass its content to a new Master/Slave (M/S) datastore as is expained here : https://developers.google.com/appengine/docs/adminconsole/migration#Deploying_Your_New_HRD_Application Where it say I have to : "appcfg.py update myapp/" where have I to type that ? I have not used app engine, but ... Since the action needs to happen on the Google servers, rather than on your machine, I would expect that there should be a text box in the Administration Console (looking above Deploying Your New ... . -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginners question
On 8/30/2012 9:30 AM, Oscar Benjamin wrote: On Thu, 30 Aug 2012 09:23:03 -0400, Dave Angel wrote: I haven't discovered why sometimes the type output shows type instead of class. There are other ways of defining classes, however, and perhaps this is using one of them. Still, it is a class, and stat() is returning an instance of that class. Builtin types show as type and classes defined in python show as class (even if they inherit from builtin types). Only in 2.x, and this goes back to the old user class system, which the OP should not have to learn about. >>> type(1) -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Making sense of a traceback from py2exe
Not sure where the best place to post this is. My app uses wxpython, matplotlib. I'm running Python 2.7 on Windows 7. I have a script app.py that I'm trying to turn into app.exe using py2exe. The exe runs fine on the pc that it was compiled on but on another Win7 machine I get something like the following in the app.exe.log: Traceback (most recent call last): File "app.py", line 1951, in File "wx\_core.pyo", line 7981, in __init__ File "wx\_core.pyo", line 7555, in _BootstrapApp File "app.py", line 1944, in OnInit File "app.py", line 1811, in __init__ File "matplotlib\backends\backend_wxagg.pyo", line 59, in draw File "matplotlib\backends\backend_agg.pyo", line 401, in draw File "matplotlib\artist.pyo", line 55, in draw_wrapper File "matplotlib\figure.pyo", line 884, in draw File "matplotlib\artist.pyo", line 55, in draw_wrapper File "matplotlib\axes.pyo", line 1983, in draw File "matplotlib\artist.pyo", line 55, in draw_wrapper File "matplotlib\text.pyo", line 526, in draw File "matplotlib\text.pyo", line 309, in _get_layout File "matplotlib\backends\backend_agg.pyo", line 179, in get_text_width_height_descent File "matplotlib\mathtext.pyo", line 2974, in parse File "matplotlib\mathtext.pyo", line 2352, in parse File "matplotlib\pyparsing.pyo", line 1048, in parseString File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2559, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2307, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2679, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2307, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2756, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2714, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2373, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2559, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2416, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2559, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2559, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2416, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2293, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2756, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2559, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2373, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache File "matplotlib\pyparsing.pyo", line 2416, in parseImpl File "matplotlib\pyparsing.pyo", line 981, in _parseCache File "matplotlib\pyparsing.pyo", line 950, in _parseNoCache File "matplotlib\mathtext.pyo", line 2469, in symbol File "matplotlib\mathtext.pyo", line 1312, in __init__ File "matplotlib\mathtext.pyo", line 1319, in _update_metrics File "matplotlib\mathtext.pyo", line 485, in get_metrics File "matplotlib\mathtext.pyo", line 618, in _get_info File "matplotlib\mathtext.pyo", line 720, in _get_glyph KeyError: 98 Traceback (most recent call last): File "wx\_core.pyo", line 14669, in File "app.py", line 826, in _in
Re: Flexible string representation, unicode, typography, ...
On 8/30/2012 12:00 PM, Steven D'Aprano wrote: On Thu, 30 Aug 2012 07:02:24 -0400, Roy Smith wrote: In article <503f0e45$0$9416$c3e8da3$76491...@news.astraweb.com>, Steven D'Aprano wrote: The only thing which is innovative here is that instead of the Python compiler declaring that "all strings will be stored in UCS-2", the compiler chooses an implementation for each string as needed. So some strings will be stored internally as UCS-4, some as UCS-2, and some as ASCII (which is a standard, but not the Unicode consortium's standard). Is the implementation smart enough to know that x == y is always False if x and y are using different internal representations? Yes, after checking lengths, and in same circumstances, x != y is True. From http://hg.python.org/cpython/file/ab6ab44921b2/Objects/unicodeobject.c PyObject * PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) { int result; if (PyUnicode_Check(left) && PyUnicode_Check(right)) { PyObject *v; if (PyUnicode_READY(left) == -1 || PyUnicode_READY(right) == -1) return NULL; if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) || PyUnicode_KIND(left) != PyUnicode_KIND(right)) { if (op == Py_EQ) { Py_INCREF(Py_False); return Py_False; } if (op == Py_NE) { Py_INCREF(Py_True); return Py_True; } } ... KIND is 1,2,4 bytes/char 'a in s' is also False if a chars are wider than s chars. If s is all ascii, s.encode('ascii') or s.encode('utf-8') is a fast, constant time operation, as I showed earlier in this discussion. This is one thing that is much faster in 3.3. Such things can be tested by timing with different lengths of strings, where the initial string creation is done in setup code rather than in the repeated operation code. But x and y are not necessarily always False just because they have different representations. There may be circumstances where two strings have different internal representations even though their content is the same, so it's an unsafe optimization to automatically treat them as unequal. I am sure that str objects are always in canonical form once visible to Python code. Note that unready (non-canonical) objects are rejected by the rich comparison function. My expectation is that the initial implementation of PEP 393 will be relatively unoptimized, The initial implementation was a year ago. At least three people have expended considerable effort improving it since, so that the slowdown mentioned in the PEP has mostly disappeared. The things that are still slower are somewhat balanced by things that are faster. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Making sense of a traceback from py2exe
On Thu, Aug 30, 2012 at 3:11 PM, Jonno wrote: > Not sure where the best place to post this is. My app uses wxpython, > matplotlib. > I'm running Python 2.7 on Windows 7. > I have a script app.py that I'm trying to turn into app.exe using py2exe. > The exe runs fine on the pc that it was compiled on but on another Win7 > machine I get something like the following in the app.exe.log: > > Traceback (most recent call last): > File "app.py", line 1951, in > File "wx\_core.pyo", line 7981, in __init__ > File "wx\_core.pyo", line 7555, in _BootstrapApp > File "app.py", line 1944, in OnInit > File "app.py", line 1811, in __init__ > File "matplotlib\backends\backend_wxagg.pyo", line 59, in draw > File "matplotlib\backends\backend_agg.pyo", line 401, in draw > File "matplotlib\artist.pyo", line 55, in draw_wrapper > File "matplotlib\figure.pyo", line 884, in draw > File "matplotlib\artist.pyo", line 55, in draw_wrapper > File "matplotlib\axes.pyo", line 1983, in draw > File "matplotlib\artist.pyo", line 55, in draw_wrapper > File "matplotlib\text.pyo", line 526, in draw > File "matplotlib\text.pyo", line 309, in _get_layout > File "matplotlib\backends\backend_agg.pyo", line 179, in > get_text_width_height_descent > File "matplotlib\mathtext.pyo", line 2974, in parse > File "matplotlib\mathtext.pyo", line 2352, in parse > File "matplotlib\pyparsing.pyo", line 1048, in parseString > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2559, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2307, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2679, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2307, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2756, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2714, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2373, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2559, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2416, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2559, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2559, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2416, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2293, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2756, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2559, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2373, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 924, in _parseNoCache > File "matplotlib\pyparsing.pyo", line 2416, in parseImpl > File "matplotlib\pyparsing.pyo", line 981, in _parseCache > File "matplotlib\pyparsing.pyo", line 950, in _parseNoCache > File "matplotlib\mathtext.pyo", line 2469, in symbol > File "matplotlib\mathtext.pyo", line 1312, in __init__ > File "matplotlib\mathtext.pyo", line 1319, in _update_metrics > File "matplotlib\mathtext.pyo", line 485, in get_metrics > File "matplotlib
PipeController v0.1 - experimental tool to simulate simple UNIX-style pipes in Python
I wrote PipeController recently to experiment with doing UNIX-style pipes in Python. Blog post about it: http://jugad2.blogspot.in/2012/08/pipecontroller-v01-released-simulating.html The blog post has a link to the downloadable PipeController source code. It will be released under the New BSD License, which means you can use it for any purpose, commercial or otherwise, subject to the terms of the license. - Vasudev Ram www.dancingbison.com jugad2.blogspot.com twitter.com/vasudevram -- http://mail.python.org/mailman/listinfo/python-list
get return or locals from "exec" str in "environment"
ok, i am stuck. i tried some test code attempts and i am stuck. so here is some sample code: xx2 = """ def lucas53(): harry = (4+16)/2 rtn = dict(harry=harry) return rtn """ and then i run: env = {} exec xx2 in env lst = env and lst returns a huge dictionary of many types, some excerpts are: {... ...'globals': , ... ...'vars': , ... ...'locals': , ... ...'lucas53': } and i can see my executed function in there as a type function, and local and global vars, but i can not access or find "harry" or "rtn" the variables within the function lucas53. i do not know how to access the local variables within lucas53 or the locals to find harry or rtn. i really just want the return dictionary. make sense? anyway, python impresses me with its graceful and concise code, but i really have not found the solution to this mess. please advise and thank you in advance. lucas -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
On Fri, Aug 31, 2012 at 8:11 AM, lucas wrote: > and i can see my executed function in there as a type function, and local and > global vars, but i can not access or find "harry" or "rtn" the variables > within the function lucas53. i do not know how to access the local variables > within lucas53 or the locals to find harry or rtn. i really just want the > return dictionary. make sense? Far as I can see, you never actually called that function anywhere. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
> Far as I can see, you never actually called that function anywhere. > ChrisA doesn't the exec command call the function? -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Question. Deploy new Master/Slave (M/S) datastore
That is the question, where have I to write, and what have I to write. My old acount was tarot-gratis, the new account is tarot-gratis-hrd. What have I to write, where Google help says "myapp" ? Where should I write appcfg.py update 'myapp'/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Question. Deploy new Master/Slave (M/S) datastore
On 30/08/2012 23:32, Ylodis wrote: That is the question, where have I to write, and what have I to write. My old acount was tarot-gratis, the new account is tarot-gratis-hrd. What have I to write, where Google help says "myapp" ? Where should I write appcfg.py update 'myapp'/ Probably where Terry Reedy told you to look some hours ago!!! -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On 30Aug2012 05:51, Adam W. wrote: | On Thursday, August 30, 2012 12:55:14 AM UTC-4, Dennis Lee Bieber wrote: | > How many bytes did it claim to send? | | 11, which is what I expected. But I changed the byte value to 16 | (because I was having trouble getting single digit hex values working | in the command) and sent this command: | | >>> for x in range(0,500): | ep.write(b'\x16\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF') | | it respond with 500 17's and prints a black bar! So it looks like whatever concern you had with using encode was coming to fruition. Yeah. Try 'iso8859-1' instead of 'utf-8'. You want to be not translating the byte values at all. UTF-8 encodes character values over 127 as multibyte sequences. ISO8859-1 is a 256 code set that does no translation - character codes in go directly to byte values out. You're speaking a binary protocol, not text, so you want a one to one mapping. Better still would be to be using a bytes I/O layer instead of one with a text->byte translation; I do not know if the USB library you're using offers such. So try 'iso8859-1'; at least the translation is a no-op. Cheers, -- Cameron Simpson B1FF is an archetype, and all you're showing us is one of the more amusing of his many instantiations.- Howard E. Motteler Ah, perhaps Arthur Clarke anticipated this in his celebrated short story, "The Nine Million Names Of B1FF"? - Nosy -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
On Fri, Aug 31, 2012 at 8:25 AM, lucas wrote: >> Far as I can see, you never actually called that function anywhere. >> ChrisA > > doesn't the exec command call the function? (Side point: You don't have to post to both comp.lang.python and python-list - they mirror each other.) What you executed included the 'def' statement. That's an executable statement that creates a function object: 'lucas53': In Python, functions are objects just like dictionaries, strings, and integers; you can construct them (usually with 'def' or 'lambda'), pass them around, tinker with their attribututes, and ultimately, call them. But unless you do actually call that function, none of its code will be executed. You can test this by putting a 'print' inside the function; you'll see screen output when the function's called, and your code above won't show that. To access the local variables/names from the function itself, you'll need to put a call to locals() inside that function, because as soon as it finishes, those locals disappear. Try this: >>> xx2 = """ def lucas53(): harry = (4+16) / 2 rtn = dict(harry=harry) return rtn foo = lucas53() """ >>> env = {} >>> exec(xx2,env) (This is Python 3 syntax, exec is now a function - otherwise equivalent to what you did.) You'll now see a name 'foo' in env, with the mapping returned from your function. There's no peeking into locals here, just a straight function return value. Is this what you were looking for? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
oh, yeah that was perfect. got it working and it is graceful too. sorry about the double post, i thought i was only posting to this one. one final concern, if this code is running under a function in a multi-threaded, multi-session kind of environment, does exec cross threads or sessions? like, i am afraid that i will get cross-over or bleeding into other threads or sessions. does exec do that kind of common memory space wherein i have to be very very careful about executing such code and my daemon crashing or security holes and the like. lucas -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
also, does that environment space, what i am assigning as env, have any such common memory space or cross thread problem with simultaneous threads or sessions? -- http://mail.python.org/mailman/listinfo/python-list
Re: class object's attribute is also the instance's attribute?
Hans Mulder writes: > Next week's lesson will be: if you test it first, then paste it into a > message for this forum, then tweak just one unimportant detail, you'll > need to test it again. +1 QotW -- \“Look at it this way: Think of how stupid the average person | `\ is, and then realise half of 'em are stupider than that.” | _o__) —George Carlin, _Doin' It Again_, 1990 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: get return or locals from "exec" str in "environment"
On Fri, Aug 31, 2012 at 9:54 AM, lucas wrote: > oh, yeah that was perfect. got it working and it is graceful too. sorry > about the double post, i thought i was only posting to this one. Hehe, you're still posting to both. I don't see the duplicates myself, but I'm sure others do. Just pick one and ignore the other. > one final concern, if this code is running under a function in a > multi-threaded, multi-session kind of environment, does exec cross threads or > sessions? like, i am afraid that i will get cross-over or bleeding into > other threads or sessions. does exec do that kind of common memory space > wherein i have to be very very careful about executing such code and my > daemon crashing or security holes and the like. Not that I am aware of, and I would be extremely surprised if there were any. But exec is not the sort of thing you'll normally want to use. What are you trying to accomplish? There's usually an alternative. The only time I've used an exec-like feature is when I'm actually writing something that loads code from the disk at run-time, such as my MUD with room files that look like this: @sdesc Short Description @ldesc This is the long description of the room, blah blah @cmds thwap #do_something_when_user_types_thwap() VERY unusual sort of thing to do - having real code in a data file. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Logging: Specifying converter attribute of a log formatter in config file
I have the same problem and couldn't find a solution. It seems that converters can only be set programmatically? On Thursday, August 30, 2012 6:38:27 AM UTC-4, Radha Krishna Srimanthula wrote: > I'd like to have all timestamps in my log file to be UTC timestamp. When > specified through code, this is done as follows: > > > > myHandler = logging.FileHandler('mylogfile.log', 'a') > > formatter = logging.Formatter('%(asctime)s %(levelname)-8s > %(name)-15s:%(lineno)4s: %(message)-80s') > > formatter.converter = time.gmtime > > > > myLogger = logging.getLogger('MyApp') > > myLogger.addHandler(myHandler) > > > > > > I'd like to move away from the above 'in-code' configuration to a config file > based mechanism. > > > > Here's the config file section for the formatter: > > > > [handler_MyLogHandler] > > args=("mylogfile.log", "a",) > > class=FileHandler > > level=DEBUG > > formatter=simpleFormatter > > > > Now, how do I specify the converter attribute (time.gmtime) in the above > section? -- http://mail.python.org/mailman/listinfo/python-list
Re: Making sense of a traceback from py2exe
On Thu, Aug 30, 2012 at 4:02 PM, Jonno wrote: > > Well I managed to figure out that the first traceback is the one causing > the problem and that matplotlib/mathtext in my app is the problem. > Now to figure out how to get mathtext working. > Bit more information: I am also seeing warnings in app.exe.log: C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXGeneral'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1226: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=normal:stretch=normal:size=12. Returning c:\windows\fonts\browai.ttf C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXSizeOneSym'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1226: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=bold:stretch=normal:size=12. Returning c:\windows\fonts\browai.ttf C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXSizeThreeSym'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXSizeFourSym'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXSizeFiveSym'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXSizeTwoSym'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1226: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=italic:variant=normal:weight=normal:stretch=normal:size=12. Returning c:\windows\fonts\browai.ttf C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['STIXNonUnicode'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmb10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmtt10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmmi10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmex10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmsy10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmr10'] not found. Falling back to Bitstream Vera Sans C:\Users\Administrator\Desktop\dist\library.zip\matplotlib\font_manager.py:1216: UserWarning: findfont: Font family ['cmss10'] not found. Falling back to Bitstream Vera Sans I think these are all fonts that matplotlib/mathtext would use so it makes sense that the traceback ends with: File "matplotlib\mathtext.pyo", line 720, in _get_glyph KeyError: 98 I then discovered that both the methods I tried for getting data_files (using glob and matplotlib.get_py2exe_datafiles) were not working and I had nothing in my mpl-data/fonts directory. This directory should contain 3 folders: afm, pdfcorefonts & ttf. The ttf folder is where the mathtext fonts mentioned above are located. I then tried manually copying the entire mpl-data folder into the dist folder after running py2exe on setup.py but still I get the same error. Does data_files do anything other than include files and directories in the dist folder? -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumping all the sql statements as backup
>> I have some long running processes that do very long simulations which >> at the end need to write things on a database. >> >> At the moment sometimes there are network problems and we end up with >> half the data on the database. >> >> The half-data problem is probably solved easily with sessions and >> sqlalchemy (a db-transaction), but still we would like to be able to >> keep a backup SQL file in case something goes badly wrong and we want to >> re-run it manually.. >> >> This might also be useful if we have to rollback the db for some reasons >> to a previous day and we don't want to re-run the simulations.. >> >> Anyone did something similar? >> It would be nice to do something like: >> >> with CachedDatabase('backup.sql'): >> # do all your things > " ... at the end need to write things on a database ... " Is it necessary to write those things during the process, or only at the end? If only at the end, can you write locally first, and then write that local store to your remote database? -- http://mail.python.org/mailman/listinfo/python-list
Context manager to save/restore a name binding
Howdy all, I have written a context manager to save and restore a name binding:: import contextlib @contextlib.contextmanager def preserve_value(namespace, name): """ A context manager to preserve, then restore, the specified binding. :param namespace: The namespace object (e.g. a class or dict) containing the name binding. :param name: The name of the binding to be preserved. :yield: None. When the context manager is entered, the current value bound to `name` in `namespace` is saved. When the context manager is exited, the binding is re-established to the saved value. """ saved_value = getattr(namespace, name) yield setattr(namespace, name, saved_value) The use case is http://stackoverflow.com/a/6811921/70157>, where it's used like this:: with preserve_value(sys, 'dont_write_bytecode'): sys.dont_write_bytecode = True module = imp.load_module(…) That way, I can set ‘sys.dont_write_bytecode’ to the value I need in this part of the code, knowing that however the code continues the previous value of that setting will be restored to whatever it was before I touched it. Have I re-invented a context manager which already exists? Is there a better way to do what ‘preserve_value’ is doing? -- \ “When a well-packaged web of lies has been sold to the masses | `\over generations, the truth will seem utterly preposterous and | _o__)its speaker a raving lunatic.” —Dresden James | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
"Adam W." wrote: > >You are correct about the 2 being the number of bytes written. However when I >issue a read command I get: > ep.write('\x1BA') >4 ep.read(1) >usb.core.USBError: [Errno None] b'libusb0-dll:err [_usb_setup_async] invalid >endpoint 0x02\n' USB endponts only go in one direction. There will be one endpoint for outoging data, and one endpoint for incoming data. -- Tim Roberts, t...@probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Text editors
On 7/29/2012 5:28 AM, Mark Lawrence wrote: On 29/07/2012 06:08, Ben Finney wrote: Tim Chase writes: On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: I highly recommend the use of notepad++. If anyone knows of a better text editor for Windows please let me know :) I highly recommend not tying your editor skills to a single OS, especially one as ornery for programmers as Windows. I'll advocate for Vim which is crazy-powerful and works nicely on just about any platform I touch. Others will advocate for Emacs, which I can't say fits the way my brain works but it's also powerful and loved by many. Right. I'm in Tim's position, but reversed: my preference is for Emacs but Vim is a fine choice also. They are mature, well-supported with regular updates and a massive library of plug-ins for different uses, have a huge community to help you, and work on all major programming OSen. The ubiquity of these two platforms makes a worthwhile investment of time spent in learning at least one if not both. I use both frequently in my work for different things, and they are good for pretty much any task involving manipulation of text. Learn one of Emacs or Vim well, and you won't need to worry about text editors again. Point taken, snag being I've never used any nix box in anger. This thread reminds of the good 'ole days when I were a lad using TPU on VMS. Have we got any VMS aficionados here? I used to run two VMS superminis. I'm not sure whether I still could, though. Robert Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Text editors
> On 7/29/2012 5:28 AM, Mark Lawrence wrote: >> On 29/07/2012 06:08, Ben Finney wrote: >>> Tim Chase writes: >>> [byte] >> >> Point taken, snag being I've never used any nix box in anger. This >> thread reminds of the good 'ole days when I were a lad using TPU on VMS. >> Have we got any VMS aficionados here? > Absolutely, I used to do real time data acquisition on DEC machines. Started on PDP-8e's, graduated to PDP-12's, then jumped to 780's, and finished up on 8700's. Used CAMAC gear for the actual real-world interfaces; all at a well-known Dept. of Energy lab. Too many years ago. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to save/restore a name binding
Ben Finney wrote: > I have written a context manager to save and restore a name binding:: > > import contextlib > > @contextlib.contextmanager > def preserve_value(namespace, name): > """ A context manager to preserve, then restore, the specified > binding. > > :param namespace: The namespace object (e.g. a class or dict) > containing the name binding. > :param name: The name of the binding to be preserved. > :yield: None. > > When the context manager is entered, the current value bound > to `name` in `namespace` is saved. When the context manager is > exited, the binding is re-established to the saved value. > > """ > saved_value = getattr(namespace, name) > yield > setattr(namespace, name, saved_value) > > The use case is http://stackoverflow.com/a/6811921/70157>, where > it's used like this:: > > with preserve_value(sys, 'dont_write_bytecode'): > sys.dont_write_bytecode = True > module = imp.load_module(…) > > That way, I can set ‘sys.dont_write_bytecode’ to the value I need in > this part of the code, knowing that however the code continues the > previous value of that setting will be restored to whatever it was > before I touched it. > > Have I re-invented a context manager which already exists? Is there a > better way to do what ‘preserve_value’ is doing? You should wrap yield in a try ... finally. You might allow setting the new value in the manager (untested): import contextlib missing = object() @contextlib.contextmanager def preserve_attr(namespace, name, value=missing): saved_value = getattr(namespace, name) if value is not missing: setattr(namespace, name, value) try: yield finally: setattr(namespace, name, saved_value) -- http://mail.python.org/mailman/listinfo/python-list