Re: Conditional decoration
Roy Smith wrote in news:[email protected] in gmane.comp.python.general: > Is there any way to conditionally apply a decorator to a function? > For example, in django, I want to be able to control, via a run-time > config flag, if a view gets decorated with @login_required(). > > @login_required() > def my_view(request): > pass You need to create a decorator that calls either the original function or the decorated funtion, depending on your condition, Something like (untested): def conditional_login_required( f ): _login_required = login_required()(f) def decorated( request ): if condition == "use-login": return _login_required( request ) else: return f( request ) return decorated @conditional_login_required def my_view(request): pass Replace (condition == "use-login") with whatever your "run-time control flag" is. -- Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending a broadcast message using raw sockets
Peter Steele wrote in news:[email protected] in comp.lang.python: > I want to write a program in Python that sends a broadcast message > using raw sockets. The system where this program will run has no IP or > default route defined, hence the reason I need to use a broadcast > message. > > I've done some searches and found some bits and pieces about using raw > sockets in Python, but I haven't been able to find an example that > explains how to construct a broadcast message using raw sockets. > > Any pointers would be appreciated. This is part of my Wake-On-Lan script: def WOL_by_mac( mac, ip = '', port = 9 ): import struct, socket a = mac.replace( ':', '-' ).split( '-' ) addr = struct.pack( 'B'*6, *[ int(_, 16) for _ in a ] ) msg = b'\xff' * 6 + addr * 16 s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 ) s.sendto( msg, ( ip, port ) ) s.close() The mac address is 6 pairs of hex digits seperated by '-' or ':'. http://en.wikipedia.org/wiki/Wake-on-LAN Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending a broadcast message using raw sockets
Peter Steele wrote in news:[email protected] in comp.lang.python: > On Monday, January 21, 2013 1:10:06 AM UTC-8, Rob Williscroft wrote: >> Peter Steele wrote in >> >> news:[email protected] in >> >> comp.lang.python: >> >> > I want to write a program in Python that sends a broadcast message [snip] >> This is part of my Wake-On-Lan script: >> >> def WOL_by_mac( mac, ip = '', port = 9 ): [snip] > Thanks for the code sample. Does this code work if the box has no IP > or default route assigned? I'm away from the office at the moment so I > can't test this. No idea, but the sockets system must be up and running before the card (interface) has an IP (otherwise how would it ever get assigned) and I presume DHCP works in a similar manner. However the "route assignemt" is irrelevent, broadcast messages never get routed. Rob -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending a broadcast message using raw sockets
Peter Steele wrote in news:[email protected] in comp.lang.python: > I just tried running you code, and the "sendto" call fails with > "Network is unreachable". That's what I expected, based on other tests > I've done. That's why I was asking about how to do raw sockets, since > tools like dhclient use raw sockets to do what they do. It can clearly > be duplicated in Python, I just need to find some code samples on how > to construct a raw packet. > Try s = socket.socket( socket.AF_INET, socket.SOCK_RAW ) I tried this on windows and it needed admin privaleges to run. Rob. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
Steven D'Aprano wrote in news:[email protected] in gmane.comp.python.general: > I can connect to an IMAP server using Python 2.6: > > steve@runes:~$ python2.6 > Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) server = imaplib.IMAP4_SSL('x') > But when I try with Python 3.2, it just sits there until it times out: server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) > What am I doing wrong? > Not using IMAP4_SSL, above you are using IMAP4 (non SSL) but with the SSL port. http://docs.python.org/py3k//library/imaplib.html#imaplib.IMAP4_SSL -- http://mail.python.org/mailman/listinfo/python-list
Re: ordering with duck typing in 3.1
andrew cooke wrote in news:33019705.1873.1333801405463.JavaMail.geo-discussion-forums@ynmm9 in gmane.comp.python.general: > > hi, > > please, what am i doing wrong here? the docs say > http://docs.python.org/release/3.1.3/library/stdtypes.html#comparisons > "in general, __lt__() and __eq__() are sufficient, if you want the > conventional meanings of the comparison operators" but i am seeing > >> assert 2 < three > E TypeError: unorderable types: int() < IntVar() > > with this test: > > > class IntVar(object): > > def __lt__(self, other): > return self.value < other > > so what am i missing? > The part of the docs you are relying on uses the wording "in general", IOW, it is not saying that defining __eq__ and __lt__ will always be sufficient. In this case the expression "2 < three" is calling int.__lt__, which doesn't know how to comapre to an instance of your class so returns NotImplemented. At this point if you had defined a __gt__ method the interpreter would then try and call that having first switched the arguments around. But you didn't so a TypeError is raised. I'm afraid I couldn't find anywhere in the docs where that behaviour is described, I suspect I only know it from lurking on usenet for a number of years. The best description that I could find of the behaviour you are seeing is at: http://docs.python.org/py3k/reference/expressions.html#not-in There is a paragraph that contains: "... the == and != operators always consider objects of different types to be unequal, while the <, >, >= and <= operators raise a TypeError when comparing objects of different types that do not implement these operators for the given pair of types. ..." Perhapse the docs could be reworded to note that, to define a full set of comparisons between *different* types, you need to define a full set of special methods. Some links I found along the way: http://docs.python.org/release/3.1.3/library/constants.html? highlight=__lt__#NotImplemented http://code.activestate.com/recipes/576685/ http://docs.python.org/py3k/library/functools.html#functools.total_ordering Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: None versus MISSING sentinel -- request for design feedback
Steven D'Aprano wrote in news:4e1fd009$0$29986$c3e8da3 [email protected] in gmane.comp.python.general: > I'm designing an API for some lightweight calculator-like statistics > functions, such as mean, standard deviation, etc., and I want to support > missing values. Missing values should be just ignored. E.g.: > > mean([1, 2, MISSING, 3]) => 6/3 = 2 rather than 6/4 or raising an error. If you can't make your mind up then maybe you shouldn't: MISSING = MissingObject() def mean( sequence, missing = MISSING ): ... Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.isdir do not work for Foder named '2011-07-03'
Nulpum wrote in news:0bf400a3-735c-487a-8d74- [email protected] in gmane.comp.python.general: > I want to make sure that folder exists. > '2011-07-03' is really exists. but 'os.path.isdir' say false > Does anyone know why? > os.path.isdir("C:\Users\Á¶Ã¢ÁØ\Desktop\logs") > True os.path.isdir("C:\Users\Á¶Ã¢ÁØ\Desktop\logs\2011-07-03") > False Maybe it isn't a directory, but a file, what does os.path.exists() return. Also could it be a "Shortcut" in which case 2011-07-03.lnk will exist. Also have you left "Hide extensions for known file types" switched on, in which case it may really be "2011-07-03.zip" for example, a file not a directory even though Windows explorer shows it as a directory. -- Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning a value from exec or a better solution
Jack Trades wrote in
news:CAG5udOg=GtFGPmTB=1ojnvnrpdyucxdokn1wjqmomv9gx0+...@mail.gmail.com
in gmane.comp.python.general:
> ... I wanted to allow the user to manually return the
> function from the string, like this:
>
> a = exec("""
> def double(x):
> return x * 2
> double
> """)
>
> However it seems that exec does not return a value as it produces a
> SyntaxError whenever I try to assign it.
def test():
src = (
"def double(x):"
" return x * 2"
)
globals = {}
exec( src, globals )
return globals[ "double" ]
print( test() )
The a bove works on 2.7 (I tested it) on earlier versions you may need
to use:
exec src in globals
Rob.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Button Label change on EVT_BUTTON in wxpython!!!
Ven wrote in news:aa1212bb-35e5-4bf9-b8ad-7a3c083749c2
@x2g2000yql.googlegroups.com in gmane.comp.python.general:
> So, here is what I did/want:
>
> self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
> self.Bind(wx.EVT_BUTTON, self.OnRun,id=ID_RUN_BUTTON)
>
> def OnRun(self,evt):
> self.run_button.SetLabel('Installing..')
> #call a function that does the installation task
> installation_task()
> #After task completion, set the button label back to "Install"
> self.run_button.SetLabel('Install')
>
> When I try doing this, it doesn't set the label to "Installing" while
> the task is being performed. Any suggestions how do I achieve this?
>
http://wiki.wxpython.org/CallAfter
Using this your OnRun will become somthing like:
def OnRun( self, evt ):
def after():
installation_task()
self.run_button.SetLabel('Install')
self.run_button.SetLabel('Installing..')
wx.Callafter( after )
However if installation_task takes a long time you will need to use
threads, something like (untested):
def OnRun( self, evt ):
def after():
self.run_button.SetLabel('Install')
def task():
installation_task()
wx.Callafter( after )
self.run_button.SetLabel('Installing..')
import threading
threading.Thread( target = task ).start()
Rob.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Returning a value from exec or a better solution
Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w...@mail.gmail.com
in gmane.comp.python.general:
>> def test():
>> src = (
>> "def double(x):"
>> " return x * 2"
>> )
>> globals = {}
>> exec( src, globals )
>> return globals[ "double" ]
>>
>> print( test() )
>>
>
> I looked into doing it that way but it still requires that the user
> use a specific name for the function they are defining. The docs on
> exec say that an implementation may populate globals or locals with
> whatever they want so that also rules out doing a simple "for item in
> globals", as there may be more than just the one function in there
> (though I suppose I may be able to work around that).
>
>
Why not just get the name from the user, or use a regular expression
to extract the first (or last, maybe) definition from the source string.
Rob.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Returning a value from exec or a better solution
Jack Trades wrote in news:CAG5udOiOAge3uHrGSDTZ412GAg+CC- [email protected] in gmane.comp.python.general: >> >>> class CapturingDict(dict): >> ... def __setitem__(self, key, val): >> ... self.key, self.val = key, val >> ... dict.__setitem__(self, key, val) >> ... >> >>> c = CapturingDict() >> >>> exec("def myfunction(x): return 1", c) >> >>> c.key >> 'myfunction' >> >>> c.val >> >> >> HTH, >> >> -- >> Arnaud >> > > That's brilliant and works flawlessly. Thank you very much! If an impementation (as you say up thread) can populate globals or locals with whatever they want, then how do you know that last item added was the function definition the user supplied ? Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning a value from exec or a better solution
Ethan Furman wrote in news:[email protected] in gmane.comp.python.general: > Jack Trades wrote: >> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote: >>> If an impementation (as you say up thread) can populate globals >>> or locals with whatever they want, then how do you know that last >>> item added was the function definition the user supplied ? > > Because the implementation will add things before the exec is processed. How do you know this ?, it isn't what the docs say. http://docs.python.org/reference/simple_stmts.html#the-exec-statement Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning a value from exec or a better solution
Arnaud Delobelle wrote in news:CAJ6cK1YVi3NQgdZOUdhAESf133pUkdazM1PkSP=p6xfayvo...@mail.gmail.com in gmane.comp.python.general: > On 30 August 2011 13:31, Jack Trades wrote: >> >> >> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote: >> >>> >>> > That's brilliant and works flawlessly. ¶ÿThank you very much! >>> >>> If an impementation (as you say up thread) can populate globals >>> or locals with whatever they want, then how do you know that last >>> item added was the function definition the user supplied ? > That's not an issue. The last statement that is executed will be the > "def" statement. You don't know that, an implementation may for example set __bultins__ to None, prior to returning, its not an unreasonable thing to do and the docs don't say they can't. Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Addition problems
vm wrote in news:[email protected] in gmane.comp.python.general: > def fun1(params_used_below_except_lk_and_lk2): > lk = 0.0 > lk2 = 0.0 > for raw_data, hist, freq in raw_data_hist_list: > lk2 = lk2 + fun2(some_constants_and_params_from_this_scope) > q = fun2(same_args_as_before) > lk = lk + q > print lk, lk2 > > For some set of input parameters, This function with specific input > prints out the same constant twice (as expected): > > 15377.7424582 15377.7424582 (twice the same value) > > If I comment out lines q = fun2 and lk = lk + q, fun1, with the > same parameters, prints: > > 0.0 3.3469936856 > > First value is expected, but I cannot understand how come the second > value is different in these two cases! Clearly the value returned by fun2 (get_beta_func_fit_quality_hist_lk) is different the second time you call it. So it either depends on and modifies a global or a value referenced or contained in one of the arguments. Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with sha.new
Florian Lindner wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hello, > I try to compute SHA hashes for different files: > > > for root, dirs, files in os.walk(sys.argv[1]): > for file in files: > path = os.path.join(root, file) > print path > f = open(path) Here you rebind 'sha' from what it was before (presumably the module sha) to the result of 'sha.new' presumably the new 'sha' doesn't have a 'new' method. try renameing your result variable. > sha = sha.new(f.read()) > sha.update(f.read()) > print sha.hexdigest() result = sha.new(f.read()) result.update(f.read()) print result.hexdigest() also I don't think you need the second call to update as f will have been read by this time and it will add nothing. > > > this generates a traceback when sha.new() is called for the second > time: > > sha = sha.new(f.read()) > AttributeError: new > Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve wrote in news:[EMAIL PROTECTED] in comp.lang.python: > --- Robert Williscroft <[EMAIL PROTECTED]> wrote: > >> My apologies for having to resort to email but for some reason I >> can't post this message to comp.lang.python. I've tried about 4 times >> including starting a >> new thread, but for some reason it doesn't turn up, though I've >> followed up on >> another thread without problem. > > Very strange. I hope it is not a conspiracy! :) > You can email to the list directly (that's what I am doing): > > [email protected] > I'll follow up and post this, and then see what happens :). >> > Is there a way out with Python as-is? >> > - >> > >> > Yes. If you take the time to look at the file in the CVS you'll >> > find that I was cheating a bit. To reduce the terrible clutter >> > above, I am actually using a simple trick:: >> > >> > adopt_init_args(self, locals()) >> > >> >> Also there is a decorator solution: >> >> def init_self( init ): >> vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] >> >> def decorated_init(self, *args, **kw): >> off = 0 >> for name in vn: >> if not name.startswith('_'): >> if name in kw: >> value = kw[name] >> else: >> value = args[off] >> off += 1 >> >> setattr( self, name, value ) >> >> init( self, *args, **kw ) >> return decorated_init >> >> >> class MyClass(object): >> __slots__ = ['x', 'z'] >> >> @init_self >> def __init__( self, x, _y, z ): >> pass >> >> def show( self ): >> for i in self.__slots__: >> print 'self.%s = %d' %(i,eval('self.%s' % (i,))) >> >> MyClass( 1, 2, 3 ).show() >> >> MyClass( z = 1, x = 2, _y = 3 ).show() >> >> The __slots__ is in the test just because you mentioned you like it, >> the decorator doesn't need a "slots" class. >> >> AFAICT this differs from your proposal in that in your proposal you >> want to use '.' as an include prefix the above uses '_' as an exclude >> prefix. >> >> Rob. > > I like the looks of the decorator approach a lot. Could this somehow > be enhanced such that the user doesn't have to know about the > underscore? The underscore is just there so there is a way of having arguments that aren't added as attributes to the first object, so if that isn't required it could just be omited. Also AIUI (the above is my first attempt to write a decorator), decorators can have arguments so the decorator could take an "omit_prefix" argument, so the user could specify there own prefix. Or maybe have an include prefix, say "self_", if thats what you prefer. Personaly I'm happy with the underscore, 1 leading underscore at module scope means hide the name, 2 at class scope means hide the name, so I kinda like that an undersore is used to omit an argument. > Thinking about runtime efficiency, could the decorator > approach somehow achieve that the attribute-to-be arguments are never > added to locals()? > Again AIUI, locals() is an inbuild that constructs a dict of the local arguments and variables, IOW the dict doesn't exist *until* you call locals(). Wether or not the fact the decorator doesn't call locals() makes any difference though I don't know, the real arguments will get passed to decorated_init() in some way and then setattr()'d to the self object. But then again there is a loop, 2 if's and a lookup of the keyword dictionary in there, using this as it stands is going to hurt compared to doing the asignments manually inside __init__(), though as I haven't timed it, I could be wrong ;-). Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve wrote in
news:[EMAIL PROTECTED] in
comp.lang.python:
> Does anyone know if there is a way to hide the _ or self_ from the
> user of the class, i.e. given:
>
> class foo(object):
> @attribute_decorator
> def __init__(self, x, _y, z):
> pass
>
> can we make it such that the user can still write
>
> foo(x=1,y=2,z=3)
>
> without the underscore?
>
Sorry I didn't understand what you ment before:
def init_self( init ):
class KeywordArgumentError(Exception):
pass
vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ]
def decorated_init(self, *args, **kw):
off = 0
for name in vn:
if not name.startswith('_'):
if name in kw:
value = kw[name]
else:
value = args[off]
off += 1
setattr( self, name, value )
else:
off += 1 #was missing (a bug) in last version.
if name in kw:
raise KeywordArgumentError(
"Use %s not %s" % (name[1:],name)
)
if name[1:] in kw:
kw[name] = kw[name[1:]]
del kw[name[1:]]
init( self, *args, **kw )
return decorated_init
class MyClass(object):
@init_self
def __init__( self, x, _y, z ):
print "in __init__() _y =", _y
def show( self ):
for i in self.__dict__:
print 'self.%s = %d' %(i,eval('self.%s' % (i,)))
MyClass( 1, 2, 3 ).show()
MyClass( z = 1, x = 2, y = 3 ).show()
MyClass( z = 1, x = 2, _y = 3 ).show()
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: What does "::" mean?
Robert Kern wrote in news:mailman.1954.1121875043.10512.python-
[EMAIL PROTECTED] in comp.lang.python:
> [EMAIL PROTECTED] wrote:
>> Hi Robert,
>> I didn't succeed in reversing a string with the "full form" you
>> proposed:
>> live[len(live)-1:-1:-1] # where live="live"
>> The result is an empty string.
>> To reverse "live" (in a "full form"), I have to put a char in front of
>> the string and...:
>> ('x'+live)[len(live)+1:0:-1] # --> "evil"
>> Is it due to the Python's version (I still have 2.3.4)?
>
> No, it's because I am stupid. There isn't a full form.
> live[len(live)::-1] is the closest expansion.
>
import sys
live = 'live'
print live[ sys.maxint : : -1 ]
print live[ len(live)-1 : : -1 ]
print live[ len(live)-1 : -len(live)-1 : -1 ]
print live[ len(live)-1 : -sys.maxint : -1 ]
print live[ sys.maxint : -sys.maxint : -1 ]
print live[ -1 : -len(live)-1 : -1 ]
Of course there is only one obvious way to do it, but alas
as I'm not Dutch I can't tell which it is.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: namespaces
deelan wrote in news:[EMAIL PROTECTED] in
comp.lang.python:
> Paolino wrote:
> (...)
>> What I'm needing as a global (in globals() or at the module level or
>> in the module namespace) is 'translate'.The rest of bindings
>> (all,badcars and table) is something which is 'polluting' the module
>> namespace.
>
> try this:
>
> ## yourmodule.py ##
>
> def _setup_table():
>import string
>all=string.maketrans('','')
>badcars=all.translate(all,string.letters+string.digits)
>return string.maketrans(badcars,'_'*len(badcars))
>
> TABLE = _setup_table()
>
> # optional, get rid of _setup_table symbol
> del _setup_table()
>
> def translate(text):
>return text.translate(TABLE)
>
After 3 or 4 iterations I refactored you code to this:
def translate( text )
import string
all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
TABLE = string.maketrans(badcars,'_'*len(badcars))
global translate
def translate( text ):
return text.translate(TABLE)
print "First Call! ", # -- Just for demonstration --
return translate( text )
print translate("If I was ...")
print translate("If I was ...")
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: namespaces
Paolino wrote in news:mailman.2453.1122812091.10512.python-
[EMAIL PROTECTED] in comp.lang.python:
> Rob Williscroft wrote:
>
> > After 3 or 4 iterations I refactored you code to this:
> >
> > def translate( text )
> > import string
> > all=string.maketrans('','')
> > badcars=all.translate(all,string.letters+string.digits)
> > TABLE = string.maketrans(badcars,'_'*len(badcars))
> >
> > global translate
> > def translate( text ):
> > return text.translate(TABLE)
> >
> > return translate( text )
>
> There is a way to access 'all' and 'badcars' here?
>
> In my trial translate.all and translate.badcars can be accessed easily
> and maybe coherently.
I had to do this inorder to access them:
def translate( text ):
import string
all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
TABLE = string.maketrans(badcars,'_'*len(badcars))
global translate
def translate( text ):
return text.translate(TABLE)
print "First Call! ", # -- Just to showoff --
translate.all = all
translate.badcars = badcars
return translate( text )
print translate("If I was ...")
print translate("If I was ...")
print "badcars:", len(translate.badcars)
CPython 2.4 on windows XP. But maybe you mean something else ?
>
> Thanks a lot, and don't tell me 'the dictator has marked the trail' ;)
>
I got the idea from Hung Jung Lu, here:
http://groups.google.co.uk/group/comp.lang.python/msg/1e63e07c7d83cc7d
How the trail got there I've no idea ;-)
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: namespaces
Steven D'Aprano wrote in
news:[EMAIL PROTECTED] in
comp.lang.python:
> Quoting Rob Williscroft:
>
>> > def translate( text )
>> > import string all=string.maketrans('','')
>> > badcars=all.translate(all,string.letters+string.digits)
>> > TABLE = string.maketrans(badcars,'_'*len(badcars))
>> >
>> > global translate
>> > def translate( text ):
>> > return text.translate(TABLE)
>> >
>> > return translate( text )
>
> This is a difficult piece of code to understand and maintain.
Its 8 lines, of self contained code. It does everyting its supposed to do
and nothing its not.
> You have
> a function called translate, which in turn calls the string
> translate() method. That's okay. But then you have a global variable
> *also* called translate -- does that refer to the same function?
This is how globals work in python, if you wish to (re)bind to a global
before reading it at function scope, you need to say so.
> Is
> this self-modifying code? That is a dangerous, hard to debug, hard to
> understand technique that is too-clever-by-half.
>
Maybe so, but if true, python as a language is too-clever-by-half.
> Then you create a local variable, also called translate, also a
No, that isn't how globals work in python, there is no local called
translate above.
> function, which simply calls the translate method of its argument. A
> waste of a function, when all you need to do is call the pre-existing
> translate method. If I have understood this code correctly, the
> *local* translate is bound to the *global* translate, which is the
> function being defined.
Close but there isn't, and never was, a *local* translate function.
> And lastly, just to complete the confusion, the original function
> itself appears to call itself -- presumably the rebound copy that
> points to what was the local copy -- recursively, with the same
> argument.
def f()
global g
def g():
return "something"
return g()
f() is a function that (re)creates a global function g() and calls it.
Is it just that translate() rebinds itself that is too much, or do you
object to f() too ? I do object to f() but only because its useless.
> That's a nifty piece of code for showing how clever you are at writing
> mildly obfuscated code. But for commercial use, where the code has to
> be maintained and debugged, it is a terrible idea.
8 lines of self contained code are a terrible idea !, you have IMO a
very strange idea of what is or isn't maintainable.
Is using generators and decorators a terrible idea too ?
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Managing events
cantabile wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi, > > I have a class (a gui) with buttons and other controls. A button, for > example, has a callback method, so that writing > > b = Button(label, OnClick) > > will call the global OnClick method. > > Now, if I want the OnClick method to call some of my main class > methods, > I need to write: > > UI = None > ... > class MainClass: > ... > global UI = self > > > Then, > def OnClik(button): > UI.do_something(button.get_label()) > > Is this the correct way to do it in Python ? Try: class MainClass: def do_something( self, label ): pass def OnClick( self, button ): self.do_something( button.get_label() ) def some_method( self ): b = Button( label, self.OnClick ) With the above you could also do: main = MainClass() b = Button( "A Label", main.OnClick ) Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: comment out more than 1 line at once?
Riko Wichmann wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Dear all, > > is there a way in Python to comment out blocks of code without putting a > # in front of each line? Somethings like C's > > /* > block of code here is commented out > */ > if False: (indented) block of code here is commented out I've no idea how efficient it is compared to triple-quoted strings or line by line comments. But (at least with the editors I use) it does retain the syntax highlighting, which I quite like YMMV. BTW for C and C++: #if 0 block of code here is commented out /* with embeded comments ! */ #endif Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: comment out more than 1 line at once?
Gustavo Córdova Avila wrote in news:mailman.6944.1101838678.5135.python- [EMAIL PROTECTED] in comp.lang.python: > Actually, it's infinitly [sp?] more defficient > (contrary of efficient?) than triple-quoted strings > or line-by-line comments, because those two never > make it to execution stage, because they're dropped > by the compiler. :-) > >>> False = True >>> if False: print "It Seems you are right" It Seems you are right >>> :-) How about: if 0: print "unreachable ??" Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: installing wxPython on Linux and Windows
Daniel Bickett wrote in news:mailman.7076.1102081193.5135.python- [EMAIL PROTECTED] in comp.lang.python: >> I have no way to build it on Windows though, as I don't have Visual C++ >> 7.1, for that we must wait for Robin Dunn. > > Would it be too difficult of a task to try getting the build working > with Dev-C++? That way those without enough incentive for purchasing > Visual C++ (in excess of $100, I believe) could build it. Forgive my > ignorance if this has already been considered ;) > Just the tools (no IDE): http://msdn.microsoft.com/visualc/vctoolkit2003/ Its a 33 MB download, a bit less than $100. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Twisted Non-Admin Installation
Kartic wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hello, > > I downloaded the Win32 installer for Twisted 1.3.0, Python 2.3. > > The installer, when executed under my login, fails as it requires > administrator rights to install (why they have it as a requirement, I > don't understand). > > So I started the installer as the admin user. That too failed because I > have a non-admin install of Python 2.3 on my machine and when I launch > the Twisted installer as admin, it is unable to find a Python > installation for the admin user! > > So, can someone let me know how I can install Twisted as a non-admin > user for a non-admin installation of Python? Installing from source is > not an option as I do not have MSVC. > Logon as Administrator, add yourself to the Administrators group logon as yourself, install twisted. Then remove yourself from the Administrators group. This should let you install, but wether it leaves twisted in a usable (by a non administrator) state, I don't know. Also AIUI twisted have a mailing list of there own, the link http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python is on there home page: http://twistedmatrix.com Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple thread-safe counter?
Tim Peters wrote in news:mailman.1223.1112417955.1799.python- [EMAIL PROTECTED] in comp.lang.python: > [Paul Rubin] >> I'd like to have a function (or other callable object) that returns >> 0, 1, 2, etc. on repeated calls. That is: >> >>print f() # prints 0 >>print f() # prints 1 >>print f() # prints 2 >># etc. >> >> There should never be any possibility of any number getting returned >> twice, or getting skipped over, even if f is being called from >> multiple threads. >> >> What's the simplest and most natural way to do this? I can think of a >> few but am not sure that they work. And I can think of some ways that >> are sure to work, but are messier than I'd like. > > The GIL is your friend here: > Yes but IIUC the GIL is only CPython, will this work with Jython, IornPython etc ? (*) > import itertools > f = itertools.count().next > *) I'm either being rhetorical or stupid, not sure which :). Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble using \ to escape %
Lucas Machado wrote in news:1113606334.524947.54630 @l41g2000cwc.googlegroups.com in comp.lang.python: > str1 = "[%s%s]\n\tpath = /mnt/samba/%s%s/\%U" % (list[0], list[1], > list[0], list[1]) > In a format string use '%%' for a single % char': str1 = "[%s%s]\n\tpath = /mnt/samba/%s%s/%%U" % (list[0], list[1],list[0], list[1]) Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Tix Tree open/close issue
Sorin Schwimmer wrote in news:mailman.8142.1152816058.27775.python-
[EMAIL PROTECTED] in comp.lang.python:
> The following code:
>
> from Tix import *
>
> r=Tk()
>
> tr=Tree(r)
> tr.subwidget('hlist').add('br1',text='branch 1')
> tr.subwidget('hlist').add('br1.b1',text='branch 1-1')
> tr.subwidget('hlist').add('br1.b1.b1',text='branch
> 1-1-1')
> tr.subwidget('hlist').add('br1.b1.b2',text='branch
> 1-1-2')
> tr.subwidget('hlist').add('br1.b2',text='branch 1-2')
> tr.subwidget('hlist').add('br1.b2.b1',text='branch
> 1-2-1')
> tr.subwidget('hlist').add('br1.b2.b2',text='branch
> 1-2-2')
> r.tk.call(tr,'setmode','br1','close')
> r.tk.call(tr,'setmode','br1.b1','open')
> r.tk.call(tr,'setmode','br1.b2','open')
> #tr.setmode('br1','close')
> #tr.setmode('br1.b1','open')
> #tr.setmode('br1.b2','open')
Try instead:
tr.setmode('br1.b1','close')
tr.setmode('br1.b2','close')
tr.setmode('br1','close')
tr.close('br1.b2')
tr.close('br1.b1')
> tr.grid()
>
> r.mainloop()
>
>
> will show the whole tree, but will set correctly the
> (+) and (-) boxes. (The commented out statements where
> in place before direct calls to Tk - same result).
>
> I was hoping to have some branches hidden (the leaves,
> in this case).
My solution above make any sense till I read the docs,
http://epydoc.sourceforge.net/stdlib/public/Tix.Tree-class.html
say:
setmode(self, entrypath, mode='none')
[snip]
... If mode is set to close, a (-)
indicator is drawn next the the entry.
... The
open mode indicates the entry has hidden children and this entry can be
opened by the user. The close mode indicates that all the children of the
entry are now visible and the entry can be closed by the user.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: using names before they're defined
Iain King wrote in news:1153323649.171612.74510 @s13g2000cwa.googlegroups.com in comp.lang.python: > > [EMAIL PROTECTED] wrote: >> [...] I need to reference (link) each object to the objects >> upstream and downstream of it, i.e. >> >> supply = supply() >> compressor = compressor(downstream=combustor, upstream=supply) >> combuster = combuster(downstream=turbine, upstream=compressor) >> etc. >> >> the problem with this is that I reference 'combustor' before is it >> created. [...] > > At the top of your code you could put: > > supply = None > compressor = None > combuster = None > turbine = None That doesn't help. The variable names will be rebound when assigned to the result of the contructor calls, but only after the previous binding (None) has been passed to some other objects constructor. IOW the second line of the OP's code would effectively be: compressor = Compressor(downstream=None, upstream=supply) Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial classes
Bruno Desthuilliers wrote in news:[EMAIL PROTECTED] in comp.lang.python: > John Salerno wrote: >> Marc 'BlackJack' Rintsch wrote: >> >>> Can you flesh out your use case a little bit and tell why you can't >>> solve the problem with inheritance or a meta class? >> >> >> From my experience with C#, the only real use for partial classes is >> when you want to separate your GUI code from the rest of your logic. > > What the ... is GUI code doing in a domain object ??? It doesn't (shouldn't) really work like that. The partial classes are used by GUI designer tools (Visual Studio[1] and SharpDevelop[2] for example) to seperate code that the tool generates from code (event handlers etc) that the programmer writes. IOW hopefully both parts of the class have GUI code in them. [1] http://msdn.microsoft.com/vstudio/ [2] http://www.sharpdevelop.net/OpenSource/SD/ Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: building lists of dictionaries
Jean_Francois Moulin wrote in
news:[EMAIL PROTECTED] in
comp.lang.python:
> Hi all,
>
> I tried this piece of code (FWIW, it was taken as is from a help
> section of mpfit, a mathematical routine for least square fitting):
>
> parinfo = [{'value':0., 'fixed':0, 'limited':[0,0],
> 'limits':[0.,0.]}]*6 parinfo[0]['fixed'] = 1
> parinfo[4]['limited'][0] = 1
> parinfo[4]['limits'][0] = 50.
>
> The first line builds a list of six dictionaries with initialised
> keys. I expected that the last three lines would only affect the
> corresponding keys of the corresponding dictionnary and that I would
> end up with a fully initialised list where only the 'fixed' key of the
> first dict would be 1, and the first values of limited and limits for
> dict number 4 would be 1 and 50. respectively
>
> This is not so!
> I end up with all dictionaries being identical and having their
> 'fixed' key set to 1, and limited[0]==1 and limits[0]==50.
>
> I do not understand this behaviour...
This should help:
http://www.python.org/doc/faq/programming/#how-do-i-create-a-
multidimensional-list>
As a TinyUrl: http://tinyurl.com/s8akj
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: How do you implement this Python idiom in C++
wrote in news:[EMAIL PROTECTED] in
comp.lang.python:
> #include
> using namespace std;
>
> // A base class that provides counting
> template class Counted {
> static int count;
> };
>
> template int Counted::count = 0;
>
> // Curious class definitions
> class CountedClass : public Counted {};
> class CountedClass2 : public Counted {};
>
> It apparently works but in fact it doesn't:
> If you derive from such a class, you get the count of the parent class,
You are mistaken about how it should work in the first place.
It may well be that it doesn't do what you wan't it to.
To translate the python idom into C++ you need to replace
derivation with the CRTP (*) code the author supplied.
*) CRTP = Curiosly Recuring Template Pattern
>
> not of the derived class.
> class CountedClass3 : public CountedClass {};
Don't use the above always use:
class CountedClass3 : public Counted< CountedClass3 >
{
};
Note that the "classmethod emulation" stops here, if you need
it to continue you will need to keep using the CRTP:
template < typename T = void >
class CountedClass : public Counted< CountedClass< T > >
{
};
Create instances:
CountedClass<> cc; /* T = void */
Derive (keeping the "classmethod emulation") using the CRTP:
template < typename T = void > /* So we can "Derive" again */
class CountedClass2 : public CountedClass< CountedClass2< void > >
{
};
Note that the trick works by always making the instantition of
Counted< T > you are deriving from unique, CountedClass<> has
a base class Counted< CountedClass< void > > and CountedClass2<>
has (ultimatly) a base class Counted< CountedClass2< void > >.
Ofcouse the next problem is that CRTP-derivation above isn't real
derivation, this idom translation clearly has a breaking point.
If this is more than idle curiosity I strongly suggest you post
a version of the python code you need to translate to C++.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > > I think what you say makes perfect sense > > I am using 2.4.2 python (I typed pthon -V on console to get) > > How can I find what my SPE editor is using ? > Wherever you can run python you can find the version by running the following bit of python import sys print sys.version For example I currently get: running: python ...\test-1.py 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] from my homebrew (wxPython) editor. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python open a named pipe == hanging?
Rochester wrote in news:[EMAIL PROTECTED] in
comp.lang.python:
> I just found out that the general open file mechanism doesn't work
> for named pipes (fifo). Say I wrote something like this and it
> simply hangs python:
>
> #!/usr/bin/python
>
> import os
>
> os.mkfifo('my_fifo')
>
> open('my_fifo', 'r+').write('some strings.')
> x = os.popen('cat my_fifo').read()
>
You will probably need to use os.open()
w = os.open( 'my_fifo', os.O_WRONLY )
r = os.open( 'my_fifo', os.O_RDONLY )
though I'm using windows now, so can't test it.
> print x
>
>
> I know I could use a tempfile instead of a fifo in this very
> simple case, I just want to know is there a standard way of
> handling fifos withing python.
See also os.pipe()
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Trouble displaying image with tkinter
sj wrote in news:[EMAIL PROTECTED] in comp.lang.python: > I am just learning to use Tkinter and am having problems displaying > image files. I am able to display an image using tutorials (such as > http://www.daniweb.com/code/snippet296.html) But when I try my own > code all I get is an empty widget. What is wrong with the following > program? > The problem is that CPython is (garbage) collecting the image. The canvas object is using it (i.e. passing to TCL/TK) but not keeping a reference to it. change idata to self.idata and all should be well. > > from Tkinter import * > > class Foo(Frame): [snip] > > idata = > PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif") > self.idata = PhotoImage . > canvas = Canvas(width=300,height=200) Your missing a parent reference in there (self in this case) i.e.: canvas = Canvas(self, width=300,height=200) but when I tested it it didn't seem to matter. I'd guess however that when the layout gets more complex it will make a difference. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
RE: file system iteration
Tim Golden wrote in news:mailman.119.1160403292.11739.python-
[EMAIL PROTECTED] in comp.lang.python:
> [Rick]
>| Searching for a file by name. Scanning for viruses.
> Etc.
>| There are lots
>| of legitimate reason to walk all paths from a centra
> l
>| starting point, no???
>
> Well, to get you started, I think this is the kind
> of thing you'll want. Uses ctypes, which is built-in
> to Python 2.5 so presumably legit.
>
>
> import ctypes
> import string
>
> GetDriveType = ctypes.windll.kernel32.GetDriveTypeA
>
> for letter in string.uppercase:
> print letter, "=>", GetDriveType ("%s:" % letter)
>
>
>
> You'll have to refer to
>
> http://windowssdk.msdn.microsoft.com/en-us/library/ms685874.aspx
>
> and various headers to get the values in question, but they
> look quite straightforward at a glance.
>
These seem to map when tested on my system:
import ctypes
DRIVE_TYPE_MAP = dict( enumerate ( """\
DRIVE_UNKNOWN
DRIVE_NO_ROOT_DIR
DRIVE_REMOVABLE
DRIVE_FIXED
DRIVE_REMOTE
DRIVE_CDROM
DRIVE_RAMDISK
""".split()
))
## if you need the constants ...
for i, name in DRIVE_TYPE_MAP.iteritems():
exec( "%s = %d" %( name, i) )
GetDriveTypeW = ctypes.windll.kernel32.GetDriveTypeW
for i in range( ord( 'A' ), 1 + ord('Z') ):
path = u"%c:\\" % chr( i )
print path, DRIVE_TYPE_MAP[ GetDriveTypeW( path ) ]
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Using Gnutar to remove a list of files
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi folks, I've got a question for yas. I'm trying to write code that > will open up a gzipped tar file using gnutar, and copy the list of > files(including their directories) to a list variable in python. From > there, I want to go through the list and delete those files from my > system. That part is easy, but what I'm stuck on is getting the list > of files in an archive into a list variable. If I use the -t parameter > in gnutar, it prints a list of the files in a seperate cmd screen, but > only returns 0. Is there any way to make it return a list, or to copy > the information over? Thanks in advance! > Perhaps this will help: http://docs.python.org/lib/tar-examples.html Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert StringIO to string
Jonathan Bowlas wrote in
news:[EMAIL PROTECTED] in
comp.lang.python:
> Hi listers,
>
> I've written this little script to generate some html but I cannot get
> it to convert to a string so I can perform a replace() on the >,
> < characters that get returned.
>
> from StringIO import StringIO
>
> def generator_file(rsspath,titleintro,tickeropt):
> scripter=StringIO()
> scripter.write('\n')
> scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath,
> titleintro, tickeropt))
> scripter.write('\n')
> return scripter.getvalue()
>
> I tried adding this:
>
> scripter = scripter.replace("<", "<")
> scripter = scripter.replace(">", ">")
>
> But obviously replace() isn't an attribute of StringIO so I guess I
> need to convert it to a string first, can someone please advise how I
> can do this?
>
How strange, you are already "converting" to a string in the return
line (the call to the getvalue() method), so:
scripter = scripter.getvalue().replace("<", "<")
scripter = scripter.replace(">", ">")
return scripter
should do what you want.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Strange Behavior
abcd wrote in news:[EMAIL PROTECTED] in comp.lang.python: > class Foo: > def __init__(self, name, data=[]): http://docs.python.org/ref/function.html#l2h-619 Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: forcing a definition to be called on attribute change
Bruno Desthuilliers wrote in news:[EMAIL PROTECTED] in comp.lang.python: >> class cSphere() : > > OT : prefixing classes names with 'c' is totally unpythonic. My understanding of "pythonic" is that its about how you use the language not what style you code in. Here's a variation of the usual example of pythonic: use: for i in some_list: pass not: i = 0 while i < len( some_list ): i += 1 IOW, pythonic code is code that uses the features of the language for the purpose they are intended, not code that ignores python's features and tries to adapt features or idiom's from other languages. I guess we could claim that one-liners are unpythonic (because indentation is a language feature), but claiming a all PEP 8 violating styles are unpyhonic seems to me to be devaluing the term. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do nested functions live?
Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- [EMAIL PROTECTED] in comp.lang.python: >def increment_time (interval_ms): > outer weeks, days, hours, minutes, seconds, mseconds # 'outer' > akin to 'global' > (...) > mseconds = new_ms - s * 1000# Assignee remains outer > m, seconds = divmod (s, 60) > h, minutes = divmod (m, 60) > d, hours = divmod (h, 24) > weeks, days = divmod (d, 7) # No return necessary > > The call would now be: > >increment_time (msec) # No reassignment necessary > > > Hope this makes sense Yes it does, but I prefer explicit in this case: def whatever( new_ms ): class namespace( object ): pass scope = namespace() def inner(): scope.mseconds = new_ms - s * 1000 m, scope.seconds = divmod (s, 60) h, scope.minutes = divmod (m, 60) d, scope.hours = divmod (h, 24) scope.weeks, scope.days = divmod (d, 7) The only thing I find anoying is that I can't write: scope = object() Additionally if appropriate I can refactor further: def whatever( new_ms ): class namespace( object ): def inner( scope ): scope.mseconds = new_ms - s * 1000 m, scope.seconds = divmod (s, 60) h, scope.minutes = divmod (m, 60) d, scope.hours = divmod (h, 24) scope.weeks, scope.days = divmod (d, 7) scope = namespace() scope.inner() In short I think an "outer" keyword (or whatever it gets called) will just add another way of doing something I can already do, and potentially makes further refactoring harder. Thats -2 import-this points already. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I import a script with an arbitrary name ?
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi all, > > I have a script responsible for loading and executing scripts on a > daily basis. Something like this: > > import time > t = time.gmtime() > filename = t[0] + '-' + t[1] + '-' + t[2] + '.py' > import filename > > So, I have a module with an arbitrary file name and I want to load it, > and later access its function definitions. > How can I do this ? In my example, the last line will obviously not > work. > http://docs.python.org/lib/built-in-funcs.html The first one __import__ should do the trick. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling GNU/make from a Python Script
Efrat Regev wrote in news:[EMAIL PROTECTED] in comp.lang.python: >Hello, > >I need to call GNU/make from within a Python script. This raised some > problems: > 1. The script is not in the directory of the makefile, and changing the > locations of either is not an option. Consequently, the makefile fails, > since it can't find the targets/dependencies. > 2. After searching around, it seems that os.system(..) should be avoided > if there's an alternative. Is there one in this case? > USe the subprocess module, in particular see Popen: http://docs.python.org/lib/node529.html and call: http://docs.python.org/lib/node530.html you will need to use the "cwd" argument. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do nested functions live?
Frederic Rentsch wrote in news:mailman.1536.1162292996.11739.python- [EMAIL PROTECTED] in comp.lang.python: > Rob Williscroft wrote: >> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- >> [EMAIL PROTECTED] in comp.lang.python: >> >> >> def whatever( new_ms ): >> class namespace( object ): >> pass >> scope = namespace() >> >> def inner(): >> scope.mseconds = new_ms - s * 1000 >> m, scope.seconds = divmod (s, 60) >> h, scope.minutes = divmod (m, 60) >> d, scope.hours = divmod (h, 24) >> scope.weeks, scope.days = divmod (d, 7) >> >> > > This is interesting. I am not too familiar with this way of using > objects. Actually it isn't all that different from a list, because a > list is also an object. But this way it's attribute names instead of > list indexes which is certainly easier to work with. Very good! > >> In short I think an "outer" keyword (or whatever it gets called) >> will just add another way of doing something I can already do, >> and potentially makes further refactoring harder. >> >> > > Here I'm lost. What's the advantage of this? It looks more convoluted. I'll agree that having to explicitly define a namespace class first does add some convolution. But if you refer to having to prefix you "outer" variables with "scope." then this would be the same as claiming that the explict use of self is convoluted, which is a valid opinion, so fair enough, but I can't say that I agree. It should also be noted that although I have to declare and create a scope object. My method doesn't require the attributes passed back from the inner function be pre-declared, should I during coding realise that I need to return another attribute I just assign it in the inner function and use it in the outer function. I would count that as less convoluted, YMMV. > And speaking of convoluted, what about efficiency? There is much talk > of efficiency on this forum. I (crudely) benchmark your previous > example approximately three times slower than a simple inner function > taking and returning three parameters. It was actually the aspect of > increased efficiency that prompted me to play with the idea of > allowing direct outer writes. Did you have optimisation turned on ? As I see it there should be no reason an optimiser couldn't transform my code into the same code we might expect from your "outer keyword" example, as the scope object's type and attributes are all contained within (thus known to) the outer function defenition. Wether CPython's optimiser does this or not, I don't know. > >> Thats -2 import-this points already. >> >> > > Which ones are the two? Explicit is better than implicit. There should be one-- and preferably only one --obvious way to do it. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do nested functions live?
Frederic Rentsch wrote in news:mailman.1556.1162316571.11739.python- [EMAIL PROTECTED] in comp.lang.python: > Rob Williscroft wrote: >> Frederic Rentsch wrote in news:mailman.1536.1162292996.11739.python- >>> Rob Williscroft wrote: >>>> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- [snip] >>>> >>> Here I'm lost. What's the advantage of this? It looks more convoluted. >>> >> >> I'll agree that having to explicitly define a namespace class first >> does add some convolution. >> >> But if you refer to having to prefix you "outer" variables with >> "scope." then this would be the same as claiming that the explict use >> of self is convoluted, which is a valid opinion, so fair enough, but >> I can't say that I agree. >> >> > > I didn't mean to call into question. I didn't understand the advantage > of the added complexity of your second example over the first. > Ok, I missed your point, as for the second example it was an attempt to show that further refactoring from a function with local functions that are sharing some state via the scope object, to a class with methods that share state via the instance, is a matter of editing a few lines. This is useful when a function grows too large (for some value of "too large"). As an added bonus you get to use the same thechniques with both styles of coding. [snip] Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Style for modules with lots of constants
Paul McGuire wrote in news:[EMAIL PROTECTED] in comp.lang.python: > > class Constants(object) > pass > > (I guess value immutability could probably be implemented using clever > implementations of __setattr__ and such, but is it really worth the > bother?). > > Then I defined the context for my LEFT and RIGHT constants, which are > being created to specify operator associativity, and then my constant > fields as attributes of that object: > > opAssoc = Constants(object) > opAssoc.RIGHT = 0 > opAssoc.LEFT = 1 > This is nice, but you can cut down on some of the cruft: class Constants( object ): pass Constants.RIGHT = 0 Constants.LEFT = 1 ## client code ... print Constants.LEFT Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Style for modules with lots of constants
Paul McGuire wrote in news:[EMAIL PROTECTED] in comp.lang.python: >>> opAssoc = Constants(object) >>> opAssoc.RIGHT = 0 >>> opAssoc.LEFT = 1 >> This is nice, but you can cut down on some of the cruft: >> Constants.LEFT = 1 > One man's cruft is another man's clarity. :-) > The reason I used instances > instead of just the Constants class was so that I could define a > little more descriptive context for the constants, Sorry I don't know what you mean here, could I have an example ? > rather than simply > a shortcut for importing lots and lots of constant definitions. I > expect I will want to define some more constants for other parts of > pyparsing, and the instance scoping helps organize them, that's all. Again I'm struggling to see how using an instance is any different from just using the class ? Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do nested functions live?
Frederic Rentsch wrote in news:mailman.1613.1162403556.11739.python- [EMAIL PROTECTED] in comp.lang.python: > Since we have a class that goes out of scope > when the function returns, and we don't need more than one instance, why > bother to make an instance? Why not use the class object itself? Because you hadn't yet pointed this out to me :-). Thanks Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Style for modules with lots of constants
Tim Chase wrote in news:mailman.1617.1162412498.11739.python- [EMAIL PROTECTED] in comp.lang.python: >>> The reason I used instances instead of just the Constants >>> class was so that I could define a little more descriptive >>> context for the constants, >> >> Sorry I don't know what you mean here, could I have an example > > > It helps in the recognition if you have separation between > something like > > turnDirection.LEFT class turnDirection( object ) : pass turnDirection.LEFT = 0 turnDirection.RIGHT = 1 > > and > > alignment.LEFT class alignment( object ) : pass alignment.LEFT = 3 > > They may be the same or different value for LEFT, but by grouping > them in a "descriptive context", it's easy to catch mistakes such as > > paragraph.align(turnDirection.LEFT) > > when what you want is > > paragraph.align(alignment.LEFT) > > and, as an added bonus, prevents name clashes such as > > turnDirection.LEFT = 2 > alignment.LEFT = 0 > > With the grab-bag o' constants, you have to use old-school > C-style in your modern name-space'd Python: > > gboc.TURN_LEFT = 2 > gboc.ALIGN_LEFT = 0 > > or even worse, you'd end up with cruftage where you have > > gboc.LEFT = 2 > gboc.ALIGN_LEFT = 0 #created a month later as needed > > and then accidentally call > > paragraph.align(gboc.LEFT) > > when you mean > > paragraph.align(gboc.ALIGN_LEFT) > > This is what I understand the grandparent's post to be referring > to by "descriptive context". Fair enough, but there is nothing in this that can't be done with pure (instance free) classes as shown above, with the advantage that the client just imports the name for the set of constants they want to use, and uses them with no need to construct. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where do nested functions live?
Steve Holden wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Since we have a class that goes out of scope >> when the function returns, and we don't need more than one instance, >> why bother to make an instance? Why not use the class object itself? >> >> def whatever( new_ms ): >> >> class scope ( object ): >> >> def inner(): >> scope.mseconds = new_ms - s * 1000 >> m, scope.seconds = divmod (s, 60) >> h, scope.minutes = divmod (m, 60) >> d, scope.hours = divmod (h, 24) >> scope.weeks, scope.days = divmod (d, 7) >> > That will need to be > >class scope(object): pass > > to avoid syntax errors, I suspect. There doesn't seem to be any reason > why you couldn't use a class instead of an instance. And, of course, > either might give you problems in the case of a recursive inner > function. What problems would it have that a recursive global function that modified a global object, or a recursive method that modified its instance doesn't have ? Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Tools for Java/Python scripting
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > > steve> http://wiki.python.org/moin/Java_Scripting > > Renamed to "JavaScripting". > > Skip So nobody around here has heared of that other language called JavaScript then ? Perhaps "Scripting_Java" might be better. Pythoning-ly yr's Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get/read Hard disk label / drive label
Praveen wrote in news:1162752076.121514.313750 @h48g2000cwc.googlegroups.com in comp.lang.python: > I want to read individual disk label > > for Hard disk (C: drive, D: drive disk label) > and > CD-ROM disk label > > Please provide some pointer to the code or document. > You could use: http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__ GetVolumeInformation_meth.html> which will require: http://sourceforge.net/projects/pywin32/ Or you can use this: http://windowssdk.msdn.microsoft.com/en-us/library/ms685899.aspx with this: http://docs.python.org/dev/lib/module-ctypes.html which is built in to python 2.5 Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError
Terry Reedy wrote in news:[EMAIL PROTECTED] in comp.lang.python: >> def main(): >>number = number() > > Within a function, a given name can be either global or local, but not > both. > Here you are expecting the compiler to interpret the first occurance > of 'number' as local and the second as global. Humans can often > resolve such ambiguities correctly, but not necessarily always. So > this is too much to ask of a program and hence it is not allowed. > ".. asked too much of the programme", sounds like a BOFH excuse to me ;-). Seriously I'd bet (if I were a gambling man) that this is by design, not either of "too much work for the interpreter" or "nobody's submitted a patch". IOW: Why should the intepreter do more work just so the user can find new and interesting ways to shoot them selves in the foot. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: odd problem with watsup and VB6 application with modal dialog
Grumman wrote in news:[EMAIL PROTECTED] in comp.lang.python:
[snip]
> Roughly, I have a script that fills in a field, sets a combobox, then
> clicks a button via clickButton. At this point, the python interpreter
> hangs. The only thing I've been able to identify as different about
> this form is that it is set as dialog-modal.
>
> I've managed to work around this by adding a second python script that
> contains just enough code to click the offending button. I call it via
> os.system('start other.py') and it starts in a different process,
> clicks the button then hangs.
>
> But the main script continues on to fill in the following form, and
> click another button. When the VB app returns to its starting form,
> destroying the other form instances, the hung interpreter ends.
>
> This works, but it is quite the ugly kludge isn't it?
>
> Is this a normal behaviour for watsup with modal windows? Is there a
> saner way around it?
AFAICT the problem is that the clickButton() function calls
the internal windows API function SendMessage(), which waits
for the buttons event handler to return something.
There is an alternative PostMessage(), which returns as soon as
the message is put in the target windows message queue.
A potential proplen with this is that it will return immediately
so the caller will need to wait (time.sleep) until the button
handler has recieved the message and done something about it.
Here's a rewrite of the winGuiAuto.clickButton function,
post_clickButton() that uses PostMessage:
def post_clickButton( hwnd ):
'''All code here adapted from winGuiAuto.py
see http://www.tizmoi.net/watsup/intro.html
'''
def _buildWinLong(high, low):
'''Build a windows long parameter from high and low words.
See http://support.microsoft.com/support/kb/articles/q189/1/70.asp
'''
return int( 0x & ( (high << 16) | (low & 0x) ) )
def _postNotifyMessage(hwnd, notifyMessage):
'''Post a notify message to a control.'''
import win32gui
import win32con
import win32api
win32gui.PostMessage(
win32gui.GetParent(hwnd),
win32con.WM_COMMAND,
_buildWinLong(
notifyMessage, win32api.GetWindowLong(hwnd, win32con.GWL_ID)
),
hwnd
)
import win32con
_postNotifyMessage( hwnd, win32con.STN_CLICKED )
if __name__=='__main__':
'''Just here to show how it works, this code won't actually
work unless you have a sutible GUI programme running.
'''
from watsup.winGuiAuto import \
findControl,setEditText, \
findTopWindow,clickButton
from time import sleep
def main():
form=findTopWindow(wantedText='Main_Form')
button=findControl(form,wantedText='Open')
print 'clicking button to open dialog...'
post_clickButton(button)
sleep( 0.5 )
form=findTopWindow(wantedText='Dialog_Form')
button=findControl(form,wantedText='Close')
print "clicking close button"
post_clickButton(button)
main()
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: select multiple entries in Listbox widget?
Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- [EMAIL PROTECTED] in comp.lang.python: > Hello, > > Is there an option or a way to allow the selection of multiple entries > in the Listbox widget? I could not find any, and would like to allow > the end user to select multiple entries. > > When configuring use: selectmode = "multiple" e.g.: import Tkinter as tk root = tk.Tk() a = tk.Listbox( root, selectmode = "multiple" ) for i in range(10): a.insert( i, str(i) + " item" ) a.pack() root.mainloop() I found the answer here: http://www.python.org/doc/life-preserver/ClassListbox.html Though I had to guess the `= "multiple"` part. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to define a static field of a given class
feel_energetic wrote in news:1149239221.045268.6170 @g10g2000cwb.googlegroups.com in comp.lang.python: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ),but I find there isn't a built-in func to build a > static field ( something like staticfield() ) > can anyone help me on this? > thanks very much for your help :) > What you possibly want is just a class attribute: class MyClass( object ): static_field = 10 myInstance = MyClass() print MyClass.static_field, myInstance.static_field Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Making a second window with Tkinter
greenflame wrote in news:1149305472.893535.67770
@h76g2000cwa.googlegroups.com in comp.lang.python:
> Ok so I played with your script. Here is a script that more closely
> mimics what I would like to do except that the way I make the variable
> deckstr will be different. The only thing I am confused about is that
> it opens the second window in the beginning and when I click on the
> button, it does nothing even after I have closed the other window.
>
> from Tkinter import *
> from string import join
>
> root = Tk()
>
> def showdeck(deck):
>deckwin = Toplevel()
>deckstr = join(deck, "\n")
>Label(deckwin, text=deckstr, justify=LEFT, anchor=W,
> font="Courier").pack(fill=X)
>
> L = Button(root, text="Show Deck", font="Courier",
> command=showdeck(list('zxcvbnm')))
You made the buttons command option None (which is what
showdeck() returns), you need to make command a function
that calls showdeck(list('zxcvbnm')).
L = Button(root, text="Show Deck", font="Courier",
command= lambda : showdeck(list('zxcvbnm')))
> L.pack()
>
> root.mainloop()
>
lambda's docs online:
http://docs.python.org/ref/lambdas.html
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Which compiler will Python 2.5 / Windows (Intel) be built with?
wrote in news:[EMAIL PROTECTED] in comp.lang.python: >> As nikie pointed out, you can buy a 1-year MSDN Pro Subscription that >> includes the VS2003 system. All that stopped is the free toolkit. > > The MSDN Pro Subscription is not really an option because we have no > use for the 2005 compiler at all if it doesn't work with Python. I > think we'll just try to get some boxed version of Visual Studio 2003 > Professional from somewhere. This is the .NET 11 SDK, I belive it includes the 2003 compiler (*): http://www.microsoft.com/downloads/thankyou.aspx?familyId=9b3a2ca6-3647- 4070-9f41-a333c6b9181d&displayLang=en&oRef= I found the link with google: net 1.1 sdk download its the first hit. *) I'm not going to check as I have VS2003 installed already. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython: how does EVT_IDLE work?
John Salerno wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Quick question about the code below: I understand why the progress bar > fills up at a steady pace when the mouse is idle over the frame; but > why, when you move the mouse, does the progress bar speed up? Shouldn't > it stop completely until the mouse is idle again? wxWidgets is sending the idle event after it has processed all other events, but it just sends it once not in a loop. see the documentation (help) for wxIdleEvent::RequestMore. > > def OnIdle(self, event): event.RequestMore(True) > self.count += 1 > if self.count >= 50: > self.count = 0 Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: time.clock() going backwards??
Claudio Grondi wrote in news:[EMAIL PROTECTED] in gmane.comp.python.general: > Tim Roberts wrote: >> "Tim Peters" <[EMAIL PROTECTED]> wrote: >> >> It is much simpler than that. With a multiprocessor HAL, including >> on a dual-core or hyperthreaded system, QueryPerformanceCounter >> returns the raw cycle counter (RDTSC). However, on Windows XP, the >> operating system does not synchronize the cycle counters on multiple >> processors, and they can be actually be millions of cycles apart. >> >> This was a change from previous systems. On NT4 and Win2000, the >> operating actually rewrote the cycle counters on the second (and >> beyond) processors to align them to the first processor, so the delta >> was usually only a dozen or two cycles. XP does not appear to do >> that. I think that is a huge mistake, since it renders >> QueryPerformanceCounter non-monotonic. > > How does it come, that processors on same mainboard run at different > speeds? Do they have separate clock-pulse generators? I don't see any claim above that they run at different speeds, only that the counters are several million cycles apart, IOW running at the same speed but with different initial values, or more likely starting at different times. For processors that run at (say) 2GHz, several million (say 10 million) represents a difference of 10e6/2e9 = 0.005 seconds between when the processors were sufficiently powered up to start counting cycles. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: threading support in python
Daniel Dittmar wrote in news:[EMAIL PROTECTED] in comp.lang.python: > - removing reference counting and relying on garbage collection alone > will break many Python applications (because they rely on files being > closed at end of scope etc.) > They are already broken on at least 2 python implementations, so why worry about another one. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
[EMAIL PROTECTED] wrote in news:1157758817.446690.105620
@i42g2000cwa.googlegroups.com in comp.lang.python:
> Please help my poor brain :) Every time I try to do a list
> comprehension I find I just don't comprehend ...
>
> Anyway, I have the following bit of code:
>
> seq = [2, 3, 1, 9]
> tmp = []
> for a in range(len(seq)):
> tmp.extend([a]*seq[a])
>
> which correctly returns:
>
> [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>
> Question is, can I do this as a list comprehension?
>
Well apparently I can, though it did take me 2 goes:
>>> seq = [2, 3, 1, 9]
>>> sum( [ [a]*seq[a] for a in range(len(seq)) ] )
Traceback (most recent call last):
File "", line 1, in -toplevel-
sum( [ [a]*seq[a] for a in range(len(seq)) ] )
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> sum( [ [a]*seq[a] for a in range(len(seq)) ], [] )
[0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>>
But thats just me showing off what a filthy programmer I am.
My third attempt went like:
>>> [ x for a in a in range(len(seq)) for x in [a] * seq[a] ]
Traceback (most recent call last):
File "", line 1, in -toplevel-
[ x for a in a in range(len(seq)) for x in [a] * seq[a] ]
TypeError: iteration over non-sequence
Ah the perils of cut-n-paste (and my what a strange error),
But my forth attemp yeilded (If that's a pun I do appologise)
this:
>>> [ x for a in range(len(seq)) for x in [a] * seq[a] ]
[0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>>
Which is possibly something you might of expected.
Note the unrolled version goes:
>>> tmp = []
>>> for a in range(len(seq)):
for x in [a] * seq[a]:
tmp.append( x )
>>> tmp
[0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>>
IOW a comprehension appends rather than extends. Other than
that you move the value you're appending from the inside of
the loop('s) to the begining of the comprehension then remove
newlines and colon's [inside some brakets ofcourse].
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL cannot open TIFF image in Windows
Andres Corrada-Emmanuel wrote in
news:[EMAIL PROTECTED] in
comp.lang.python:
> I have installed PIL 1.1.5 on Windows with Python 2.4. I'm unable to
> open .tiff images that I can open and view using Windows Explorer. In
> other words, this simple test fails:
>
> import Image
> im = Image.open('small.tif')
>
> with an 'cannot identify image file' error message. I'm able to open
> .jpg images. Is PIL's support for TIFF images dependent on something
> else in Windows?
I downloaded some test images from:
http://www.remotesensing.org/libtiff/images.html>
I then ran a test:
LIBTIFFPIC = r".\libtiffpic"
import Image, os
def main():
ok = error = 0
for root, sub, files in os.walk( LIBTIFFPIC ):
for i in files:
if i.endswith( '.tif' ):
full = os.path.join( root, i )
try:
tiff = Image.open( full )
except:
print "error:", full[ len( LIBTIFFPIC ) + 1 : ]
error += 1
else:
print "ok: ", full[ len( LIBTIFFPIC ) + 1 : ]
ok +=1
print "ok:", ok, "\terror:", error, "\ttotal:", ok + error
main()
The final line gave:
ok: 28 error: 33 total: 61
So I only managed to load 28 of the 61 test images, AFAIK I
have never installed anything special to get PIL to work
with tiff images.
As a side note The GIMP http://www.gimp.org/> wouldn't load
some of the images too (I didn't test all), it had problems with
64 bit floating point images and images with RBGA data in them.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: xinclude and pathnames
Tim Arnold wrote in news:[EMAIL PROTECTED] in comp.lang.python: > "Tim Arnold" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> I'm using ElementTree to access some xml configuration files, and >> using the module's xinclude capability. I've got lines like this in >> the parent xml file (which lives in the same directory as the >> included xml file): > href="/dept/app/doc/current/en/xml/asdf/asdf_syntaxterms.xml"/> >> >> When I started the project it was Unix-only; this worked fine. Now I >> have users who want to use the system on Windows and of course that >> directory path doesn't exist on Windows, but it is available on the >> network using a name like >> \\ladida\current\en\xml\asdf\asdf_syntaxterms.xml >> >> if relative paths worked, I could imagine >> would work. >> Also,the file can be read via an http server. >> >> My question: is there a way to make xinclude work with relative paths >> or perhaps urls? >> Any ideas welcome--to me it looks like I'll have to restructure this >> part of the system since I've basically programmed myself into a >> corner. >> According to the docs: http://effbot.org/zone/element-xinclude.htm The default handler just sees the href value as a filename, so you should be able to use a relative path if you os.chdir() to the working directory before processing you xml file. I just ran a 3 line sample to make sure os.chdir() works with network paths, which it did. Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Working with email and mailbox module
Nirnimesh wrote in news:1158840271.942540.85640 @d34g2000cwd.googlegroups.com in comp.lang.python: > I want to extract emails from an mbox-type file which contains a number > of individual emails. > > I tried the python mailbox and email modules individually, but I'm > unable to combine them to get what I want. Mailbox allows me to iterate > over all the mails but doesn't give me access the individual messages > of a multipart mail. The email.Message module provides this, but I'm > unable to iterate through all the messages with this module. > > Here's what I want: > > Get a list of all messages from mbox-file > For each message, be able to read the header or body individually (so > that I can apply some operation) > > Does someone have experience in doing something of this sort? > Not really, but this is what I came up with the other day to read one of my newsreaders mbx files: MBX = r"<<<-insert-path-to-your-mbx->>>" import mailbox, email fmbx = open( MBX, 'rb' ) mbx = mailbox.PortableUnixMailbox( fmbx, email.message_from_file ) for i, msg in enumerate( mbx ): print msg.__class__ for i in msg.keys(): # gets header names print i break fmbx.close() http://docs.python.org/lib/module-email.Message.html Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils on Windows with VC++ 8
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in comp.lang.python: > [EMAIL PROTECTED] schrieb: >> I'm trying to install two different packages which wrap C or C++ code >> and which make use of distutils.build_ext, which barfs because my only >> compiler is too new. Trying this both on Python 2.4.3 and 2.5. >> Evidently there is a requirement that the compiler used to build the >> C/C++ in the installation must be the same as was used to build >> Python? Am I understanding that correctly? > > Yes. > >> What's the workaround? > > There are several work-arounds, but they all come down to > "get a copy of the one of the supported compilers". The options > are: > - get a copy of VS 2003 on Ebay Download the 1.1 SDK: http://www.microsoft.com/downloads/details.aspx?familyid=9B3A2CA6- 3647-4070-9F41-A333C6B9181D&displaylang=en> yes it does have 90 odd megabytes of stuff you don't want but the C/C++ compiler is in there. > - use cygwin/mingw (should work for C, might not work for > C++ if you use MFC or some other MS-compiled library) > - find the VS 2003 Toolkit; Microsoft took it off the net, > but Google may still be able to help I think the VS 2003 toolkit is a framework for extending Visual Studio 2003, IOW a bunch of .NET dlls, some examples and a helpfile (no compiler). Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils on Windows with VC++ 8
=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote in news:4514479B.5070808
@v.loewis.de in comp.lang.python:
> Rob Williscroft schrieb:
>> Download the 1.1 SDK:
>>
>> http://www.microsoft.com/downloads/details.aspx?familyid=9B3A2CA6-
>> 3647-4070-9F41-A333C6B9181D&displaylang=en>
>>
>> yes it does have 90 odd megabytes of stuff you don't want but the C/C++
>> compiler is in there.
>
> That's yet another option. Somebody reported that the compiler in the
> .NET SDK won't support generating optimized code, though. That's a
> problem for some people.
I belive that was true "Academic" releases of Visual Studio, AIUI it
was never true of the 7.1 compiler that came with .NET 1.1 SDK's.
>
>> I think the VS 2003 toolkit is a framework for extending Visual Studio
>> 2003, IOW a bunch of .NET dlls, some examples and a helpfile (no
>> compiler).
>
> I don't think so. It was (as it's no longer officially available) a
> command-line only version of the compiler. In any case, it is
> (or was) different from the .NET SDK.
Having read Noel Byron's reply also, I'm tempted to say there is
some confusion here between a Visual *Studio* toolkit (VS 2003)
and a Visual *C++* toolkit (VC 2003).
There is defenitly a Visual Studio Toolkit I downloaded the 2005
version reciently (to test IornPython integration), and I remember
coming accross a 2003 version too ('cause Microsoft never like to
make a download easy to find ;-)).
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: distutils on Windows with VC++ 8
Rob Williscroft wrote in news:Xns9846DDC7A18E0rtwfreenetREMOVEcouk@ 216.196.109.145 in comp.lang.python: >> That's yet another option. Somebody reported that the compiler in the >> .NET SDK won't support generating optimized code, though. That's a >> problem for some people. > > I belive that was true "Academic" releases of Visual Studio, AIUI it > was never true of the 7.1 compiler that came with .NET 1.1 SDK's. > ... a 106 MB download later ... Strike that. My belief was incorrect, the SDK comes with the "Standard" compiler that doesn't understand the /O... options that the "Optimizing" compiler that comes with Visual Studio does. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
[email protected]
Nigel wrote in news:[EMAIL PROTECTED]
in comp.lang.python:
> from Tkinter import *
> import pyTTS
> Hi i am trying to get a button so that when i click on it i hear a
> voice say "Hi Molly" this is my code so far.Can any one shed any light
> on this for please.
> Thanks Nige.
Your problem appears to be that you do not know how to associate
an action (the press of the button) with the code you want to run
( tts.Speak ('hello molly') ).
Tk buttions have a command attribute that is called when the button
is clicked:
self.button1[ 'command' ] = HelloMolly
Where HelloMolly is an already defined python callable, for example:
def HelloMolly():
self.tts.Speak ('hello molly')
The above defenition of HelloMolly requires that somtime before it
is called, self.tts is created:
self.tts = pyTTS.Create()
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Printing a percent sign
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi all. How do I escape the "%" sign in a print statement so that it > prints? Thanks. > print "%%" Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing a percent sign
Rob Williscroft wrote in news:Xns9849DC7DB4102rtwfreenetREMOVEcouk@ 216.196.109.145 in comp.lang.python: > wrote in news:[EMAIL PROTECTED] in > comp.lang.python: > >> Hi all. How do I escape the "%" sign in a print statement so that it >> prints? Thanks. >> > > print "%%" > Ok, confused by the simplicity of the question. Real answer is: print "%" But the real question was "how to print a % whern doing % formating", acuracy = 100 print "this is %d%% more acurate than my previous answer" % acuracy Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator question
Neal Becker wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Any suggestions for transforming the sequence: > > [1, 2, 3, 4...] > Where 1,2,3.. are it the ith item in an arbitrary sequence > > into a succession of tuples: > > [(1, 2), (3, 4)...] > > In other words, given a seq and an integer that specifies the size of > tuple to return, then for example: > > seq = [a,b,c,d,e,f] > for e in transform (seq, 2): > print e > > would return > (a,b) > (c,d) > (e,f) > >>> seq = range(11) >>> zip(seq[::2], seq[1::2] + [None]) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)] >>> seq = range(10) >>> zip(seq[::2], seq[1::2] + [None]) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator question
Rob Williscroft wrote in news:Xns984ACDA635C9rtwfreenetREMOVEcouk@ 216.196.109.145 in comp.lang.python: >>>> seq = range(11) >>>> zip(seq[::2], seq[1::2] + [None]) > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)] > >>>> seq = range(10) >>>> zip(seq[::2], seq[1::2] + [None]) > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] For bigger sequences: >>> import itertools as it >>> seq = range(11) >>> even = it.islice( seq, 0, None, 2 ) >>> odd = it.islice( seq, 1, None, 2 ) >>> zipped = it.izip( even, it.chain( odd, [None] ) ) >>> list( zipped ) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)] Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: generator with subfunction calling yield
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Any insight? >From the docs: The yield statement is only used when defining a generator function, and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. Note that its when a function defention contains a yeild statement (expression) that the defenition is taken to be a generator function. > def nn(): > >def _nn(): >print 'inside' >yield 1 > >print 'before' > >_nn() >print 'after' So tha above (nn()) isn't a generator as it doesn't contain a yield statement. Note also that the call to _nn() returns a generator, it isn't a regular function call. Here is nn() re-writen to return what you may have originaly expected: def nn(): def _nn(): print 'inside' yield 1 print 'before' for i in _nn(): yield i print 'after' So to forward another generator you need to iterate over it and yield each element, just as you would for any other iterable. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two dates in seconds
Steven D'Aprano wrote in news:[EMAIL PROTECTED] in comp.lang.python: > On Wed, 27 Sep 2006 20:16:52 +0200, Fredrik Lundh wrote: > >> Claes at work wrote: >> >>> Please tell me there is a simpler way than subtracting two datetimes >>> to get a timedelta and then compute >>> >>> days * number of seconds per day + seconds >>> >>> from it myself?? >> >> why would you have to do that yourself? why not let Python do it for >> you? here's the code: >> >> seconds = td.days * 86400 + td.seconds > > I'm sure somebody as experienced as Fredrik doesn't need to be told > why peppering code with magic constants like 84600 are a less than > ideal solution -- and for those who do need to be told, carefully > compare what I wrote to what Fredrik wrote to see one of those > reasons. What you wrote, where ? > > Arguably a better solution would be to do this: > > seconds = td.days * 24*60*60 + td.seconds > > Still not ideal though, although that depends on just how often you > need to convert days to or from seconds. > > Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: PATCH: Speed up direct string concatenation by 20+%!
Larry Hastings wrote in news:1159495643.213830.289620 @m7g2000cwm.googlegroups.com in comp.lang.python: > _ > THE PATCH > > The core concept: adding two strings together no longer returns a pure > "string" object. Instead, it returns a "string concatenation" object > which holds references to the two strings but does not actually > concatenate > them... yet. The strings are concatenated only when someone requests > the > string's value, at which point it allocates all the space it needs and > renders the concatenated string all at once. On the python 3k list there is a thread about stings becoming "views", I think this is similar to what you are doing here. http://search.gmane.org/? query=string+view&author=&group=gmane.comp.python.python- 3000.devel&sort=relevance&DEFAULTOP=and&xP=string.view. &xFILTERS=Gcomp.python.python-3000.devl---A> http://tinyurl.com/kadco Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw strings and escaping
Matthew Warren wrote in news:mailman.1152.1159872720.10491.python- [EMAIL PROTECTED] in comp.lang.python: > I would expect this to work, > > rawstring=r'some things\new things\some other things\' It in the docs: http://docs.python.org/ref/strings.html#l2h-14> ... Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation. Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Instantiating an object when the type is only known at runtime
Samuel wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi, > > I am trying to replace the eval() in the following code: > > def myfunc(type, table): > module = __import__(type) > type = 'module' + '.' + type > obj = eval(type) > return obj(row[table.c.name], row[table.c.handle]) > >>> m = __import__( "StringIO" ) >>> x = getattr( m, "StringIO" )() >>> x >>> Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Restart a thread
many_years_after wrote in news:1164467660.760671.145440
@j44g2000cwa.googlegroups.com in comp.lang.python:
> class mythread(threading.Thread):
> def __init__(self, threadname):
> threading.Thread.__init__(self, name = threadname)
>
> def run(self):
> print 'i am running'
> print 'i quit run()'
>
> thread = mythread('1')
> thread.start()
> print threading.activeCount() ## 1 , this means the thread is active
> if not thread.isAlive():
> print 'i am dead,you can restart' ### OK, this is executed. this
> means the thread is no alive
> thread.start() " thread already started "
>
> This program presentes that the thread quit the *run()* func and is
> active but not alive. How to understand this? It is said if the
> thread quit the *run()* func , it's dead.
> how to restart it ?
>
> Thanks
>
Form the manual [1] (you must have missed this):
start( )
Start the thread's activity.
This must be called at most once per thread object.
It arranges for the object's run() method to be invoked
in a separate thread of control.
Note the 2nd line:
This must be called at most once per thread object.
so you simply can't restart a Thread object.
[1] http://docs.python.org/lib/thread-objects.html
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: case insensitive dictionary
John Henry wrote in news:1164494606.514366.124810 @l39g2000cwd.googlegroups.com in comp.lang.python: > I believe the standard dictionary should be amened to allow the use of > case insensitive keys - as an option. class idict( dict ): class __istr( str ): def __eq__( self, other ): return self.lower() == other.lower() def __hash__( self ): return self.lower().__hash__() def __setitem__( self, k, v ): dict.__setitem__( self, idict.__istr( k ), v ) d = idict( a = 1, b = 2 ) d['A'] = 3 print d Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: super() and type()
Chris Mellon wrote in news:[EMAIL PROTECTED] in comp.lang.python: > I see super documented, and in use, as below (from the Python > documentation) > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > > I'd like to not write C all the time, so is there any problem with > writing: > > class C(B): > def meth(self, arg): > super(type(self), self).meth(arg) > > > This seems to work in practice but I don't see it used anywhere and > I'm worried what I might be missing. Have you considered what happens if somebody writes: class D(C): def meth(self, arg): super( D, self ).meth( arg ) > > This was especially brought to my attention because pylint flags the > second usage as invalid, and I'm not sure if it should be considered a > false positive or not. Nope, the type argument to super tells it where you are in the type hierarchy, type(self) is always the top of the hierarchy. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing file metadata on windows XP
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > When rightclicking a, for example, pdf file on windows, one normally > gets a screen with three or four tags. Clicking on one of the summary > tag one can get some info like "title", "Author", "category", "keyword" > etc.. > > My question is how can I programmatically read and change these data > with python. I know I should use Hammond's win32 extension, somehow > involving the pythoncom, storagecon of win32com etc.. Unfortunately, > so far I cannot get anything useful. Instead of trying blindly, would > somebody please points me to the correct direction. A little snippet > would help. I am particular interested in pdf files. > This looks like it might be useful: http://msdn.microsoft.com/library/default.asp?url=/library/en- us/shellcc/platform/shell/reference/objects/shellfolderitem/shellfolderit em.asp> Thats: MSDN Home > MSDN Library > Win32 and COM Development > User Interface > Windows Shell > Windows Shell > Shell Objects for Scripting and Microsoft Visual Basic > ShellFolderItem > Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem understanding how closures work
Tom Plunket wrote in news:[EMAIL PROTECTED] in comp.lang.python: > ...at least, I think that I'm having a problem understanding the way > closures work. > > I'm trying to define a function for an object which will take certain > objects from the parent scope at the time that function is defined. > For some reason, if I do this function definition in a loop, the > locals given by that function (is this a closure?) are changed each > iteration of the loop, whereas if the function definition is isn't > looped over, I get the behavior I desire. Can anyone provide any > insight for me? > Test 1 doesn't work the way I would expect: > Test 4 says, "Test 0" > Test 4 says, "Test 4" > > def CreateTests1(count): > tests = [] > for i in xrange(count): > name = 'Test %d' % i > t = Test(name) > tests.append(t) > > def ExCall(text): >print '%s says, "%s"' % (name, text) > > t.ExternalCall = ExCall > > return tests "name" in the above code is bound to a an entry in "CreateTests1"'s locals, and ExCall has a (hidden) reference to that locals, so by the time ExCall is finally called the value associated with "name" has been replaced by (count - 1). The solution (as always) is to add another level of indirection: def create_tests( count ): def make( arg ): def ExCall( text ): print arg, text return ExCall tests = [] for i in range( count ): name = i t = Test( name ) t.ExternalCall = make( name ) In the above, every call to make() creates a new frame (a new set of locals) and binds the value of the passed in "name" to the name "arg" in this new frame, it will be this value that is eventually printed. There is a trick with default arguments that lets you do what you want with a bit less faffing about: >>> r = [] >>> for i in range(10): def f( i = i ): print i r.append( f ) >>> for i in r: i() In this example the value of "i" is bound to the default argument for the function "f" every time the def f() statments are executed. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows SetLocalTime
Podi wrote in news:[EMAIL PROTECTED] in comp.lang.python: > I am trying to set the system time on my Windows computer, but avoid > using the DOS command (date, time). > > Does anyone know what parameter to pass to function SetLocalTime? http://msdn.microsoft.com/library/default.asp?url=/library/en- us/sysinfo/base/setlocaltime.asp> Google will usually find the documentation of anything in the Windows API however sometimes it also helps to add "msdn" to your search as in: http://www.google.com/search?client=firefox-a&rls=org.mozilla%3Aen- US%3Aofficial_s&hl=en&q=setlocaltime+msdn&btnG=Google+Search> Adding site:msdn.microsoft.com is even better (but alas more typing): http://www.google.com/search?hl=en&lr=&client=firefox- a&rls=org.mozilla%3Aen-US%3Aofficial_s&q=setlocaltime+site% 3Amsdn.microsoft.com&btnG=Search> Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows SetLocalTime
Podi wrote in news:[EMAIL PROTECTED] in
comp.lang.python:
> Rob Williscroft wrote:
>>
>> Google will usually find the documentation of anything in the
>> Windows API however sometimes it also helps to add "msdn" to
>> your search as in:
> Yes, thank you.
>
> I found the function SetLocalTime or SetSystemTime to set the time from
> MSDN http://msdn2.microsoft.com/en-us/library/ms724942.aspx. I am
> having trouble passing parameter to the functions in Python.
>
Ok I see, you will probably need these 2 bits of the ctypes
documentation:
http://docs.python.org/lib/ctypes-structures-unions.html
http://docs.python.org/lib/ctypes-pointers.html
>From there on geting to this is farly straight forward:
from ctypes import *
from ctypes.wintypes import WORD
class SYSTEMTIME(Structure):
_fields_ = [
( 'wYear', WORD ),
( 'wMonth', WORD ),
( 'wDayOfWeek', WORD ),
( 'wDay', WORD ),
( 'wHour', WORD ),
( 'wMinute', WORD ),
( 'wSecond', WORD ),
( 'wMilliseconds', WORD ),
]
GetSystemTime = windll.kernel32.GetSystemTime
st = SYSTEMTIME()
GetSystemTime( pointer( st ) )
print st.wYear, st.wMonth, st.wDayOfWeek
A bit more digging into the docs will get to this:
prototype = WINFUNCTYPE( None, POINTER( SYSTEMTIME ) )
paramflags = (1, "lpSystemTime" ),
GetSystemTime = prototype(("GetSystemTime", windll.kernel32), paramflags )
st = SYSTEMTIME()
GetSystemTime( st )
print st.wYear, st.wMonth, st.wDayOfWeek
Which will give a much better error message if you try to
pass something other than a SYSTEMTIME, as well as wrapping
the argument in pointer for you.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Property error
king kikapu wrote in news:1166181267.949316.197360@ 16g2000cwy.googlegroups.com in comp.lang.python: > I am sure it is something very obvious Yes, property is *NOT* a decorator, it can only be used as a decorator in the one case that is mentioned in the docs: http://docs.python.org/lib/built-in-funcs.html#l2h-57";> If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator: class Parrot(object): def __init__(self): self._voltage = 10 @property def voltage(self): """Get the current voltage.""" return self._voltage Note the use of "read-only" in the above description and that the decorated function (voltage) *is* the properties "fget" function. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
Evan wrote in news:[EMAIL PROTECTED] in comp.lang.python: > In matlab I can do the following: > >>> ind = [3,5,7,2,4,7,8,24] > ind = 3 5 7 2 4 7 824 >>> ind(1) ans = 3 >>> ind(end) ans =24 >>> ind([1 end]) ans = 324 > > but I can't get the last line in python: > > In [690]: ind = [3,5,7,2,4,7,8,24] > In [691]: ind[0]Out[691]: 3 > In [692]: ind[-1:] Out[692]: [24] > In [693]: ?? > > How do I pull out multiple indices as in matlab? [ind[0], ind[-1]] or if you need something that can be generalised: [ind[i] for i in [0, -1]] so if you have: indexes_of_ind = [0, 2, -1, -2] you can write: [ind[i] for i in indexes_of_ind] Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: method names in __slots__ ??
John Machin wrote in news:1167008799.074885.250770@ 73g2000cwn.googlegroups.com in comp.lang.python: > Given a = Adder(), > a.tally = 0 > gets AttributeError: 'Adder' object attribute 'tally' is read-only > a.notinslots = 1 > gets AttributeError: 'Adder' object attribute 'notinslots' is read-only > > So is there some magic class-fu going down here, or is this just a > waste of memory space in the instances? > Haven't you, with your 2 examples above, answered your own question ? Clearly from your example it doesn't make any difference if you add a class attribute to the slots, one way or another its as if you hadn't put it in there in the first place. This will give the same error, which shows its about class attributes and not just methods: class Adder(object): __slots__ = [ 'class_name' ] class_name = 3 a = Adder() a.class_name = 2 It would seem that the interpreter removes any names it finds as class attribute names from the list it finds in __slots__ before it creates the instance. Of course if my guessing above isn't good enough, we could look at the documentation: http://docs.python.org/ref/slots.html#l2h-218 __slots__ are implemented at the class level by creating descriptors (3.4.2) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment. So its that the __slots__ assignment makes the descriptors and then the subsiquent method defenitions and class attribute bindings remove them. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: method names in __slots__ ??
John Machin wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Rob Williscroft wrote: >> John Machin wrote in news:1167008799.074885.250770@ >> 73g2000cwn.googlegroups.com in comp.lang.python: >> >> > Given a = Adder(), >> > a.tally = 0 >> > gets AttributeError: 'Adder' object attribute 'tally' is read-only >> > a.notinslots = 1 >> > gets AttributeError: 'Adder' object attribute 'notinslots' is >> > read-only >> > >> > So is there some magic class-fu going down here, or is this just a >> > waste of memory space in the instances? >> > >> >> Haven't you, with your 2 examples above, answered your own question ? > > No. > >> >> Clearly from your example it doesn't make any difference if you add >> a class attribute to the slots, one way or another its as if you >> hadn't put it in there in the first place. > > Clearly? Not so. It takes up memory. A list of 1 million Adder > instances takes up about 68 Mb (Python 2.5 on Windows XP). With the > method names removed from the __slots__, it takes only about 44 Mb. > [For comparison: with no __slots__ at all, it takes about 180 Mb] 68 - 44 = 24 24 / 4 = 6 So thats 6 pointers for 5 methods, probably 5 pointers and and 4 bytes round up to the nearest allocation unit. So the slots in the instance are staying arround, even though they are no longer accesable (see below). [snip] > It would seem that the interpreter removes any names it finds as >> class attribute names from the list it finds in __slots__ before it >> creates the instance. > > It doesn't seem so to me. If it did that, the memory usage would not > increase. It was a guess, and an incorrect guess, but thats why I quoted the docs below. > >> >> Of course if my guessing above isn't good enough, we could look at >> the documentation: >> >> http://docs.python.org/ref/slots.html#l2h-218 >> >> __slots__ are implemented at the class level by creating descriptors >> (3.4.2) for each variable name. As a result, class attributes cannot >> be used to set default values for instance variables defined by >> __slots__; otherwise, the class attribute would overwrite the >> descriptor assignment. > > I have read that, before I posted. Asides: > (1) It would be useful if it stated the empirically determined fact > that the result is that the class attribute is thusly made read-only. > (2) The second sentence is not a model of clarity. > > In any case I can't see how the paragraph gives any support for your > next statement: > >> >> So its that the __slots__ assignment makes the descriptors and then >> the subsiquent method defenitions and class attribute bindings remove >> them. > > Errrmmm ... if the descriptors are removed, how is it that the > behaviour is read-only? The descriptors are part of the class object, they are removed when the class attributes are rebound, further rebinding of the class attributes will work fine: Adder.tally = 0 They are not assignable in the instance as the class descriptors that would have forwarded the assignment to the instances slots have been replaced. The memory usage is higher because the slots in the instance are still there even though the descriptors that would allow them to be assigned have been removed. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: where to find wx package
siggi wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi all, > > a newbie question: > > I have a program gui03A.py using wxPython, importing it such: > "from wxPython.wx import *" > > The program works, but I get the warning message: > > "gui03A.py:4: DeprecationWarning: The wxPython compatibility package > is no longer automatically generated or activly maintained. Please > switch to the wx package as soon as possible." > > However, after extensive searching on www.python.org and Googling the > web, I do not find any package with "wx" as its only name. > > Where can I get the wx package (for win32 XP)? The "wx package" talked about above is also part of WxPython, so you have already got it. To import it use: import wx You will need to translate all (well most) identifiers in your programme from wxBlah to wx.Blah so: class MyFrame( wxFrame ): pass becomes class MyFrame( wx.Frame ): pass Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Get the current date, python 2.2
On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote: > Using python 2.2 what is the simplest way to get the current date value? > I have looked in so many places. The question is often asked and the > usual response indicates how to get the current date and time like > > now = time.localtime() > > I want just the date, like 2007-06-15. The value will go into a > postgresql Date type column. >>> import datetime >>> d = datetime.date.today() >>> d.isoformat() '2007-06-15' >>> Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Get the current date, python 2.2
On Fri, 15 Jun 2007 14:46:20 -0700, nano wrote: > In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] > says... >> On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote: >> >> > Using python 2.2 what is the simplest way to get the current date >> > value? I have looked in so many places. The question is often asked >> > and the usual response indicates how to get the current date and time >> > like >> > >> > now = time.localtime() >> > >> > I want just the date, like 2007-06-15. The value will go into a >> > postgresql Date type column. >> >> >>> import datetime >> >>> d = datetime.date.today() >> >>> d.isoformat() >> '2007-06-15' >> >>> >> >>> >> Rob. >> > Thanks, I'd read that today() was only good for 2.3? Right I missed that, though its actually the datetime module that is new in 2.3. This should do though: >>> import time >>> time.strftime( "%Y-%m-%d" ) '2007-06-15' >>> -- Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use the config parser?
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Hi, > I need a specific example. I have seen the docs, but I don't all the > stuffs there. > > from ConfigParser import ConfigParser > Now I want to know how to read a section, a section attribute's value, > and to write thoses back after reading. > ConfigParser is derived from RawConfigParser, so you need to look at RawConfigParser's docs here: http://docs.python.org/lib/RawConfigParser-objects.html Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when using Custom Exception defined in a different python module.
wrote in news:[EMAIL PROTECTED] in
comp.lang.python:
> Hi,
>
> I am hitting this error consistently and don't know why it's
> happening. I would like to define all exceptions for my project in one
> file and use them across the project. Here's a sample -
>
> exceptions.py -
> from exceptions import *
> raise MyException("Raise custom error")
>
> When the above is run, I get the following error -
> NameError: global name 'MyException' is not defined
When you get this kind of error, goto a python prompt
(type python at a command prompt, or click on IDLE)
and try this:
>>> import exceptions
>>> help( exceptions )
I got this response (clipped):
Help on built-in module exceptions:
NAME
exceptions - Python's standard exception class hierarchy.
Another common module name to avoid is "test".
Rob.
--
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: tkinter get widget option value
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > If I have a button widget > > w = Button(root, text = "Button", state = 'disabled') > > How can I get the value of option 'state' from the widget 'w'. > I want something like -- > > print w.state >> to print out >> 'disabled' > print w.cget( "state" ) Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > >>> [] == [] > True > >>> ['-o'] == [] > False > >>> ['-o'] == False > False > >>> To test wether something is true use if. To test wether something is false use if not. The python values "True" and "False" are for when you need to *store* a boolean value (for later testing). I you want to to see if an arbitry expression would test as true or false at the interactive prompt use bool(): >>> bool([]) False >>> bool(['-o']) True >>> There is *never* any need to write things like: expression == True or: expression == False Once you stop doing this things will become much simpler. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Is wsgi ready for prime time?
Ron Garret wrote in news:rNOSPAMon-B77D6B.12263417052007 @news.gha.chartermi.net in comp.lang.python: >> PACKAGE CONTENTS >> handlers >> headers >> simple_server >> util >> validate >> >> Reading the documentation can be useful sometimes. Recommending >> http://docs.python.org/lib/module-wsgiref.html, too. > > I did read the documentation, but the documentation does not seem to > reflect reality, e.g.: > wsgiref.util > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'util' > IDLE 1.2 >>> import wsgiref.util >>> wsgiref.util >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Connection acception with confirmation
no`name` wrote in news:[EMAIL PROTECTED] in comp.lang.python: > maybe someone have some ideas how to block first stdin in main > function and get stdin from the thread when here is a new connection? > No, but you could instead use a Queue: http://docs.python.org/lib/module-Queue.html so that your main thread reads stdin and then uses an instance of Queue to post the 'y's and 'n's it recives to your server thread. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
