utf-8 read/write file
Hi! I have big .txt file which i want to read, process and write to another .txt file. I have done script for that, but im having problem with croatian characters (Š,Đ,Ž,Č,Ć). How can I read/write from/to file in utf-8 encoding? I read file with fileinput.input. thanks -- http://mail.python.org/mailman/listinfo/python-list
Numpy compatibility issue (python 2.6)
It seems that some TypeError messages have changed between versions 2.5 and 2.6, e.g.: from math import radians radians () in 2.5, this leads to "radians () takes exactly 1 argument (0 given)" whereas in 2.6, the message is now: "radians () takes exactly one argument (0 given)" I agree that the two messages do have quite similar meanings, but the 2.6 message can no longer be "interpreted" by the _get_nargs function (in numpy/lib/function_base.py) As a result, you can no longer define (same example): v_radians = numpy.vectorize (radians) Anyone already confronted to this problem? Thanks in advance... -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
This work in 3.1+: $ python3 Python 3.1.3 (r313:86834, Nov 28 2010, 11:28:10) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> one_number = 1234567 >>> print('number={:,}'.format(one_number)) number=1,234,567 >>> paz e amor (love and peace), Alysson Bruno === Palmas(TO) Brasil Blog: http://abruno.com Twitter: http://twitter.com/alyssonbruno Facebook: http://www.facebook.com/ProfessorAlyssonBruno = *Meu alterego Escritor:* Leia alguns contos que escrevo, não esqueça de me dar sua opinião: http://goo.gl/Wjn4p <http://goo.gl/AXv1g> = On Tue, May 21, 2013 at 2:44 AM, Ned Deily wrote: > In article , > Carlos Nepomuceno wrote: > > Is there a way to format integers with thousands separator (digit > grouping) > > like the format specifier of str.format()?> > > I'm currently using the following:> > > >>> sys.stdout.write('Number = %s\n' % '{:,.0f}'.format(x)) > > Number = 12,345> > > 'x' is unsigned integer so it's like using a sledgehammer to crack a > nut!> > > I'd like to have something like: > > sys.stdout.write('Number = %,u\n' % x) > > Is that possible? How can I do it if not already available? > > For Python 3.2+ or 2.7, why not just: > > >>> print('Number = {:,}'.format(x)) > Number = 12,345 > > -- > Ned Deily, > n...@acm.org > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
why does dead code costs time?
Hi, I'm interested in compilers optimizations, so I study python compilation process I ran that script: import timeit def f(x): return None def g(x): return None print(x) number = 1 print(timeit.timeit('f(1)',setup="from __main__ import f", number=number)) print(timeit.timeit('g(1)',setup="from __main__ import g", number=number)) print(dis.dis(f)) print(dis.dis(g)) It gives this output: 0.003460251959040761 0.004164454061537981 17 0 LOAD_CONST 0 (None) 3 RETURN_VALUE None 20 0 LOAD_GLOBAL 0 (None) 3 RETURN_VALUE 21 4 LOAD_GLOBAL 1 (print) 7 LOAD_FAST0 (x) 10 CALL_FUNCTION1 (1 positional, 0 keyword pair) 13 POP_TOP None I do not understand why the dead code `print(x)` takes time (~20% in that case). As we see in the opcode, a call to g(1) returns immediately, so there should be no delay at all. Where am i wrong? mmhh... it comes to me now that the gap must be in function loading time... I'll check ceval.c However, isn't there a room for a slight optim here? (in this case, the dead code is obvious, but it may be hidden by complex loops and conditions) Cheers -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: why does dead code costs time?
On Wed, Dec 05, 2012 at 04:15:59PM +, Neil Cerutti wrote: > On 2012-12-05, Bruno Dupuis wrote: > > Hi, > > > > I'm interested in compilers optimizations, so I study python > > compilation process > > > > I ran that script: > > > > import timeit > > > > def f(x): > > return None > > > > def g(x): > > return None > > print(x) > > > > number = 1 > > > > print(timeit.timeit('f(1)',setup="from __main__ import f", > > number=number)) > > print(timeit.timeit('g(1)',setup="from __main__ import g", > > number=number)) > > > > print(dis.dis(f)) > > print(dis.dis(g)) > > > > It gives this output: > > > > 0.003460251959040761 > > 0.004164454061537981 > > 17 0 LOAD_CONST 0 (None) > > 3 RETURN_VALUE > > None > > 20 0 LOAD_GLOBAL 0 (None) > > 3 RETURN_VALUE > > > > 21 4 LOAD_GLOBAL 1 (print) > > 7 LOAD_FAST0 (x) > > 10 CALL_FUNCTION1 (1 positional, 0 keyword > > pair) > > 13 POP_TOP > > None > > > > I do not understand why the dead code `print(x)` takes time (~20% in > > that case). As we see in the opcode, a call to g(1) returns immediately, so > > there should be no delay at all. Where am i wrong? > > > > mmhh... it comes to me now that the gap must be in function loading time... > > I'll check ceval.c > > > > However, isn't there a room for a slight optim here? (in this case, the > > dead code is obvious, but it may be hidden by complex loops and > > conditions) > > Maybe it's the difference between LOAD_CONST and LOAD_GLOBAL. We > can wonder why g uses the latter. Good point! I didn't even noticed that. It's weird... Maybe the difference comes from a peehole optim on f which is not possible on g as g is to complex. > > -- > Neil Cerutti > -- > http://mail.python.org/mailman/listinfo/python-list -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: why does dead code costs time?
On Wed, Dec 05, 2012 at 05:40:51PM +0100, Bruno Dupuis wrote: > On Wed, Dec 05, 2012 at 04:15:59PM +, Neil Cerutti wrote: > > Maybe it's the difference between LOAD_CONST and LOAD_GLOBAL. We > > can wonder why g uses the latter. > > Good point! I didn't even noticed that. It's weird... Maybe the > difference comes from a peehole optim on f which is not possible on g as > g is to complex. > Neil, you were right, thanks. I patched peehole.c to remove this optim, and now the figures are the same. I investigate to find out why the latter function is not optimized the same way (and if it can be, I'll propose a patch for that) -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: How does one make argparse print usage when no options are provided on the command line?
On Wed, Dec 05, 2012 at 08:48:30AM -0800, rh wrote: > I have argparse working with one exception. I wanted the program to print out > usage when no command line options are given. But I only came across > other examples where people didn't use argparse but instead printed out > a separate usage statement. So they used argparse for everything but the > case where no command line args are given. > this is quite raw, but i'd add import sys if len(sys.argv) == 1: sys.argv.append('-h') before I call parser.parse_args() Should work -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: why does dead code costs time?
On Wed, Dec 05, 2012 at 10:59:26AM -0700, Ian Kelly wrote: > On Wed, Dec 5, 2012 at 10:34 AM, Steven D'Aprano > wrote: > > The difference is almost certain between the LOAD_CONST and the > > LOAD_GLOBAL. > > > > As to *why* there is such a difference, I believe that's a leftover from > > early Python days when None was not a keyword and could be reassigned. > > I think this should even be considered a bug, not just a missing > optimization. Consider: This is definitely a bug > >>> globals()['None'] = 42 > >>> def f(x): > ... return None > ... print(x) > ... > >>> f('test') > 42 This one is pretty scary The difference between `return None` and `return` leads to inconsistency and is in contradiction with the specs, AFAIK. I'm glad we pointed this out. -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: why does dead code costs time?
On Wed, Dec 05, 2012 at 03:41:19PM -0500, Terry Reedy wrote: > On 12/5/2012 1:24 PM, Bruno Dupuis wrote: > >On Wed, Dec 05, 2012 at 10:59:26AM -0700, Ian Kelly wrote: > >>On Wed, Dec 5, 2012 at 10:34 AM, Steven D'Aprano > >> wrote: > >>>The difference is almost certain between the LOAD_CONST and the > >>>LOAD_GLOBAL. > >>> > >>>As to *why* there is such a difference, I believe that's a leftover from > >>>early Python days when None was not a keyword and could be reassigned. > >> > >>I think this should even be considered a bug, not just a missing > >>optimization. Consider: > > > >This is definitely a bug > > > >>>>>globals()['None'] = 42 > >>>>>def f(x): > >>... return None > >>... print(x) > >>... > >>>>>f('test') > >>42 > > > >This one is pretty scary > > > >The difference between `return None` and `return` leads to inconsistency and > >is in contradiction with the specs, AFAIK. I'm glad we pointed this out. > > You did not specify version, but I confirmed in 3.3.0. Please open a > tracker issue. It is also in 2.7 and 3.4 head, I didn't test other versions. I forgot to mention here the issue I have just opened: http://bugs.python.org/issue16619 -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: why does dead code costs time?
I added a patch on the issue tracker. It solves the bug for short (<32700 bytes) functions ref : http://bugs.python.org/file28217/16619-1.patch -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused compare function :)
On Wed, Dec 05, 2012 at 11:50:49PM +0100, Anatoli Hristov wrote: > I'm confused again with a compare update function. The problem is that > my function does not work at all and I don't get it where it comes > from. > > in my DB I have total of 754 products. when I run the function is says: > Total updated: 754 > Total not found with in the distributor: 747 > I just don't get it, can you find my mistake ? > > Thanks in advance > > def Change_price(): > total = 0 > tnf = 0 > for row in DB: # DB is mySQL DB, logically I get out 1 SKU and I > compare it with next loop > isku = row["sku"] > isku = isku.lower() > iprice = row["price"] > iprice = int(iprice) > found = 0 > try: > for x in PRICELIST:# here is my next loop in a CSV file > which is allready in a list PRICELIST > try: > dprice = x[6] > dprice = dprice.replace(",",".") # As in the > PRICELIST the prices are with commas I replace the comma as python > request it > dprice = float(dprice) > newprice = round(dprice)*1.10 > dsku = x[4] > dsku = dsku.lower() > stock = int(x[7]) > if isku == dsku and newprice < int(iprice):# If > found the coresponded SKU and the price is higher than the one in the > CSV I update the price > print dsku, x[6], dprice, newprice > Update_SQL(newprice, isku)# goes to the SQL Update > print isku, newprice > if isku == dsku:# Just a check to see if it works > print "Found %s" %dsku > found = 1 > else: > found = 0 > except IndexError: > pass > except ValueError: > pass > except TypeError: > pass > except IndexError: > pass > if found == 1: > print "%s This is match" % isku > if found == 0: > print "%s Not found" % isku > tnf = tnf +1 > total = total +1 > print "Total updated: %s" % total > print"Total not found with in the distributor: %s" % tnf I tried, I swear I did try, I didn't understand the whole algorithm of the function. However, in a first sight, I find it way to deeply nested. def ... for ... try ... for ... if ... if. Can't you split it in several function, or in methods of a callable class? Somtimes it's finally much more clear and the errors become obvious. Another advice: never ever except XXXError: pass at least log, or count, or warn, or anything, but don't pass. I bet your missing products have disapeared into those black holes. mmmh, now, i see that you set found to 1 only if newprice http://mail.python.org/mailman/listinfo/python-list
Re: Confused compare function :)
On Thu, Dec 06, 2012 at 04:32:34AM +, Steven D'Aprano wrote: > On Thu, 06 Dec 2012 03:22:53 +, Rotwang wrote: > > > On 06/12/2012 00:19, Bruno Dupuis wrote: > >> [...] > >> > >> Another advice: never ever > >> > >> except XXXError: > >> pass > >> > >> at least log, or count, or warn, or anything, but don't pass. > > > > Really? I've used that kind of thing several times in my code. For > > example, there's a point where I have a list of strings and I want to > > create a list of those ints that are represented in string form in my > > list, so I do this: > > > > listofints = [] > > for k in listofstrings: > > try: > > listofints.append(int(k)) > > except ValueError: > > pass > > > > Another example: I have a dialog box with an entry field where the user > > can specify a colour by entering a string, and a preview box showing the > > colour. I want the preview to automatically update when the user has > > finished entering a valid colour string, so whenever the entry field is > > modified I call this: > > > > def preview(*args): > > try: > > previewbox.config(bg = str(entryfield.get())) > > except tk.TclError: > > pass > > > > Is there a problem with either of the above? If so, what should I do > > instead? > > They're fine. > > Never, ever say that people should never, ever do something. > > > *cough* > Well, dependening on the context (who provides listofstrings?) I would log or count errors on the first one... or not. On the second one, I would split the expression, because (not sure of that point, i didn't import tk for years) previewbox.config and entryfield.get may raise a tk.TclError for different reasons. The point is Exceptions are made for error handling, not for normal workflow. I hate when i read that for example: try: do_stuff(mydict[k]) except KeyError: pass (loads of them in many libraries and frameworks) instead of: if k in mydict: do_stuff(mydict[k]) Note that the performances are better with the latter. There are some exceptions to this, though, like StopIteration For me, it's a rule of thumb, except: pass is possible in situations where I control every input data, and I deeply, exactly know all code interractions. If figuring all this out is longer (it's almost always the case) than typing: log.warning('oops:\n %s' % traceback.format_exc()) I log. It depends also on the context, I'd be more 'permissive' a short script than into a large program, framework, or lib, for the very reason it's easy to know all code interactions. In my coder life, i spent more time debugging silently swallowed exceptions than logging abnormal behaviours. -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to contribute Unicode General Category encoding/decoding
On Thu, Dec 13, 2012 at 01:51:00AM -0800, Pander Musubi wrote: > Hi all, > > I have created some handy code to encode and decode Unicode General > Categories. To which Python Package should I contribute this? > Hi, As said in a recent thread (a graph data structure IIRC), talking about new features is far better if we see the code, so anyone can figure what the code really does. Can you provide a public repository uri or something? Standard lib inclusions are not trivial, it most likely happens for well-known, mature, PyPI packages, or battle-tested code patterns. Therefore, it's often better to make a package on PyPI, or, if the code is too short, to submit your handy chunks on ActiveState. If it deserves a general approbation, it may be included in Python stdlib. Cheers -- Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get the selected text of the webpage in chrome through python ?
On Mon, Jan 07, 2013 at 08:20:28PM -0800, iMath wrote: > How to get the selected text of the webpage in chrome through python ? What you need is a way to get selected text from wherever it comes. The way to do this depends on your graphical environment. If you use X, i'd make a a quick and dirty call to xclip -o, although there must be a pure python implementation which in turn depends on the python framework you play with (gtk/qt/wx/tk/...). Short answer is : it depends on your system, and it may be easier and more portable if you use a graphical toolkit. cheers. -- Bruno Dupuis -- http://mail.python.org/mailman/listinfo/python-list
Instituições que utilizam Python.
Olá, boa tarde! Eu, estou entrando em contato com vocês, pois eu gostaria de saber quais instituições brasileiras usam regularmente Python para o desenvolvimento de suas atividades. Essas instituições podem ser usuários de sistemas desenvolvidos usando a linguagem Python, ou podem ser instituições que criam aplicações para terceiros usando a linguagem Python. Acredito que talvez, vocês contenham uma lista com essas instituições que utilizam Python. Desde já agradeço a sua atenção; Muito Obrigado; Att; Bruno Andrade. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compute working days
Em sábado, 14 de março de 2009 às 13:59:41 UTC-3, Casey escreveu: > How about: > from datetime import date, timedelta > # Define the weekday mnemonics to match the date.weekday function > (MON, TUE, WED, THU, FRI, SAT, SUN) = range(7) > def workdays(start_date, end_date, whichdays=(MON,TUE,WED,THU,FRI)): > ''' > Calculate the number of working days between two dates inclusive > (start_date <= end_date). > The actual working days can be set with the optional whichdays > parameter > (default is MON-FRI) > ''' > delta_days = (end_date - start_date).days + 1 > full_weeks, extra_days = divmod(delta_days, 7) > # num_workdays = how many days/week you work * total # of weeks > num_workdays = (full_weeks + 1) * len(whichdays) > # subtract out any working days that fall in the 'shortened week' > for d in range(1, 8 - extra_days): > if (end_date + timedelta(d)).weekday() in whichdays: > num_workdays -= 1 > return num_workdays Could it include the holidays in Brazil? -- https://mail.python.org/mailman/listinfo/python-list
Python and Flask Book
Hello all, I would like to spread the word about a new Python book I have released, on how to develop a web application using Flask and deploying it on Heroku. It's geared more towards beginners or towards anyone who is willing to learn Python and Flask! I would be very glad if you know of people, friends, or colleagues who are interested in learning Python and could spread words about my book: https://brunooliv.gumroad.com/l/cookpythonbook <https://www.google.com/url?q=https://brunooliv.gumroad.com/l/cookpythonbook&sa=D&source=hangouts&ust=1635502485987000&usg=AOvVaw2RFbMdp7h-toAR8c8BELtO> Best regards, Bruno -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie regular expression and whitespace question
googleboy a écrit : > Hi. > > I am trying to collapse an html table into a single line. Basically, > anytime I see ">" & "<" with nothing but whitespace between them, I'd > like to remove all the whitespace, including newlines. I've read the > how-to and I have tried a bunch of things, but nothing seems to work > for me: > > -- > > table = open(r'D:\path\to\tabletest.txt', 'rb') > strTable = table.read() > > #Below find the different sort of things I have tried, one at a time: > > strTable = strTable.replace(">\s<", "><") #I got this from the module > docs From which module's doc ? ">\s<" is the litteral string ">\s<", not a regular expression. Please re-read the re module doc, and the re howto (you'll find a link to it in the re module's doc...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes
Jeremy Sanders wrote: > Is it possible to implement some sort of "lazy" creation of objects only > when the object is used, but behaving in the same way as the object? Smells like a Proxy pattern... > For instance: > > class Foo: > def __init__(self, val): > """This is really slow.""" > self.num = val > > # this doesn't call Foo.__init__ yet > a = lazyclass(Foo, 6) > > # Foo is only initalised here > print a.num > > What I really want to do is make an object which looks like a numarray, > but only computes its contents the first time it is used. > Here's a Q&D, stupid simple, possibly flawed solution: class LazyProxy(object): def __init__(self, klass, *args, **kwargs): self.__klass = klass self.__args = args self.__kwargs = kwargs self.__subject = None def __lazy_init(self): if self.__subject is None: self.__subject = self.__klass(*self.__args,**self.__kwargs) def __getattr__(self, name): self.__lazy_init() return getattr(self.__subject, name) def __setattr__(self, name, value): # TODO : there's a better way to do this, # but I don't remember it ruight now and # don't have time to search... if name in ['_LazyProxy__klass', '_LazyProxy__args', '_LazyProxy__kwargs', '_LazyProxy__subject']: self.__dict__[name] = value else: self.__lazy_init() setattr(self.__subject, name, value) if __name__ == '__main__': class Greeter(object): def __init__(self, name): self.name = name def greet(self, who): return "hello %s, my name is %s" % (who, self.name) lazy1 = LazyProxy(Greeter, 'toto') print lazy1.greet('titi') lazy2 = LazyProxy(Greeter, 'lolo') lazy2.name = "lili" print lazy2.greet(lazy1.name) Every comment, fix etc welcome. Now there are probably better ways to do this playing with decorators or meta-classes. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes
Jeremy Sanders wrote: > Diez B. Roggisch wrote: > > >>It works - in python 2.4!! I tried subclassing dict, but my >>__getitem__-method wasn't called - most probably because it's a C-type, >>but I don't know for sure. Maybe someone can elaborate on that? > > > Yes - I tried that (see thread below). Unfortunately it needs Python 2.4, > and I can't rely on my users having that. > > Traceback (most recent call last): > File "test.py", line 15, in ? > print eval("10 * a + b", globals(), l) > TypeError: eval() argument 3 must be dict, not Foo > > If you subclass dict it doesn't call the __getitem__ method. Could it work with a UserDict subclass ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Need to pass Object by value into a list
Aaron a écrit : > I have a data sructure setup and I populate it in a loop like so: > > y=0 > while X: >DS.name = "ASDF" >DS.ID = 1234 >list[y] = DS; >y = y + 1 > > print list Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-9150sSF", line 2, in ? while X: NameError: name 'X' is not defined Please post running code. The rule is: - explain what you did - explain what you expected - explain what you've got - post the minimal running code that reproduce the problem Here are a short listing of errors and bad style in this code: 1/ DS is not defined 2/ X is not defined 3/ 'list' is the name of the builtin class list. The list *class* is unsubscriptable. 4/ Assuming you rebound the name 'list' to a list instance (which is a very Bad Thing(tm)), you still can't assign to an inexistant index 5/ even if DS and X were defined, this loop would run forever 6/ In Python, identifiers in uppercase are constants (well... this is only a convention, but convention in Python are part of the language, even if there's nothing to enforce them) 7/ you mix arbitrary naming conventions ('DS.name' vs 'DS.ID', 'X' vs 'y'). Either this is not your real code or you did not try to run this code. In fact, I guess this is not your real code AND you did not try to run it. Please do *yourself* a favor: post running code (I don't mean 'code that don't crash', I mean: 'code that reproduce your real problem'). > This does not work "Does not work" is the worst possible description of a problem. Now effectively, this code (the one you posted, not the one you are describing) crashes for a very obvious reason (see point n°1 above). The code you are describing (which is obviously different...) "works" - it may not behave how you'd expect it to, but this is another problem. > because DS is passed in by reference causing all > entries into the list to change to the most current value. DS is not 'passed by reference', since there is no function call in your code. A reference to the object bound to the name DS is stored (well, I assume this is what happen in your real code) in the list - which is not the same thing. BTW, you need to understand that, in Python, an identifier is just a name bound to a reference to an object. Think of the namespace as a hashtable with names as keys and references to objects as values (this exactly how it's implemented). When it comes to function calls, the *name* is local to the function, but the object referenced by the name is the original object. If you rebind the name (ie: 'assign' another object to it), this change will be local, because the *name* is local. But if you modify the object itself, this will impact the 'original' object, ie: def fun(aList, anotherList): # rebind local name 'aList', original object not impacted aList = [1, 2, 3] # modify ('mutate') object bound to 'anotherList', # original object impacted anotherList.append(42) listOne = [4, 5, 6] listTwo = [7, 8, 9] fun(listOne, listTow) print listOne print listTwo > I cannot > find a "new" function in Python like there is in C++. In C++, 'new' is an operator, not a function. In Python, classes are callable objects (a callable is something like a function - or, should I say, a function is a kind of callable object - everything in Python being an object...) that return an instance when called. So there is no need for a 'new' operator - just call the class object (like you'd call a function), and you'll get an instance. Also, if the class has an '__init__' method, this method will be called after object instanciation, with the arguments passed when calling the class. ie: class Foo(object): def __init__(self, name): self.name = name f = Foo('foo') f.name => 'foo' > How do you do > this in Python? > class Ds(object): def __init__(self, id, name): self.id = id self.name = name x = 42 # or any other integer value # short way ds_list = [Ds(1234, "ASDF") for i in range(x)] print ds_list # verbose way: ds=list = [] for i in range(x): ds_list.append(Ds(1234, "ASDF") print ds_list ds_list[0].name="FOO" print ds_list HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Carrying variables over from function to function
Ivan Shevanski a écrit : > Alright heres my problem. . .Say I want to carry over a variable from > one function to another or even another run of the same function. Is > that possible? Heres a quick example of what I'm talking about. > > def abc(): >x = 1 >y = x + 1 >print y > > def abcd(): >y = x + 1 >print y > > abc() > abcd() > > the output would be: > abc() > > 2 > abcd() > > Traceback (most recent call last): >File "(stdin)", line 1, in ? >File "(stdin)", line 2, in abcd > NameError: global name 'x' is not defined > > > > See, I want y in the second function to equal 4, carrying the x from the > first function over to the next. Is there any way to do this? > Actually, there are at least 3 ways to do it. 1/ Dirty solution: -- x = 0 def abc(): global x x = 1 print x + 1 def abcd(): global x print x + 1 2/ functional solution: --- def make_funcs(): x = 0 def _abc(): x = 1 return x + 1 def _abcd(): return x + 1 return _abc, _abcd abc, abcd = make_funcs() print abc() print abcd() 3/ OO solution: --- class Foo(object): def __init__(self): self._init_x() def _init_x(self): self._x = 1 def abc(self): self._init_x() return self.abcd() def abcd(self): return self._x + 1 f = Foo() print f.abc() print f.abcd() Now guess which are: A/ the pythonic solution B/ the worst possible solution C/ the most arcane solution !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Carrying variables over from function to function
Peter Otten wrote: > Bruno Desthuilliers wrote: > > >>2/ functional solution: >>--- >>def make_funcs(): >>x = 0 >>def _abc(): >>x = 1 >>return x + 1 >>def _abcd(): >>return x + 1 >>return _abc, _abcd >> >>abc, abcd = make_funcs() >>print abc() >>print abcd() > > > The x in function _abc() is not the same as that in make_funcs() and _abcd() > as you can easily verify by modifying _abc() to > > def _abc(): > x # raises UnboundLocalError > x = 1 > return x + 1 > > Once a variable is assigned a value the compiler treats it as local to that > function. Closed-over variables are therefore always read-only, much to the > chagrin of Lisp-lovers. Doh :( I wasn't aware of this limitation (I thought I had done this before in Python and it was working, but it seems that I suffer a severe case of MemoryCorruption...). And this will also teach me to *always* test my code before posting (I usually do...). Sorry, my bad :( Thanks for the correction -- bruno desthuilliers ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 350: Codetags
On 2005-09-26, Micah Elliott <[EMAIL PROTECTED]> wrote: > > :Objection: I aesthetically dislike for the comment to be terminated > with <> in the empty field case. > > :Defense: It is necessary to have a terminator since codetags may be > followed by non-codetag comments. Or codetags could be limited to > a single line, but that's prohibitive. I can't think of any > single-character terminator that is appropriate and significantly > better than <>. Maybe [EMAIL PROTECTED] could be a terminator, but then > most > codetags will have an unnecessary @. > > What about allowing a blank line between codetag and following comment as valid terminator of codetag? ie: # NOTE: see spec xyz for Transport Protocol description # how many times to retry open of a recordset DB_OPEN_RETRYS = 3 Also if the codetag is immediatly followed by code, all the commentlines from start of the tag to the beginning of code could be considered part of the codetag. # TODO: catch possible exception here # (in case someone deletes file) f = open("data") -- http://mail.python.org/mailman/listinfo/python-list
Re: Module organization
Lasse Vågsæther Karlsen wrote: > I am slowly learning Python and I'm already starting to write some minor > modules for myself. Undoubtedly there are better modules available > either built-in or 3rd party that do the same as mine and much more but > I need to learn it one way or another anyway. > > What I'm wondering about is module organization. > > I created my own directory for storing my modules and added the full > path to this to PYTHONPATH (Windows XP platform). > > This means that "import modulename" works for my modules now. > > However, the name of my module is "db" or "database", a module name that > will likely conflict with other modules I might encounter later. > > As such, I was thinking of doing the same that the "distutils" set of > modules have done, by creating a subdirectory and storing them there, so > I created a "lvk" directory in that directory of mine and moved the > module in there, but now "import lvk.modulename" doesn't find the module. What you want is a package: http://www.python.org/doc/current/tut/node8.html#SECTION00840 > Is there a trick to this? Do I have to store my own modules beneath > C:\Python24\Lib? or can I use the organization I've tried just with some > minor fixes to make python locate my modules? briefly put, add an (even empty) __init__.py file in your lvk directory, and it should work fine (minus potential import problems in your modules, but that should be easy to fix...) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Zope3 Examples?
Markus Wankus wrote: > Hi All, > > Does anyone know of any good Zope3 examples? Ask the Zope mailing-list. Zope is a world by itself, and is usually not discussed here. BTW, Zope3 is a really really new thing, so you won't find much existing apps. When it's said that it offers 'the best from Plone', (s/plone/cmf/ IMHO), it's about framework/system architecture, not OOTB application. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
James A. Donald wrote: > I am contemplating getting into Python, which is used by engineers I > admire - google and Bram Cohen, but was horrified "horrified" ??? Ok, so I'll give you more reasons to be 'horrified': - no private/protected/public access restriction - it's just a matter of conventions ('_myvar' -> protected, '__myvar' -> private) - no constants (here again just a convention : a name in all uppercase is considered a constant - but nothing will prevent anyone to modify it) - possibility to add/delete attributes to an object at runtime - possibility to modify a class at runtime - possibility to change the class of an object at runtime - possibility to rebind a function name at runtime If you find all this horrifying too, then hi-level dynamic languages are not for you !-) > to read > > "no variable or argument declarations are necessary." No declarative static typing is necessary - which not the same thing. In Python, type informations belong to the object, not to names that are bound to the object. Of course you cannot use a variable that is not defined ('defining' a variable in Python being just a matter of binding a value to a name). > Surely that means that if I misspell a variable name, my program will > mysteriously fail to work with no error message. Depends. If you try to use an undefined variable, you'll get a name error: >>> print var1 # var1 is undefined at this stage Traceback (most recent call last): File "", line 1, in ? NameError: name 'var1' is not defined Now if the typo is on the LHS, you'll just create a new name in the current namespace: myvra = 42 # should have been 'myvar' and not 'myvra' But you'll usually discover it pretty soon: print myvar Traceback (most recent call last): File "", line 1, in ? NameError: name 'myvar' is not defined > If you don't declare variables, you can inadvertently re-use an > variable used in an enclosing context when you don't intend to, yes, but this is quite uncommon. The 'enclosing context' is composed of the 'global' (which should be named 'module') namespace and the local namespace. Using globals is bad style, so it shouldn't be too much of a concern, but anyway trying to *assign* to a var living in the global namespace without having previously declared the name as global will not overwrite the global variable - only create a local name that'll shadow the global one. Since Python is very expressive, functions code tend to be small, so the chances of inadvertently reuse a local name are usually pretty low. Now we have the problem of shadowing inherited attributes in OO. But then the same problem exists in most statically typed OOPLs. > or > inadvertently reference a new variable (a typo) when you intended to > reference an existing variable. Nope. Trying to 'reference' an undefined name raises a name error. > What can one do to swiftly detect this type of bug? 1/ write small, well-decoupled code 2/ use pychecker or pylint 3/ write unit tests You'll probably find - as I did - that this combination (dynamic typing + [pylint|pychecker] + unit tests) usually leads to fewer bugs than just relying on declarative static typing. What you fear can become reality with some (poorly designed IMHO) scripting languages like PHP, but should not be a concern with Python. Try working with it (and not to fight agaisnt it), and you'll see by yourself if it fits you. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
James A. Donald wrote: > James A. Donald: > >> > Surely that means that if I misspell a variable name, my program will >> > mysteriously fail to work with no error message. > > > On Sun, 02 Oct 2005 17:11:13 -0400, Jean-François Doyon > >>No, the error message will be pretty clear actually :) > > > Now why, I wonder, does this loop never end :-) > egold = 0 > while egold < 10: > ego1d = egold+1 > A more pythonic style would be: egold = 0 while egold < 10: ego1d += 1 And that one raises a name error !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
[EMAIL PROTECTED] wrote: > The easiest way to avoid this problem (besides watching for NameError > exceptions) is to use an editor that has automatic name completion. > Eric3 is a good example. So, even though in theory it could be an > issue, I rarely run into this in practice. I don't use emacs automatic completion, and I still rarely (read: 'never') run into this kind of problem in Python. -- bruno desthuilliers ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" -- http://mail.python.org/mailman/listinfo/python-list
Re: Will python never intend to support private, protected and public?
Paul Rubin wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: > >>No, but that is precisely why Python's semi-private variables are >>usually better. Names like _X and class.__X are warnings to the developer >>"use these at your own risk", without preventing developers who need them >>from using them. You have most of the benefits of private variables with >>none of the disadvantages. > > > I'm sorry but I thought the idea was to actually reduce the risk of > bugs, not merely attach the risk to the right person. I'm sorry but you're just plain wrong - at least according to Python's "we're all consenting adults here" philosophy. > If changing the > way a class uses its own private variables breaks an application > because another class was using the private variable unexpectedly, > then that's bad, No, it's just an obvious side-effect of the programmer messing with implementation stuff. He knew from the start it was implementation detail, so he accepted that this may change without notice and break its code. period. > regardless of whether the other class's author was > notified or not. > > It's better to let the compiler automatically flag > these things, than to depend on conventions. Nope. *you* think it's better. Most of us here obviously think that relying on convention is a good (and even better) solution - and the fact is that it works just fine. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Which SQL module to use?
mrstephengross a écrit : > I'd like to do some basic SQL stuff in Python. It seems like there are > a heck of a lot of SQL modules for Python. What's the simplest and > easiest one to use? Probably the one that go with your RDBMS. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Mike Meyer wrote: (snip) > Antoon, at a guess I'd say that Python is the first time you've > encountered a dynamnic language. Being "horrified" at not having > variable declarations, Mike, "being horrified" by the (perceived as...) lack of variable declaration was the OP's reaction, not Antoon's. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: So far
CppNewB wrote: > I am absolutely loving my experience with Python. Even vs. Ruby, the syntax > feels very clean with an emphasis on simplification. > > My only complaint is that there doesn't appear to be a great commercial IDE Why "commercial" ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python interpreter bug
[EMAIL PROTECTED] wrote: > Sorry Fredrik but I don't understand. Just comment out the assert and > you have different results depending on whether an unrelated sort > function is defined. > This seems weird to me ! code snippet: > from random import choice > class OBJ: > def __init__(self,identifier): > self.id=identifier > self.allocated=0 # Your problem begins here... > def __cmp__(self,other): # it continues here > return cmp(other.allocated,self.allocated) > mylist=[OBJ(i) for i in range(20)] > excluded=[obj for obj in mylist if obj.id>choice(range(20))] > for obj in mylist: > if obj in excluded: # and you see it in action here > assert obj.id in [objt.id for objt in excluded] > continue How do you think the "membership" test works ? Could it be possible that it uses the __cmp__ method ? And if so, how do you think your instances will compare knowing that your __cmp__ method will return equality for all the instances in this snippet ? Just change your __init__ method to: def __init__(self,identifier): self.id=identifier self.allocated=identifier and rerun the test. I don't think this is a bug... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's Performance
Laszlo Zsolt Nagy a écrit : > Dave wrote: > >> Hello All, >> >> I would like to gather some information on Python's runtime >> performance. As far as I understand, it deals with a lot of string >> objects. Does it require a lot string processing during program >> execution? How does it handle such time-consuming operations? Is there >> a way to find out how many string operations (perhaps in the >> underlying system) ) it does during program execution? > > > Do you want to know how many internal string operations are done inside > the Python interpreter? I believe it is not a useful information. There > are benchmarks testing the *real performance* of Python. > > For example: http://www.osnews.com/story.php?news_id=5602 > A benchmark stating that Python is interpreted is bullshit. > Les > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's Performance
Alex Stapleton wrote: > > On 9 Oct 2005, at 19:04, Bruno Desthuilliers wrote: > > >> Laszlo Zsolt Nagy a écrit : (snip) >>> Do you want to know how many internal string operations are done inside >>> the Python interpreter? I believe it is not a useful information. There >>> are benchmarks testing the *real performance* of Python. >>> >>> For example: http://www.osnews.com/story.php?news_id=5602 >>> >> >> A benchmark stating that Python is interpreted is bullshit. >> > Except it is interpreted. What is your point? Nope. It's byte-compiled, just like Java. What do you think those .pyc files are exactly ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's Performance
Donn Cave wrote: > Quoth "Fredrik Lundh" <[EMAIL PROTECTED]>: > | Alex Stapleton wrote > | > | > Except it is interpreted. > | > | except that it isn't. Python source code is compiled to byte code, which > | is then executed by a virtual machine. if the byte code for a module is up > | to date, the Python runtime doesn't even look at the source code. > > Fair to say that byte code is interpreted? Seems to require an > application we commonly call an interpreter. If so, Java is interpreted too. The only difference between Java and Python here is that Python is smart enough to call the compiler by itself. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Very dumb question
Laszlo Zsolt Nagy wrote: > I have a program with this code fragment: > >print len(data) >print data[:50] >raise SystemExit > > This prints: > > 20381 > > But if I change 50 to 51 > >print len(data) >print data[:51] >raise SystemExit > > then it prints > > 20381 > !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" > > After all, only the last 50 bytes are printed. The string is the same > (length 20381) in both cases. (snip > I'm sure it is my mistake, but I don't know what am I doing wrong. Do > you have an idea? I assume the code snippets are exact copy/paste so this is not a typo (like print data[51:] ...) - and I can't reproduce it here... even with a string of 20381 characters. mmm... type(data) ??? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie]Is there a module for print object in a readable format?
James Gan wrote: > I want the object printed in a readable format. For example, > x =[a, b, c, [d e]] will be printed as: > x--a > |_b > |_c > |___d >|_e > > I tried pickled, marshel. They do different work. > > Is there another > module which do this kind of job? > pprint -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
Johnny Lee wrote: > Class A: s/C/c/ >def __init__(self): > self.member = 1 > >def getMember(self): > return self.member > > a = A() > > So, is there any difference between a.member and a.getMember? yes : a.member is an integer, a.getMember is a bound method. You could have found this by yourself... Note that the getter/setter plague is useless and unpythonic. Use properties instead if you need to control attributes access. There are decorator idioms to make clean and easy properties, look here: http://wiki.python.org/moin/PythonDecoratorLibrary -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with properties
[EMAIL PROTECTED] wrote: > If you change it to this it works. You should provide a get and a set > function for a property. The OP did: -> command=property(getCommand, setNothing) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: override a property
Robin Becker a écrit : > Is there a way to override a data property in the instance? Do I need to > create another class with the property changed? Do you mean attributes or properties ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Vim capable IDE?
Chris Lasher wrote: > Hello, > Is there a Python-sensitive, Linux compatible IDE out there with > standard bells and whistles (source browser, symbolic debugger, etc.) > but with the action-per-keystroke editing capabilities of Vim? I have > failed to turn up such an IDE in my Googling and IDE project-page > browsing. :-( What about a Python IDE that embed Vim as it's editor ? http://pida.berlios.de/index.php/Main_Page HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: override a property
Robin Becker wrote: > Bruno Desthuilliers wrote: > >> Robin Becker a écrit : >> >>> Is there a way to override a data property in the instance? Do I need >>> to create another class with the property changed? >> >> >> >> Do you mean attributes or properties ? > > > I mean property here. Ok, wasn't sure... And sorry, but I've now answer. > My aim was to create an ObserverProperty class > that would allow adding and subtracting of set/get observers. Could you elaborate ? Or at least give an exemple ? > My current > implementation works fine for properties on the class, but when I need > to specialize an instance I find it's quite hard. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Bryan wrote: > Amol Vaidya wrote: > >> Hi. I am interested in learning a new programming language, and have >> been debating whether to learn Ruby or Python. (snip) > > why don't you do what i did? download ruby and spend a day or two > reading "programming ruby" from www.ruby-lang.org/en. the download > python and spend a day or two reading the python tuturial from > www.python.org. Or better: DiveIntoPython -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Amol Vaidya wrote: > Hi. I am interested in learning a new programming language, and have been > debating whether to learn Ruby or Python. How do these compare and contrast > with one another, and what advantages does one language provide over the > other? I would like to consider as many opinions as I can on this matter > before I start studying either language in depth. Any help/comments are > greatly appreciated. Thanks in advance for your help. The main point about "advantages" is that Python has a larger community, a larger choice of libraries, and is somewhat more mature (which is not surprising since Python is a little bit older than Ruby). Else, both are hi-level highly dynamic object oriented languages, both are fun to program with, and both are easy to get started with. So the best thing to do is to give both a try and go with the one that fits your brain. -- bruno desthuilliers ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularity of blogging tools used by python programmers
Stewart Midwinter a écrit : > I've made a comparison of the relative popularity of blogging tools > used by python programmers. I was surprised by the number of python > developers not using python for their blogs; isn't that like GM > employees driving Toyota cars? > > See my post at: > > http://midtoad.homelinux.org/wp/?p=117 > Could it be say that Python programmers are wise enough to reinvent the wheel ?-) (just kidding...) -- http://mail.python.org/mailman/listinfo/python-list
Re: A macro editor
Tom Anderson wrote: > On Thu, 20 Oct 2005, Diez B. Roggisch wrote: > >> So - _I_ think the better user-experience comes froma well-working >> easy to use REPL to quickly give the scripts a try. > > > I'd agree with that. Which is better, a difficult language with lots of > fancy tools to help you write it, or an easy language? > > I don't know Groovy, but having looked at some examples, it looks like > jave with a makeover, which, compared to python, sounds like a difficult > language. > > As for python vs ruby, i can't really offer any insights on the > languages themselves. Personally, i'd go for python, but that's because > i know python and not ruby. I know a bit of Ruby, and my *very humble* opinion is that Python is easier for beginners - *but* I'm probably (certainly) biased here, so you'd better find some non-programmers having learn Ruby in a similar context and ask them about this (with the buzzword around Rails, you find such people easily...) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Amol Vaidya wrote: > "Casey Hawthorne" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >>What languages do you know already? >> >>What computer science concepts do you know? >> >>What computer programming concepts do you know? >> >> >>Have you heard of Scheme? >> >> >>Ruby is a bit Perl like -- so if you like Perl, chances are you might >>like Ruby. Ruby is a whole lot Smalltalk-like -- so if you like Smalltalk... !-) >>Python is more like Java. Err... Python is more like what Java would have been if Java was a smart dynamic hi-level object oriented language !-) >>I have heard, but have not been able to verify that if a program is >>about >>10,000 lines in C++ >>it is about >>5,000 lines in Java >>and it is about >>3,000 lines in Python (Ruby to?) For a whole lot of common tasks (like file IO etc), the Java/Python loc ratio is between 5/1 and 10/1. Also, not having the dumbest type system in the world, Python is naturally much more generic than Java, which saves a lot of boilerplate code. I think that the real numbers would be much like 5000 lines in Java -> 1000 lines in Python - and probably 5000 -> 500 in some cases. > > I've done a lot of studying on my own, and taken the classes that my > high-school offers. I feel that I have a fairly good understanding of Java, > and basic OO concepts due to that. Err... I wouldn't start another HolyWar, but Java is not that Object Oriented. 'Class-based' would be more appropriate. Python, while not being class-based (ie: it doesn't impose that all code goes into a 'class' statement), is much more an OO language than Java, since in Python *everything* is an object - even functions, classes and modules. This makes a *big* difference. So yes, you may have learned some basic 00 concepts with Java (classes, instances, inheritence and polymorphism), but with Python and/or Ruby, you will probably realize that there's much more in the OO paradigm than all the Java world can dream of. > > Well, I'm not sure what you mean by programming concepts. I'm familiar with > OO through Java, and procedural programming through C. I'd be more detailed, > but I'm not exactly sure what you are asking. Sorry. patterns, metaclasses, aspects, closures, anonymous functions, higher-order functions, multiple dispatch, properties (computed attributes), generators, list expressions... does that ring a bell ? > I have no idea what Scheme is, but I'll cettainly look it up as soon as I'm > done writing this. Scheme is a Lisp dialect - Lisp being one of the oldest programming languages, and one of the most modern programming languages. Whatever the latest overhyped revolutionary new silver bullet buzzword stuff, you can bet your ass Lisp already had it many years ago. Now Lisp never managed to make it to the mainstream... It's a language (well, a familly of languages should I say) that is worth learning, but probably not until you've become familiar with some Python features and idioms. Another language that failed to make it to the mainstream but is worth giving a try is Smalltalk - the father of OOPLs (Simula being the GrandFather). BTW, most of Ruby's feature have been happily stolen from Smalltalk !-) > I've never given Perl a shot. It was another language I considered learning, > but my father's friend told me to go with Python or Ruby. +1 -- bruno desthuilliers ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Michael Ekstrand wrote: > On Friday 21 October 2005 07:07, bruno modulix wrote: > >>>>Python is more like Java. >> >> >>Err... Python is more like what Java would have been if Java was a >>smart dynamic hi-level object oriented language !-) >> > > > +1. Python is easily applicable to most of the problem domain of Java, > but solves problems much more elegantly. It just isn't shipped embedded > in all leading browsers :-(. It's been a long time since I last saw a Java applet on a website. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Python vs Ruby
Scott David Daniels wrote: > bruno modulix wrote: > >> ... Another language that failed to make it to the mainstream but is >> worth giving a try is Smalltalk - the father of OOPLs (Simula being the >> GrandFather). > > I would say Simula is the forefather of modern OOPLs, and Smalltalk is > the toofather. Err... I'm afraid I don't understand this last word (and google have not been of much help here) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Alex Martelli wrote: (snip) > Here's a tiny script showing some similarities and differences: > > def f() > i = 0 > while i < 100 > j = 923567 + i > i += 1 > end > end > > f() > > comment out the 'end' statements, and at colons s/at/add/ > at the end of the def > and while statements, and this is also valid Python. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Zope and Persistence
[EMAIL PROTECTED] wrote: > I don't know if this is the appropriate place to post a Zope question Nope. You'd better use the zope mailing-list for this. > but I figure many here are familiar with it. I'm confused about the > role of the ZMI when it comes to development. As it's name implies, the ZMI is a *management* interface. Real Zope developpement is better made with filesystem "Products" (Zope components). > I want to write a simple > script that logs page hits. That's a typical case of reinventig the square wheel. Ever looked at /log/Z2.log ? It's an apache-like access log. And there are a whole lot of tools for building stats from apache access logs. > I wrote it in what was called a Script > (Python) resource in the ZMI. When I access the page it gives an error > saying that this file cannot import Persistence, etc. Why would you import Persistence in a Python Script ? This is already a persistent object. > This makes sense > but where would I put this script Whereever seems to fit - this depends on your application. > and how would I invoke it? Like any other Zope object. > It is only > supposed to store an integer in Data.fs. Thanks. This is another problem, and I think you'd better start with the zope book. But for you current use case, first have a look at Zope's access log. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Areas in Python
PyPK wrote: > hmm Thats one thing. Also I was thinking of something like benefites of > python over other languages. That's fairly context-dependant *and* subjective. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi All - Newby
Ask wrote: > G'day All, > (snip) Welcome here... > I must admit to much confusion regarding some of the basics, but I'm sure > time, reading, and good advice will get rid of that. at this stage, it's > just working through some examples and getting my head around things. As an > example, if I create a window, I've been unable to force it to be a certain > size, and put a button (widget) at (say) 20,40 (x & y). Is window formatting > possible? As you say, Python runs on a lot of platforms. It also allow the use of a lot of GUI toolkits. So "windows formatting" isn't a Python problem - it's specific to to toolkit you're using. Since we don't know which you're using, there's no way to answer your question. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Python vs Ruby
Scott David Daniels wrote: > bruno modulix wrote: > >> Scott David Daniels wrote: >> >>> bruno modulix wrote: >>> >>>> ... Another language that failed to make it to the mainstream but is >>>> worth giving a try is Smalltalk - the father of OOPLs (Simula being the >>>> GrandFather). >>> >>> I would say Simula is the forefather of modern OOPLs, and Smalltalk is >>> the toofather. >> >> Err... I'm afraid I don't understand this last word (and google have not >> been of much help here) > > > Sorry, I was being too cute by half. tss... > If Simula is the fore father > (4 away) then Smalltalk is half as far (2) away. Hence the "toofather." > "Toofather" by analogy with the homophones "fore" and "four" we use the > homophones "two" and "too". My my my... -- bruno desthuilliers ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Areas in Python
beza1e1 wrote: > let me try. > > 1) ''.join(lots_of_pieces) > > 2) This doesn't even work, if something is removed, the list is too > short. So: > [x for x in somelist if not isbad(x)] > well, list comprehension is Python 2.4 2.2.x IIRC > and 2.3 is the standard in many > OSes, so it is possibly not the most portable solution filter(isbad, somelist) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting Class Attributes
the.theorist a écrit : > I have a small, simple class which contains a dictionary (and some > other stuff, not shown). I then have a container class (Big) that holds > some instances of the simple class. When I try to edit the elements of > the dictionary, all instances obtain those changes; I want each > instance to hold separate entries. > > #--Begin module test.py > class ex: class ex(object): # oldstyle classes are deprecated > def __init__(self, val={}): > self.value = val You didn't search very long. This is one of the most (in)famous Python gotchas: default args are evaluated *only once*, when the function definition is evaluated (at load time). This is also a dirty trick to have a 'static' (as in C) like variable. The solution is quite simple: class ex(object): def __init__(self, val=None): if val is None: val = {} self.value = val (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: security
Mattia Adami a écrit : > Hi to all. > I'm intristing in write a plugin for browsers that can execute python > code. > I know the main problem is security. Many thread were opened about this > in the ng. > I would know if fork python rewriting some library could avoid > problems. I.e. one problem is the possibility to access files. If I > rewrite the open() function so that raises exception if the program try > to access a file out of a defined directory. > I'm sure not a security expert, so please be patient if my question is > stupid. > Thanks to all. I'm not a security expert either, but you may want to have a look at the way Zope 2.x handles this kind of restrictions for TTW scripts. -- http://mail.python.org/mailman/listinfo/python-list
Re: assignment to reference
Loris Caren a écrit : > If > > a = 'apple' > b = 'banana' > c = 'cabbage' > > How can I get something like:- > > for i in 'abc': > r = eval(i) > if r == 'cabbage': r = 'coconut' > > actually change the object referenced by r rather > than creating a new object temporarily referenced by it? > > I've tried playing with eval and exec without the desired > effect. for obj in (a, b, c): if obj == 'cabbage': obj = 'coconut' -- http://mail.python.org/mailman/listinfo/python-list
Re: How to replace all None values with the string "Null" in a dictionary
dcrespo a écrit : >>I think it would be time for you to read the Fine Manual... > > > hi, thanks for your answer... I really did it the same way you > suggested, but I forgot to tell you that I wanted to get a better way > for doing it. Let us know if you find one... > > By the way, knowing your wisdom, > what do I have to install to get the > following code work (Win XP, Python 2.4.2) Being wise, I don't use Windows !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: expanding dictionary to function arguments
Noah a écrit : > I have a dictionary that I would like to expand to satisfy a > function's agument list. I can used the ** syntax to pass a dictionary, > but > this only works if each key in the dictionary matches an argument. > I cannot pass a dictionary that has more keys than the function has > arguments. If you have control over the API functions declarations, makes them so: def my_api_func(arg1='', arg2='whatever', **kwargs): code_here -- http://mail.python.org/mailman/listinfo/python-list
Re: when and how do you use Self?
Jeffrey Schwab a écrit : > bruno at modulix wrote: > >> Steven D'Aprano wrote: >> >>> On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote: >>> >>>> Tieche Bruce A MSgt USMTM/AFD wrote: >>>> >>>>> I am new to python, >>>>> >>>>> Could someone explain (in English) how and when to use self? >>>> >>>> Don't use self. Use other. >>> >>> Are you serious? >> >> Are you seriously wondering if I am serious ? > > I was also wondering. You shouldn't. > What's the problem you see with the identifier > "self?" It's just to sale fish... -- http://mail.python.org/mailman/listinfo/python-list
Re: when and how do you use Self?
Steven D'Aprano a écrit : > On Thu, 03 Nov 2005 20:19:03 +0100, bruno at modulix wrote: > > >>Steven D'Aprano wrote: >> >>>On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote: >>> >>> >>> >>>>Tieche Bruce A MSgt USMTM/AFD wrote: >>>> >>>> >>>>>I am new to python, >>>>> >>>>> >>>>> >>>>>Could someone explain (in English) how and when to use self? >>>>> >>>> >>>>Don't use self. Use other. >>> >>> >>>Are you serious? >> >>Are you seriously wondering if I am serious ? > > > Well, you are either serious, or you're guilty of giving extremely bad > advice to a newbie who will probably have even less ability to recognise > an in-joke than I do. > Guilty. I thought the pun would be obvious (even if very bad). -- http://mail.python.org/mailman/listinfo/python-list
Re: when and how do you use Self?
Tieche Bruce A MSgt USMTM/AFD a écrit : > Well, thanx for all the ... useful information. > > I thought that I would try, but this has turned out to be a waist of my time. > > Have fun playing with your egos s/your egos/words/ If you can't stand a joke (possibly very bad, but that's another point), I'd say the ego problem is on your side. In case you didn't notice, this joke was not directed to you personally. BTW, this is (usually) a very newbie-friendly newsgroup (at least when I resist the temptation to reply with stupid puns). Instead of RTFMs, you've got helpful answers by peoples like Fredrik Lundh and Alex Martelli. -- http://mail.python.org/mailman/listinfo/python-list
Re: Diff. between Class types and classic classes
Colin J. Williams a écrit : > bruno at modulix wrote: > >> venk wrote: >> >>> Hi, >>> can some one properly explain the differences between class types and >>> classic classes? ... Still face problems in identifying what is what. >> >> >> >> I'm not sure I understand your question. Are you talking about the diff >> between old-style and new-style classes, or the diff between classes and >> metaclasses ? >> > "new" classes inherit from object. Classic classes do not. (snip) > > I hope that this helps. Colin, I don't personaly need much help with this !-) In fact, your answer is almost the same as the one I was going to post - before I re-read the OP's question. And I'm still not sure that what the OP is looking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: derived / base class name conflicts
[EMAIL PROTECTED] a écrit : > Your suggestion ('_name' -> implementation, 'name' -> API) This is not "my" convention, it's *the* (mostly agreed upon) Python convention. Like 'self', or CONSTANT, or a whole lot of things in Python. > makes sense > as a convention between programmers that know a fair amount about each > other's classes before using them. No need to know much. dir(modulename.ClassName) is enough. > I don't think it is reasonable in general to only subclass from base > classes you have studied the full API of, however. Depends on your definition of "studying the full API" !-) Now if your fear is to accidentally override something in the base class, it's just a matter of: print "API:" print [name for name in dir(modulename.ClassName) \ if not name.startswith('_')] print "IMPLEMENTATION:" print [name for name in dir(modulename.ClassName) \ if not name.startswith('_')] > The double > underscore is a decent solution to my problem. Possibly. It can also become a PITA. But it's you who know what your code need !-) > I imagine it must be used a lot in domains where people are making > heavy use of third party python code. I almost never used it (perhaps half-a-dozen times, and only in frameworks abstract base classes), and rarely saw it in 3rd part source code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multikey Dict?
David Rasmussen a écrit : > If I have a collection of dicts like: > > john = {'id': 1, 'name': "John Cleese", 'year': 1939} > graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} > > I could store all of them in a list. But for easy lookup, I might store > all these in a dict instead, like > > people = {'1': john, '2': graham} > or maybe > > people = {'John Cleese': john, 'Graham Chapman': graham} You can use integers as keys in a dict. And building an index is not that difficult: peoples = [ {'id': 1, 'name': "John Cleese", 'year': 1939}, {id': 2, 'name': "Graham Chapman", 'year': 1941}, ] peoples_name_idx = dict((p['name'], p) for p in peoples) peoples_id_idx = dict((p['id'], p) for p in peoples) which generalize to: def mk_index(index_field, records): return dict((rec[index_field], rec) for rec in records) (snip) > would like to be able to say: > people['1'].year > > in some case and in other cases I want to say > people['John Cleese'].year This should be: people['John Cleese']['year'] (If you want transform your dicts to objects so you use dotted notation, there are recipes for this in the Python Cookbook.) > If I could just say to Python: john and graham (and ...) are all a part > of a "superdict" and either their id or their name can be used as keys. > > Can I do that somehow? Writing a dict-like object is quite easy. Look for UserDict, or directly subclass Dict. Now, how could the "superdict" implementation decide which key to use ? Here, you have a numeric 'id' and a string 'name', so you could test on it in __getitem__, but what if you want to use 2 different string keys? Computers are usually very bad at guessing, that's why we are programming them. My 2 cents -- http://mail.python.org/mailman/listinfo/python-list
Re: Multikey Dict?
Sam Pointon a écrit : >>If I could just say to Python: john and graham (and ...) are all a part >>of a "superdict" and either their id or their name can be used as keys. > > >>Can I do that somehow? > > > Sure you can. There are two obvious ways to do this - enlist the aid of > a Superdict (or similar) class to take care of the details. A simple > implementation would be: > > class Superdict(object): > > def __init__(self, by_id, by_name): > self.by_id = by_id > self.by_name = by_name > > def __getitem__(self, value): > if value.isdigit(): > return self.by_id[value] > else: > return self.by_name[value] What if the OP now wants non numeric id fields ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Book
David Rasmussen a écrit : > What is the best book for Python newbies (seasoned programmer in other > languages)? I don't know if it's the "best", but a DiveIntoPython/PythonCookbook combo may be a good choice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Copyright [was Re: Python Obfuscation]
Erik Max Francis a écrit : > David T wrote: > >> Individuals, and perhaps groups of individuals are the creators of >> works. > > > When someone pays you to create a work, then they own the copyright, Depends on the country's laws and the exact agreement. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
The Eternal Squire a écrit : > Without copyright, how could one possibly earn a living writing a > novel? Without copyright, how could one possibly earn a living writing programs?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: creating package question
[EMAIL PROTECTED] a écrit : > I think I have an answer to my own question. In the > WindowsComponents/__init__.py file, I have the following, that feels > like a better answer for the problem. Is there a better answer than > this? > > import os, sys > sys.path.append(os.path.join(os.getcwd(), 'Common')) > Err... if the script is called from somewhere else, this won't work. replace os.getcwd() with os.path.dirname(os.path.realpath(__file__)) Or better, use a .pth or add the needed path in your PYTHONPATH -- http://mail.python.org/mailman/listinfo/python-list
Re: Zope vs Php
Steve a écrit : > We are building a web app and the our backend is currently using python > with php front end. We would like to do everything in python but php > for our front end is so easy to use. We would like to use zope on our > front end(no experience with it) can anyone provide any experience with > this? > >>From what I can tell you can't just do > <% > #python code > %> > some title Yuck. > this is what we would like to do with session support and things that > php provides? > I don't think Zope is the right solution for you. It's a world in itself... If you're looking for a PHP-like solution, the closer is probably mod_python + [Cheetah or PSP]. My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: about try and exception
Shi Mu a écrit : > On 11/17/05, Carl J. Van Arsdall <[EMAIL PROTECTED]> wrote: > (Carl's top-post corrrected. Carl, please do not top-post) >> >> >>Ben Bush wrote: >> >>>I wrote the following code to test the use of "try...exception", >>>and I want n to be printed out. However, the following code's output is: >>>Traceback (most recent call last): >>> File >>>"C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", >>>line 310, in RunScript >>>exec codeObject in __main__.__dict__ >>> File "C:\py\use\tryExVa.py", line 7, in ? >>>print n >>>NameError: name 'n' is not defined >>> >>>the code is here: >>> >>>try: >>>m=2/0 >>>n=1/2 >>>except ZeroDivisionError: >>>pass >>>print "Yes!!! This line will always print" >>>print n >>I would think that when the exception occurs the interpreter exits the >>block of code it is currently in and enters the exception block. >> >>Thus the line n = 1/2 would never get executed. > > It is true. Indeed... > If I want to run the statement after the division error > such as n=1/2, what should I do? Depends on what you mean by "after". But I think this is what you want: try: m = 2 / 0 except ZeroDivisionError: m = 0 # or whatever default value n = 1/2 -- http://mail.python.org/mailman/listinfo/python-list
Re: examining python objects
[EMAIL PROTECTED] a écrit : > Is there a function/class/module/whatever I can use to > look at objects? I want something that will print the object's > value (if any) in pretty-printed form, and list all it's attributes > and their values. And do all that recursively. > I want to be able to find out everything about an object that > Python can introspectively find out. Then check the inspect module -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused about namespaces
KvS a écrit : > Ok, makes sense but didn't seem "natural" to me, It will seem more natural if you understand that modules should be modulars (ie: low coupling, high cohesion). A module should *never* bother about no rely upon other modules being imported by the module it imports itself. Err, not quite clear... Let's rephrase it : a module should only used symbols it defines itself or that it *explicitely* imports from other modules. > although it is an > obvious consequence of what you just pointed out, namely that modules > are evaluated in their own namespace, something to keep in mind... On > the other hand it does apparently work recursively "the other way > around" since I didn't explicitly import wx in main.py but only > indirect via importing GUIclasses in which wx is imported right? You've already got technical answers to this - please carefully (re)read Alex Martelli's post. Now about coding style: this is *very* Bad Style(tm). Your main module imports should look like this: import wx # import settings -> we don't use the settings module here from GUIclasses import KFrame (...) and the GUIclasses module's import : import wx import wx.lib.mixins.listctrl as listmix import settings -> *here* we use the settings module (...) Python's philosophy is to favour readability. Talking about imports, take time to open your Python interactive shell and type "import this" !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python weak on the web side?
Tony a écrit : > If I'd like to learn Python for web-development, what are the options > available? There are too many *good* options for web developpement in Python. > Thanks. tony -- http://mail.python.org/mailman/listinfo/python-list
Re: ownership problem?
Gabriel Zachmann a écrit : > Is it correct to say that the typical ownership problem, which > frequently arises in C++, does not occur normally in Python? What is this "typical ownership problem" ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Raymond Hettinger a écrit : > Gustav Hållberg wrote: > >>I tried finding a discussion around adding the possibility to have >>optional underscores inside numbers in Python. This is a popular option >>available in several "competing" scripting langauges, that I would love >>to see in Python. >> >>Examples: >> 1_234_567 >> 0xdead_beef >> 3.141_592 > > > I suppose it could be done. OTOH, one could argue that most production > code has no business hardwiring-in numerical constants greater than 999 > ;-) > That's what I thought at first, but Steven D'Aprano made some good points here IMHO, ie : """ Not all numeric constants used have simple formulae, or *any* formulae, or can be calculated on the fly in any reasonable time. Numeric programming often uses magic constants which truly are "magic" (in the sense that where they come from requires deep, difficult, and sometimes hidden knowledge). Nobody sensible wants to be typing in long strings of digits, but sometimes it is unavoidable. """ and """ Another sensible usage case is in the interactive interpreter. If you are using Python interactively, you may wish to use numeric literals with large numbers of digits. It is not feasible to read them from a data file, and using a special converter function is impractical and unnecessary. """ So even if it's far from a common use case for *most* Python users, it may be a common use case for *some* Python users. Also, someone mentionned the use of Python as a configuration langage - which is probably a much more common use case. So FWIW, I'd be +1 on adding it *if and only if*: - it's trivial to implement [1] - it doesn't break older code and +1 on the space as group delimiter BTW. [1]: I never wrote a language by myself, but I've played a bit with parsers and lexers, and I _guess_ (which implies I may be wrong !-) it wouldn't require much work to add support for a "literal numeric grouping" syntax in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Request opinion on web application framework
Thomas a écrit : > Hello, > > I am new to web programming but have some experience in technical > programming in Python and other languages. I need to build a networked > program which I would like to first deploy on an intranet and later on the > web which provides access to a few technical applications, two document > management systems (simple types), a database search tool and maybe in the > future a groupware client. All data will be stored in a database. I want a > common portal for all of these functions. > > Can anyone recommend a web framework for such an application? I have looked > a little and most seem to focus on CMS type applications instead of > technical programs. Django or Turbogears would be perfect candidates IMHO. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
[EMAIL PROTECTED] a écrit : > > I'm off to study the code. (Hmm.. how does python parse ("green", > "red")[(i * 8 + j) % 2] command ... ("green", "red")[0] == "green" ("green", "red")[1] == "red" (i * 8 + j) is somewhat trivial (just take care of precedence order), and will return an integer % is the modulo operator. the modulo 2 of any integer x is 0 if x is even and 1 if x is odd (that's in fact the reversed definition !-) So this expression[1] will return "green" if (i * 8 + j) is pair and "red" if (i * 8 + j) is even. Using computed indexed access for dispatch is a common python idiom. Instead of: if condition: result = iftrue else: result = iffalse you can simply write: result = (iffalse, iftrue)[condition] [1] 'expression', not 'command'. An expression has a value and can be used on the right hand side of the assignment operator. > he says while reaching for "python > for the semi-illiterate" ...) > -- http://mail.python.org/mailman/listinfo/python-list
Re: Working with flat files [LDIF].
[EMAIL PROTECTED] a écrit : Scott A. McIntyre wrote: I looked around but didn't see any LDIF tools for perl or python... Any assistance or advice is appreciated!! Scott Hello Scott, Did you ever get this issue resolved? I have a similar need to merge two LDIF files. I did find a program called mmldif, but I believe it is proprietary to Sun. The ldap module has some tools related to ldif files, but there is not much documentation and I never had to use it, so I can't say if this can help... -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting rid of "self."
BJörn Lindqvist a écrit : I think it would be cool if you could refer to instance variables without prefixing with "self." I know noone else thinks like me so Python will never be changed, but maybe you can already do it with Python today? (snip code) It works! exec(magic()) does the needed hi = self.hi. Not so impressive in this case but much cooler when there is more instance variables around. But the solution is very ugly because you have to write exec(magic()) in every method. So I'm asking here if someone knows a better way, maybe using decorators or metaclasses or other black magic? The better way is definitively to forget about black magic and understand why mandatory 'self' is Good Thing (tm). (Tip : even when [this|self|@|whatsoever] is not mandatory, using it makes for much more readable code.) Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples vs lists
worzel a écrit : I get what the difference is between a tuple and a list, but why would I ever care about the tuple's immuutability? Because, from a purely pratical POV, only an immutable object can be used as kay in a dict. So you can use tuples for 'composed key'. Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples vs lists
Antoon Pardon a écrit : Op 2005-01-08, Bruno Desthuilliers schreef <[EMAIL PROTECTED]>: worzel a écrit : I get what the difference is between a tuple and a list, but why would I ever care about the tuple's immuutability? Because, from a purely pratical POV, only an immutable object can be used as kay in a dict. s/kay/key/ This is not true. Chapter and verse, please ? So you can use tuples for 'composed key'. lists can be so used too. Just provide a hash. Please show us an example, and let's see how useful and handy this is from a "purely practical POV" ?-) Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: Pointer or unique id
Nomak a écrit : Hello, does python have an equivalent to Java: int Object.hashCode() ? id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) hash(obj) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. HTH Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: CONTEST - What is the (best) solution?
[EMAIL PROTECTED] a écrit : In a file there can be several dictionaries like this (snip) I need to read only the the first and the last dictionaries.What is a best solution? Depends on your definition of 'best solution'. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Daniel Bickett a écrit : This is certainly a worthy topic. There are several IDEs for Python (one I like very much being Komodo) that have plenty of fancy debugging features and advanced operations, however I have yet to encounter (elsewhere) the convenience that comes with being able to press F5 and have an interactive interpreter load my code and be ready for testing. Try emacs + python-mode. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Pierre Barbier de Reuille a écrit : Fuzzyman a écrit : If you use IPython for your interactive mode stuff, you'll have a nice history... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml Best event : if your "EDITOR" system variable in "vim", using the "ed" command in ipython will bring "vim" with (eventually) the code you want to edit :) Now, I wonder if you could embed ipython inside vim ... Don't know, but you can embed ipython inside emacs !-) Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: sos!
jordan2856977 a écrit : hellow everybody! I'm from china. I'm a beginner of python. in china, python is not a fashionable language, so it's difficult to find some books about python. finally,I find a book named "python how to program" wrote by H.M.Deitel . who can tell me where can I find some interesting source code about python. otherwise, I will fell boring about study! Well, if you want to study some interesting source code, you have the whole Python standard lib, and *many* open source programs (Zope, Twisted, etc...) You can also find some good free books online, like Dive Into Python, or Text Processing With Python. (google should find relevant URLs). HTH, and welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: who can tell me BASICS of Python
[EMAIL PROTECTED] a écrit : I want to know which compiler I can use ... thank you To compile what ? Python code ? The compiler is in the standard lib. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error!
Steve Holden a écrit : (snip) So, for example, your program might look like this: base_price = int(raw_input(...)) tax_rate = int(raw_input(...) tax_amount = base_price * ((100+tax_amount)/...) s/(100+tax_amount)/(100 + tax_rate)/, I guess ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt)
Daniel Bickett a écrit : I was reading the "Pickling and inheritance are making me hurt" thread, and the latest suggestion (as of this posting) was to do with the __setstate__ and __getstate__ methods. They caught my attention because I hadn't encountered them before, and it reminded me that in the past I've never been able to very good, definitive documentation on newstyle classes. Well, the fact is that __[get|set]state__() have nothing to do with new style classes, but with the Pickle protocol: http://www.python.org/doc/2.3.4/lib/pickle-inst.html (snip) Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question
[EMAIL PROTECTED] wrote: > Hi Matt, > I also am almost a newbie (in Python) and my approach to variable > naming > follows more or less the Hungarian Type Notation Defined. which is seen as a bad practice anywhere outside Win32... http://mindprod.com/jgloss/unmainnaming.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: delphi to python converter
Thys Meintjes wrote: > Greets, > > I have need of a Delphi/pascal to python converter. Googling didn't > suggest any obvious leads so I'm trying here... Have you tried with "python/delphi programer" ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Help Figger Out My Problem
[EMAIL PROTECTED] wrote: > ##Coin Flip: randomly flips 100 "coins" and prints results > ##Original draft: june 27, 2005 > ##Chuck > > import random > heads = 0 > tails = 0 > flips = 0 > while flips < 99: > coin = random.randrange(0, 2) > if coin == 0: > heads = heads + 1 heads += 1 > else: > tails = tails + 1 idem > flips = flips + 1 idem > if flips >= 99: Why do you think you need this test ?-) > print "Heads: " + heads print "Heads: %d" % heads > print "Tails: " + tails idem > print "Total: " + flips + "flips" idem > raw_input("Press the enter key to exit.") May I suggest this version ? from random import randrange def flip_coins(flips): coins = [0, 0] for i in xrange(flips): coins[randrange(0, 2)] += 1 return coins[0], coins[1] if __name__ == "__main__": flips = 100 heads, tails = flip_coins(flips) print "Heads: %d\nTails %d\nTotal: %d flips\n" % (heads, tails, flips) #raw_input("Press the enter key to exit.") HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary to tuple
Odd-R. wrote: > I have a dictionary, and I want to convert it to a tuple, > that is, I want each key - value pair in the dictionary > to be a tuple in a tuple. > > If this is the dictionary {1:'one',2:'two',3:'three'}, > then I want this to be the resulting tuple: > ((1,'one'),(2,'two'),(3,'three')). > > I have been trying for quite some time now, but I do not > get the result as I want it. Can this be done, or is it not > possible? It's of course possible, and even a no-brainer: dic = {1:'one',2:'two',3:'three'} tup = tuple(dic.items()) The bad news is that dict are *not* ordered, so you'll have to sort the result yourself if needed :( The good news is that sorting a sequence is a no-brainer too !-) > I must also add that I'm new to Python. Welcome on board. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules for inclusion in standard library?
George Sakkis wrote: > I'd love to see IPython replace the standard interpreter. I dont. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary to tuple
Tim Williams (gmail) wrote: (snip) >>>>d = {1:'one',2:'two',3:'three'} >>>>t = tuple([(k,v) for k,v in d.iteritems()]) Err... don't you spot any useless code here ?-) (tip: dict.items() already returns a list of (k,v) tuples...) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list