Re: Can't do a multiline assignment!
On 17 avr, 18:19, [EMAIL PROTECTED] wrote: > On Apr 17, 10:54 am, [EMAIL PROTECTED] wrote: > > > On 17 avr, 17:40, [EMAIL PROTECTED] wrote: > > > Out of sheer curiosity, why do you need thirty (hand-specified and > > dutifully commented) names to the same constant object if you know > > there will always be only one object? > > I'm building a web server. The many variables are names of header > fields. One part of the code looks like this (or at least I'd like it > to): > > class RequestHeadersManager: > > # General header fields > Cache_Control = \ > Connection = \ > Date= \ > Pragma = \ > Trailer = \ > Transfer_Encoding = \ > Upgrade = \ > Via = \ > Warning = \ > > # Request header fields > Accept = \ > Accept_Charset = \ > Accept_Encoding = \ > Accept_Language = \ > Authorization = \ > ... > > Etc etc etc. At the end they'll all be assign to None. Then, when > initialized, __init__() will the the string of headers, parse them, > and use those variables shown above to assign to the header values. Of > course a normal request won't include all of those headers, so the > others will remain None. That's what I want. Ah, so they are not constant, I was mislead by the name 'CONSTANTn' in your OP. But why would you insist on: """ # helpful comment CONSTANT1 = \ # there too CONSTANT2 = \ CONSTANT3 = \ None """ rather than: """ # helpful comment CONSTANT1 = None # there too CONSTANT2 = None CONSTANT3 = None """ or even: """ CONSTANT = None # helpful comment CONSTANT1 = CONSTANT # there too CONSTANT2 = CONSTANT CONSTANT3 = CONSTANT """ (hopefully you don't consider those names in your code. ^ ^) -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't do a multiline assignment!
On 17 avr, 17:40, [EMAIL PROTECTED] wrote: > > Yuck! No way!! If you *want* to make your code that hard to read, I'm > > sure you can find lots of ways to do so, even in Python, but don't > > expect Python to change to help you toward such a dubious goal. > > Well, my actual code doesn't look like that. Trust me, I like clean > code. > > > Seriously, examine your motivations for wanting such a syntax. Does it > > make the code more readable? (Absolutely not.) Does it make it more > > maintainable. (Certainly not -- consider it you needed to change > > CONSTANT2 to a different value some time in the future.) > > Yes, it makes it more readable. And yes, it does make it (a lot) more > maintainable. Mainly because I don't have those four variables, I have > about thirty. And I think I won't need to one or two of them, but > maybe all of them at once. Out of sheer curiosity, why do you need thirty (hand-specified and dutifully commented) names to the same constant object if you know there will always be only one object? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and stale file handles
On 17 avr, 14:43, [EMAIL PROTECTED] wrote: > On 17 Apr, 04:22, tgiles <[EMAIL PROTECTED]> wrote: > > > > > Hi, All! > > > I started back programming Python again after a hiatus of several > > years and run into a sticky problem that I can't seem to fix, > > regardless of how hard I try- it it starts with tailing a log file. > > > Basically, I'm trying to tail a log file and send the contents > > elsewhere in the script (here, I call it processor()). My first > > iteration below works perfectly fine- as long as the log file itself > > (logfile.log) keeps getting written to. > > > I have a shell script constantly writes to the logfile.log... If I > > happen to kill it off and restart it (overwriting the log file with > > more entries) then the python script will stop sending anything at all > > out. > > > import time, os > > > def processor(message,address): > > #do something clever here > > > #Set the filename and open the file > > filename = 'logfile.log' > > file = open(filename,'r') > > > #Find the size of the file and move to the end > > st_results = os.stat(filename) > > st_size = st_results[6] > > file.seek(st_size) > > > while 1: > > where = file.tell() > > line = file.readline() > > if not line: > > time.sleep(1) > > file.seek(where) > > else: > > print line, # already has newline > > data = line > > if not data: > > break > > else: > > processor(data,addr) > > print "Sending message '",data,"'." > > > someotherstuffhere() > > > === > > > This is perfectly normal behavior since the same thing happens when I > > do a tail -f on the log file. However, I was hoping to build in a bit > > of cleverness in the python script- that it would note that there was > > a change in the log file and could compensate for it. > > > So, I wrote up a new script that opens the file to begin with, > > attempts to do a quick file measurement of the file (to see if it's > > suddenly stuck) and then reopen the log file if there's something > > dodgy going on. > > > However, it's not quite working the way that I really intended it to. > > It will either start reading the file from the beginning (instead of > > tailing from the end) or just sit there confuzzled until I kill it > > off. > > > === > > > import time, os > > > filename = logfile.log > > > def processor(message): > > # do something clever here > > > def checkfile(filename): > > file = open(filename,'r') > > print "checking file, first pass" > > pass1 = os.stat(filename) > > pass1_size = pass1[6] > > > time.sleep(5) > > > print "file check, 2nd pass" > > pass2 = os.stat(filename) > > pass2_size = pass2[6] > > if pass1_size == pass2_size: > > print "reopening file" > > file.close() > > file = open(filename,'r') > > else: > > print "file is OK" > > pass > > > while 1: > > checkfile(filename) > > where = file.tell() > > line = file.readline() > > print "reading file", where > > if not line: > > print "sleeping here" > > time.sleep(5) > > print "seeking file here" > > file.seek(where) > > else: > > # print line, # already has newline > > data = line > > print "readying line" > > if not data: > > print "no data, breaking here" > > break > > else: > > print "sending line" > > processor(data) > > > So, have any thoughts on how to keep a Python script from bugging out > > after a tailed file has been refreshed? I'd love to hear any thoughts > > you my have on the matter, even if it's of the 'that's the way things > > work' variety. > > > Cheers, and thanks in advance for any ideas on how to get around the > > issue. > > > tom > > Possibly, restarting the program that writes the log file creates a > new file rather than > appending to the old one?? It seems at least the op should definitely reopen the file: # create a file In [322]: f1 = open("test.txt", 'w') In [323]: f1.write("test\n") In [324]: f1.close() # check content of file In [325]: f_test1 = open("test.txt") In [326]: f_test1.readline() Out[326]: 'test\n' # check twice, we never know In [327]: f_test1.seek(0) In [328]: f_test1.readline() Out[328]: 'test\n' # rewrite over the same file In [329]: f1 = open("test.txt", 'w') In [330]: f1.write("new test\n") In [331]: f1.close() # check if ok In [332]: f_test2 = open("test.txt") In [333]: f_test2.readline() Out[333]: 'new test\n' # first file object has not seen the change In [334]: f_test1.seek(0) In [335]: f_test1.readline() Out[335]: 'test\n' -- http://mail.python.org/mailman/listinfo/python-list
Re: def power, problem when raising power to decimals
On 17 avr, 00:49, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Wed, 16 Apr 2008 19:21:18 -0300, John Machin <[EMAIL PROTECTED]> > escribió: > > > [EMAIL PROTECTED] wrote: > >> also i found a link which states 0^0 isnt 1 even though every > >> calculator ive tried says it is. > >> it doesnt say what it is but i presume 0 then. > >> but it seems the dude is wrong and it is 1? > > > Of the possible results of 0 ** 0 (i.e. 1, 0, and NaN), 1 seems to be > > the least implausible. It allows X ** 0 to be 1 for all X. > > But a result of 0 would allow 0 ** X to be 0 for all X. (btw, this is the > reason lim(x**x) for x->0 does not exist) lim(x**x) for x->0+ is well defined, exists and equals 1. [1] As x**x is continuous in 0+, it is widely customary to have: 0**0:=1 [1] Recall that x**x := exp(x*log(x)) The limit of x*log(x) for x->0 is 0 [2] therefore lim(x**x) for x->0 is 1. [2] Let y = 1/x; x*log(x)= -log(y)/y and the limit of log(y)/y for y-> +inf is 0. -- http://mail.python.org/mailman/listinfo/python-list
Re: vary number of loops
On 16 avr, 15:31, [EMAIL PROTECTED] wrote: > Hi everyone, > > I'm new to Python and the notion of lambda, and I'm trying to write a > function that would have a varying number of nested for loops > depending on parameter n. This just smells like a job for lambda for > me, but I can't figure out how to do it. Any hint? > > For example, for n=2, I want the function to look something like: > > def foo(2) >generate 2 sets of elements A, B ># mix elements by: >for a_elt in A > for b_elt in B > form all combinations of them > > If n=3, I want to have 3 sets of elements and mix them up using 3 for > loops. > > Any help is greatly appreciated, > > nullgraph You can try recursion in a more classic manner: In [283]: def foo(n): .: def bar(n): .: my_elts = xrange(2) .: if n<=0: .: raise StopIteration .: elif n<=1: .: for elt in my_elts: .: yield (elt,) .: else: .: for elt in my_elts: .: for o_elt in bar(n-1): .: yield (elt,)+o_elt .: for elt in bar(n): .: print elt .: In [284]: foo(2) (0, 0) (0, 1) (1, 0) (1, 1) In [285]: foo(3) (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) In this case, I have an inner function to generate the whole set of elements and then an outer loop to process them. Note that you can have the generation of my_elts depend on rank n of recursion (that is the index of the set in your list). -- http://mail.python.org/mailman/listinfo/python-list
Re: insert python script in current script
On 16 avr, 09:42, "Prashant" <[EMAIL PROTECTED]> wrote: > I was wondering is there any way to do this: > > I have written a class in python and __init__ goes like this: > > def __init__(self): > > self.name = 'jack' > self.age = 50 > > import data > > now here there is data.py in the same directory and contents are like: > > self.address = 'your address' > self.status = 'single' > > The problem is 'self' is giving some error here. I need to know if > somehow I can do this. It's like inserting the script as it's part of > the file itself. The purpose of import is to build a module object, which implies executing the module file but in a new context. If you simply want to execute some code in a file, you can try execfile("filename"): In [243]: class A(object): .: def __init__(self): .: execfile("test.py") .: In [244]: a=A() In [245]: a.a Out[245]: 1 In [246]: open("test.py").read() Out[246]: 'self.a = 1\n' But do you really want to execute some arbitrary code or to initialize values with some kind of configuration file? > > Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: use object method without initializing object
On 15 avr, 17:43, Robert Bossy <[EMAIL PROTECTED]> wrote: > Reckoner wrote: > > would it be possible to use one of an object's methods without > > initializing the object? > > > In other words, if I have: > > > class Test: > > def __init__(self): > > print 'init' > > def foo(self): > > print 'foo' > > > and I want to use the foo function without hitting the > > initialize constructor function. > > > Is this possible? > > Hi, > > Yes. It is possible and it is called "class method". That is to say, it > is a method bound to the class, and not to the class instances. > In pragmatic terms, class methods have three differences from instance > methods: >1) You have to declare a classmethod as a classmethod with the > classmethod() function, or the @classmethod decorator. >2) The first argument is not the instance but the class: to mark this > clearly, it is usually named cls, instead of self. >3) Classmethods are called with class objects, which looks like this: > ClassName.class_method_name(...). > > In your example, this becomes: > > class Test(object): > def __init__(self): > print 'init' > @classmethod > def foo(cls): > print 'foo' > > Now call foo without instantiating a Test: > Test.foo() To be complete, you can also define a static method that will not even be passed the class as argument: In [217]: class Test(object): .: def __init__(self): .: print 'init' .: @staticmethod .: def foo(): .: print 'foo' .: In [218]: Test.foo() foo -- http://mail.python.org/mailman/listinfo/python-list
Re: use object method without initializing object
On 15 avr, 17:27, Reckoner <[EMAIL PROTECTED]> wrote: > would it be possible to use one of an object's methods without > initializing the object? > > In other words, if I have: > > class Test: > def __init__(self): > print 'init' > def foo(self): > print 'foo' > > and I want to use the foo function without hitting the > initialize constructor function. > > Is this possible? Yes: In [214]: class Test: .: def foo(self): .: print 'foo' .: In [215]: t = Test() In [216]: t.foo() foo -- http://mail.python.org/mailman/listinfo/python-list
Re: Rounding a number to nearest even
On 14 avr, 20:02, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote: > On Fri, 2008-04-11 at 03:14 -0700, bdsatish wrote: > > The built-in function round( ) will always "round up", that is 1.5 is > > rounded to 2.0 and 2.5 is rounded to 3.0. > > > If I want to round to the nearest even, that is > > > my_round(1.5) = 2# As expected > > my_round(2.5) = 2# Not 3, which is an odd num > > > I'm interested in rounding numbers of the form "x.5" depending upon > > whether x is odd or even. Any idea about how to implement it ? > > This seams to work fine: > evenRound = lambda f: round(f/2.)*2 That was the solution I proposed first but it is inadequate since the op does not want 3 to be rounded to 4. If you're interested in this discussion, I kindly suggest you read the whole thread: many interesting proposals and discussions have ensued. -- http://mail.python.org/mailman/listinfo/python-list
Re: eval modifies passed dict
On 14 avr, 18:05, Duncan Booth <[EMAIL PROTECTED]> wrote: > Janto Dreijer <[EMAIL PROTECTED]> wrote: > > It seems eval is modifying the passed in locals/globals. This is > > behaviour I did not expect and is really messing up my web.py app. > > > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > d = dict(a=1) > d.keys() > > ['a'] > eval("a", d) > > 1 > d.keys() > > ['a', '__builtins__'] > > > That can't be right. > > That can exactly be right. > > The current document is (I think) wrong or at the least misleading. It > says: > > > If the globals dictionary is present and lacks '__builtins__', the > > current globals are copied into globals before expression is parsed. > > I think it should say: > > > If the globals dictionary is present and lacks '__builtins__', the > > current value of __builtins__ is added to globals before expression > > is parsed. > > i.e. only a single variable is assigned, other globals aren't copied. Indeed: Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> globals().keys() ['__builtins__', '__name__', '__doc__'] >>> b = 2 >>> d = {'a': 1} >>> eval('a', d) 1 >>> d.keys() ['a', '__builtins__'] -- http://mail.python.org/mailman/listinfo/python-list
Re: eval modifies passed dict
On 14 avr, 17:23, Janto Dreijer <[EMAIL PROTECTED]> wrote: > It seems eval is modifying the passed in locals/globals. This is > behaviour I did not expect and is really messing up my web.py app. > > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> d = > dict(a=1) > >>> d.keys() > ['a'] > >>> eval("a", d) > 1 > >>> d.keys() > > ['a', '__builtins__'] > > That can't be right. >From the documentation of eval[1] "If the globals dictionary is present and lacks '__builtins__', the current globals are copied into globals before expression is parsed." [1]http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Rounding a number to nearest even
On 11 avr, 14:14, Gerard Flanagan <[EMAIL PROTECTED]> wrote: > On Apr 11, 2:05 pm, Gerard Flanagan <[EMAIL PROTECTED]> wrote: > > > On Apr 11, 12:14 pm, bdsatish <[EMAIL PROTECTED]> wrote: > > > > The built-in function round( ) will always "round up", that is 1.5 is > > > rounded to 2.0 and 2.5 is rounded to 3.0. > > > > If I want to round to the nearest even, that is > > > > my_round(1.5) = 2# As expected > > > my_round(2.5) = 2# Not 3, which is an odd num > > > > I'm interested in rounding numbers of the form "x.5" depending upon > > > whether x is odd or even. Any idea about how to implement it ? > In fact you can avoid the call to the builtin round: Alternatively, you can avoid the test using both divmod and round: In [55]: def myround(x): .: d, m = divmod(x, 2) .: return 2*d + 1 + round(m-1) .: In [58]: assert myround(3.2) == 3 In [59]: assert myround(3.6) == 4 In [60]: assert myround(3.5) == 4 In [61]: assert myround(2.5) == 2 In [62]: assert myround(-0.5) == 0.0 In [63]: assert myround(-1.5) == -2.0 In [64]: assert myround(-1.3) == -1.0 In [65]: assert myround(-1.8) == -2 In [66]: assert myround(-2.5) == -2.0 -- http://mail.python.org/mailman/listinfo/python-list
Re: Rounding a number to nearest even
On 11 avr, 12:14, bdsatish <[EMAIL PROTECTED]> wrote: > The built-in function round( ) will always "round up", that is 1.5 is > rounded to 2.0 and 2.5 is rounded to 3.0. > > If I want to round to the nearest even, that is > > my_round(1.5) = 2# As expected > my_round(2.5) = 2# Not 3, which is an odd num > > I'm interested in rounding numbers of the form "x.5" depending upon > whether x is odd or even. Any idea about how to implement it ? When you say "round to the nearest even", you mean new_round(3) <> 3? Is so, you can try: In [37]: def new_round(x): : return round(x/2.)*2 : In [38]: new_round(1.5) Out[38]: 2.0 In [39]: new_round(2.5) Out[39]: 2.0 In [40]: new_round(3) Out[40]: 4.0 -- http://mail.python.org/mailman/listinfo/python-list