Re: Puzzled
On 11/06/2015 02:36 PM, Robinson, Wendy wrote: > Ah, ok I get it now. > Thanks both! Glad you got it! Thanks for letting us know, too. -- https://mail.python.org/mailman/listinfo/python-list
RE: Puzzled
Ah, ok I get it now. Thanks both! Wendy Robinson Audit Analyst -Original Message- From: Chris Gonnerman [mailto:ch...@gonnerman.org] Sent: Friday, November 06, 2015 5:40 AM To: python-list@python.org Cc: Robinson, Wendy Subject: Re: Puzzled Wendy said: > I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic > programs successfully. > This morning I rebooted my computer and can't get a single one to work. The > interpreter seems to be fine and the environment variables look correct. But > every py file I try to run at the >>> prompt gives me a NameError. But that's not how the Python interpreter works. You say you are trying to run "py files" at the >>> prompt. If what you are doing is this: >>> test.py Well, no, that's not going to work. If you want to run "test.py" as a script, from the CMD prompt you type: python test.py If test.py is a module meant to be imported, then from the Python prompt you do this: import test Hope this helps. -- Chris. -- https://mail.python.org/mailman/listinfo/python-list
RE: Puzzled
Well... I still can't get this to work. I guess I'll just uninstall it. It's a bummer that there's no help on basic startup like this. Wendy Robinson Audit Analyst (916) 566-4994 phone NOTICE OF CONFIDENTIALITY: This email is for the sole use of the intended recipient and may contain material that is confidential and protected by state and federal regulations. If you are not the intended recipient please immediately delete it and contact the sender. -Original Message- From: Laura Creighton [mailto:l...@openend.se] Sent: Sunday, November 01, 2015 2:21 AM To: Robinson, Wendy Cc: 'python-list@python.org'; l...@openend.se Subject: Re: Puzzled In a message of Fri, 30 Oct 2015 09:20:23 -0700, "Robinson, Wendy" writes: >Hi there, >I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic >programs successfully. >This morning I rebooted my computer and can't get a single one to work. The >interpreter seems to be fine and the environment variables look correct. But >every py file I try to run at the >>> prompt gives me a NameError. > >I tried running the Repair installation, but that did not help. > >Any suggestions? > >Thank you > >Wendy Robinson >Audit Analyst >(916) 566-4994 phone Paste in the Full traceback you get from the console. Also check and see that the console is actually running the 3.5 you installed, and not some other python, like 2.7 you might have lying around. Laura -- https://mail.python.org/mailman/listinfo/python-list
RE: Puzzled
Hmmm... fair enough. I sent the traceback though, on Monday. I'll give the intro a read again. I've probably missed something basic. Wendy Robinson Audit Analyst (916) 566-4994 phone NOTICE OF CONFIDENTIALITY: This email is for the sole use of the intended recipient and may contain material that is confidential and protected by state and federal regulations. If you are not the intended recipient please immediately delete it and contact the sender. -Original Message- From: Laura Creighton [mailto:l...@openend.se] Sent: Thursday, November 05, 2015 3:11 PM To: Robinson, Wendy Cc: 'Laura Creighton'; 'python-list@python.org'; l...@openend.se Subject: Re: Puzzled In a message of Thu, 05 Nov 2015 12:48:11 -0800, "Robinson, Wendy" writes: >Well... I still can't get this to work. I guess I'll just uninstall it. >It's a bummer that there's no help on basic startup like this. > >Wendy Robinson >Audit Analyst >(916) 566-4994 phone There is enormous amount of help available. But we need to know more about what your problem is, and how it presents itself before we can start tracking down what your problem is, which is why I wanted a traceback. >>Hi there, >>I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic >>programs successfully. >>This morning I rebooted my computer and can't get a single one to work. The >>interpreter seems to be fine and the environment variables look correct. But >>every py file I try to run at the >>> prompt gives me a NameError. See, this is where your problem is. There is a conceptual problem in understanding what you meant by 'tried some basic programs successfully' versus 'running py files at the >>> prompt'. Either you didn't use the Python console -- the thing that is showing you the '>>>' yesterday, and thus the programs that were working yesterday are now working every bit as well as they did then, and your problem is that you do not know how to use the python console. Or you did use the console before, and they worked there, and now you have NameErrors. I think the problem is the first sort. I think that you opened up the python console and then typed in something like 'myprogram.py' expecting the console to run the myprogram. Instead you got something like this: Python 3.5.0rc1 (default, Aug 12 2015, 14:57:46) [GCC 5.2.1 20150808] on linux Type "help", "copyright", "credits" or "license" for more information. >>> myprogram.py Traceback (most recent call last): File "", line 1, in NameError: name 'myprogram' is not defined >>> If this is what happened then your python is fine. You just do not know how the interactive console works. It doesn't run files like this. See:https://docs.python.org/3.5/tutorial/introduction.html You type code at the console and get responses back. If, on the other hand, this is not your problem, then we need a traceback --- and what I posted above was a traceback -- so that we can see what caused the NameError. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
Wendy said: I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic programs successfully. This morning I rebooted my computer and can't get a single one to work. The interpreter seems to be fine and the environment variables look correct. But every py file I try to run at the >>> prompt gives me a NameError. But that's not how the Python interpreter works. You say you are trying to run "py files" at the >>> prompt. If what you are doing is this: >>> test.py Well, no, that's not going to work. If you want to run "test.py" as a script, from the CMD prompt you type: python test.py If test.py is a module meant to be imported, then from the Python prompt you do this: import test Hope this helps. -- Chris. -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
On Thursday 05 November 2015 19:04:35 Robinson, Wendy wrote: > Hmmm... fair enough. I sent the traceback though, on Monday. If you sent a traceback on Monday, it wasn't seen by this list. Do not 'attach' it to the message, but include it as the list server might have stripped an attachment. > I'll give the intro a read again. I've probably missed something > basic. > > Wendy Robinson > Audit Analyst > (916) 566-4994 phone > > > > NOTICE OF CONFIDENTIALITY: This email is for the sole use of the > intended recipient and may contain material that is confidential and > protected by state and federal regulations. If you are not the > intended recipient please immediately delete it and contact the > sender. This is a public list Wendy, so this has no meaning. There are those, who on seeing such a message, will not reply even if they could help. > -Original Message- > From: Laura Creighton [mailto:l...@openend.se] > Sent: Thursday, November 05, 2015 3:11 PM > To: Robinson, Wendy > Cc: 'Laura Creighton'; 'python-list@python.org'; l...@openend.se > Subject: Re: Puzzled > > In a message of Thu, 05 Nov 2015 12:48:11 -0800, "Robinson, Wendy" writes: > >Well... I still can't get this to work. I guess I'll just uninstall > > it. It's a bummer that there's no help on basic startup like this. > > > >Wendy Robinson > >Audit Analyst > >(916) 566-4994 phone > > There is enormous amount of help available. But we need to know more > about what your problem is, and how it presents itself before we can > start tracking down what your problem is, which is why I wanted a > traceback. > > >>Hi there, > >>I installed Python 3.5.0 64-bit for Windows yesterday and tried some > >> basic programs successfully. This morning I rebooted my computer > >> and can't get a single one to work. The interpreter seems to be > >> fine and the environment variables look correct. But every py file > >> I try to run at the >>> prompt gives me a NameError. > > See, this is where your problem is. There is a conceptual problem in > understanding what you meant by 'tried some basic programs > successfully' versus 'running py files at the >>> prompt'. > > Either you didn't use the Python console -- the thing that is showing > you the '>>>' yesterday, and thus the programs that were working > yesterday are now working every bit as well as they did then, and your > problem is that you do not know how to use the python console. > > Or you did use the console before, and they worked there, and now you > have NameErrors. > > I think the problem is the first sort. > I think that you opened up the python console and then typed in > something like 'myprogram.py' expecting the console to run the > myprogram. Instead you got something like this: > > Python 3.5.0rc1 (default, Aug 12 2015, 14:57:46) [GCC 5.2.1 20150808] > on linux Type "help", "copyright", "credits" or "license" for more > information. > > >>> myprogram.py > > Traceback (most recent call last): > File "", line 1, in > NameError: name 'myprogram' is not defined >>> > > If this is what happened then your python is fine. You just do not > know how the interactive console works. It doesn't run files like > this. > > See:https://docs.python.org/3.5/tutorial/introduction.html > > You type code at the console and get responses back. > > If, on the other hand, this is not your problem, then we need a > traceback --- and what I posted above was a traceback -- so that we > can see what caused the NameError. > > Laura Cheers, Gene Heskett -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author) Genes Web page <http://geneslinuxbox.net:6309/gene> -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
In a message of Thu, 05 Nov 2015 12:48:11 -0800, "Robinson, Wendy" writes: >Well... I still can't get this to work. I guess I'll just uninstall it. >It's a bummer that there's no help on basic startup like this. > >Wendy Robinson >Audit Analyst >(916) 566-4994 phone There is enormous amount of help available. But we need to know more about what your problem is, and how it presents itself before we can start tracking down what your problem is, which is why I wanted a traceback. >>Hi there, >>I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic >>programs successfully. >>This morning I rebooted my computer and can't get a single one to work. The >>interpreter seems to be fine and the environment variables look correct. But >>every py file I try to run at the >>> prompt gives me a NameError. See, this is where your problem is. There is a conceptual problem in understanding what you meant by 'tried some basic programs successfully' versus 'running py files at the >>> prompt'. Either you didn't use the Python console -- the thing that is showing you the '>>>' yesterday, and thus the programs that were working yesterday are now working every bit as well as they did then, and your problem is that you do not know how to use the python console. Or you did use the console before, and they worked there, and now you have NameErrors. I think the problem is the first sort. I think that you opened up the python console and then typed in something like 'myprogram.py' expecting the console to run the myprogram. Instead you got something like this: Python 3.5.0rc1 (default, Aug 12 2015, 14:57:46) [GCC 5.2.1 20150808] on linux Type "help", "copyright", "credits" or "license" for more information. >>> myprogram.py Traceback (most recent call last): File "", line 1, in NameError: name 'myprogram' is not defined >>> If this is what happened then your python is fine. You just do not know how the interactive console works. It doesn't run files like this. See:https://docs.python.org/3.5/tutorial/introduction.html You type code at the console and get responses back. If, on the other hand, this is not your problem, then we need a traceback --- and what I posted above was a traceback -- so that we can see what caused the NameError. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
On 11/05/2015 04:10 PM, Laura Creighton wrote: > In a message of Thu, 05 Nov 2015 12:48:11 -0800, "Robinson, Wendy" writes: >> Well... I still can't get this to work. I guess I'll just uninstall it. >> It's a bummer that there's no help on basic startup like this. >> >> Wendy Robinson >> Audit Analyst >> (916) 566-4994 phone > > There is enormous amount of help available. But we need to know more > about what your problem is, and how it presents itself before we can > start tracking down what your problem is, which is why I wanted a > traceback. Indeed there was quite a lot of help given to her on this list but she didn't reply to any of those suggestions. Pretty discouraging to those who want to help out. -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
> On 03 Nov 2015, at 05:46, Michael Torriewrote: > Sometimes on Windows you can double-click a python file and it will run. The first thing I do on Windows after installing Python: edit the registry so that the 'open' key is changed to 'run', and 'edit with IDLE' becomes 'open'. I like to see my scripts in IDLE before I run them ;-) Greetings, -- https://mail.python.org/mailman/listinfo/python-list
RE: Puzzled
[cid:image001.png@01D11543.5ED11D50] Wendy Robinson Audit Analyst (916) 566-4994 phone NOTICE OF CONFIDENTIALITY: This email is for the sole use of the intended recipient and may contain material that is confidential and protected by state and federal regulations. If you are not the intended recipient please immediately delete it and contact the sender. -Original Message- From: Laura Creighton [mailto:l...@openend.se] Sent: Sunday, November 01, 2015 2:21 AM To: Robinson, Wendy Cc: 'python-list@python.org'; l...@openend.se Subject: Re: Puzzled In a message of Fri, 30 Oct 2015 09:20:23 -0700, "Robinson, Wendy" writes: >Hi there, >I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic >programs successfully. >This morning I rebooted my computer and can't get a single one to work. The >interpreter seems to be fine and the environment variables look correct. But >every py file I try to run at the >>> prompt gives me a NameError. > >I tried running the Repair installation, but that did not help. > >Any suggestions? > >Thank you > >Wendy Robinson >Audit Analyst >(916) 566-4994 phone Paste in the Full traceback you get from the console. Also check and see that the console is actually running the 3.5 you installed, and not some other python, like 2.7 you might have lying around. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
On 11/02/2015 08:52 AM, Robinson, Wendy wrote: > [cid:image001.png@01D11543.5ED11D50] Just FYI this mailing list group is tied with with a system called USENET which is plain text only, so most of us can't see your attachment. This may help you copy the text to your messages in plain text form: http://www.howtogeek.com/howto/windows-vista/copy-to-the-clipboard-from-the-windows-command-prompt/ Did you read what Peter Otten said in reply to your original message and did that not work? Sometimes on Windows you can double-click a python file and it will run. However many python programs don't display graphical elements so you'll just see a black console window flash and disappear. That's why it's probably important while learning Python to become comfortable with the command prompt. Alternatively use the IDLE program that comes with Python to edit and run your programs in a graphical environment. I think if you are on Windows and are unfamiliar with the command prompt I would recommend this course of action. Should be in the Start menu. -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
In a message of Fri, 30 Oct 2015 09:20:23 -0700, "Robinson, Wendy" writes: >Hi there, >I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic >programs successfully. >This morning I rebooted my computer and can't get a single one to work. The >interpreter seems to be fine and the environment variables look correct. But >every py file I try to run at the >>> prompt gives me a NameError. > >I tried running the Repair installation, but that did not help. > >Any suggestions? > >Thank you > >Wendy Robinson >Audit Analyst >(916) 566-4994 phone Paste in the Full traceback you get from the console. Also check and see that the console is actually running the 3.5 you installed, and not some other python, like 2.7 you might have lying around. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
Am 30.10.2015 um 17:20 schrieb Robinson, Wendy: Hi there, I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic programs successfully. This morning I rebooted my computer and can’t get a single one to work. The interpreter seems to be fine and the environment variables look correct. But every py file I try to run at the >>> prompt gives me a NameError. Did you try the exact same things yesterday and this morning? The >>> prompt isn't made for running py files, but for directly entering statements and executing them. Running py files from a windows command prompt (probably after changing into the right directory) should work. Importing py files at the >>> prompt and using their content should work (again, if Python can find them). So, what exactly did you do yesterday and what exactly did you do today? HTH Sibylle -- https://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
Robinson, Wendy wrote: > Hi there, > I installed Python 3.5.0 64-bit for Windows yesterday and tried some basic > programs successfully. > This morning I rebooted my computer and can't get a single one to work. > The interpreter seems to be fine and the environment variables look > correct. But every py file I try to run at the >>> prompt gives me a > NameError. > > I tried running the Repair installation, but that did not help. > > Any suggestions? If you want to run a python script you have to invoke it on the commandline, not inside the interactive interpreter, i. e. if you have a script myscript.py containing the line print("Hello world!") Wrong: C:\> python3 >>> myscript.py Traceback (most recent call last): File "", line 1, in NameError: name 'myscript' is not defined Here python looks for a variable "myscript" which of course isn't defined. (If it were the next step would be to look for an attribute "py" and you'd probably get an AttributeError) Right: C:\> python3 myscript.py Hello world! Here python runs the script and exits. If you have a function defined in a module that you want to use from the interactive interpreter you have to import the module. Assuming mymodule.py contains the function def say_hello(): print("Hello world!") C:\> python3 >>> import mymodule >>> mymodule.say_hello() Hello world! -- https://mail.python.org/mailman/listinfo/python-list
Re: puzzled by name binding in local function
Heureka! Am 06.02.2013 15:37, schrieb Dave Angel: def myfunc2(i): def myfunc2b(): print (myfunc2 is using, i) return myfunc2b Earlier you wrote: There is only one instance of i, so it's not clear what you expect. Since it's not an argument to test(), it has to be found in the closure to the function. In this case, that's the global namespace. So each time the function is called, it fetches that global. Actually, the important part missing in my understanding was the full meaning of closure and how it works in Python. After failing to understand how the pure Python version of functools.partial worked, I started a little search and found e.g. closures-in-python[1], which was a key element to understanding the whole picture. Summary: The reason the above or the pure Python version work is that they use the closure created by a function call to bind the values in. My version used a loop instead, but the loop body does not create a closure, so the effective closure is the surrounding global namespace. :) Uli [1] http://ynniv.com/blog/2007/08/closures-in-python.html -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled by name binding in local function
Dave and Terry, Thanks you both for your explanations! I really appreciate the time you took. Am 05.02.2013 19:07, schrieb Dave Angel: If you need to have separate function objects that already know a value for i, you need to somehow bind the value into the function object. One way to do it, as you say, is with default parameters. A function's default parameters are each stored in the object, because they're defined to be evaluated only once. That's sometimes considered a flaw, such as when they're volatile, and subsequent calls to the function use the same value. But in your case, it's a feature, as it provides a standard place to store values as known at function definition time. Yes, that was also the first way I found myself. The reason I consider this non-obvious is that it creates a function with two parameters (one with a default) while I only want one with a single parameter. This is to some extent a bioware problem and/or a matter of taste, both for me and for the other audience that I'm writing the code for. The other way to do it is with functions.partial(). I can't readily write you sample code, as I haven't messed with it in the case of class methods, but partial is generally a way to bind one or more values into the actual object. I also think it's clearer than the default parameter approach. Partial would be clearer, since it explicitly binds the parameters: import functools class Foo(object): def function(self, param): print('function({}, {})'.format(self, param)) Foo.test = functools.partial(Foo.function, param=1) f = Foo() Foo.test(f) # works f.test() # fails I guess that Python sees Foo.test and since it is not a (nonstatic) function, it doesn't create a bound method from this. Quoting the very last sentence in the documentation: Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up. The plain-Python version mentioned in the functools documentation does the job though, so I'll just use that with a fat comment. Also, after some digging, I found http://bugs.python.org/issue4331, which describes this issue. There is a comment from Jack Diederich from 2010-02-23 where he says that using lambda or a function achieves the same, but I think that this case shows that this is not the case. I'm also thinking about throwing another aspect in there: Unless you're using exec(), there is no way to put any variables as constants into the function, i.e. to enforce early binding instead of the default late binding. Using default parameters or functools.partial are both just workarounds with limited applicability. Also, binding the parameters now instead of later would reduce size and offer a speedup, so it could be a worthwhile optimization. The main place where I see this type of problem is in a gui, where you're defining a callback to be used by a series of widgets, but you have a value that IS different for each item in the series. You write a loop much like you did, and discover that the last loop value is the only one used. The two cures above work, and you can also use lambda creatively. Careful, lambda does not work, at least not easily! The problem is that lambda only creates a local, anonymous function, but any names used inside this function will only be evaluated when the function is called, so I'm back at step 1, just with even less obvious code. Greetings! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled by name binding in local function
On 02/06/2013 05:19 AM, Ulrich Eckhardt wrote: Dave and Terry, Thanks you both for your explanations! I really appreciate the time you took. Am 05.02.2013 19:07, schrieb Dave Angel: snip The main place where I see this type of problem is in a gui, where you're defining a callback to be used by a series of widgets, but you have a value that IS different for each item in the series. You write a loop much like you did, and discover that the last loop value is the only one used. The two cures above work, and you can also use lambda creatively. Careful, lambda does not work, at least not easily! The problem is that lambda only creates a local, anonymous function, but any names used inside this function will only be evaluated when the function is called, so I'm back at step 1, just with even less obvious code. Greetings! Uli I haven't been able to reconstruct it exactly, but here's the function equivalent: def myfunc2(i): def myfunc2b(): print (myfunc2 is using, i) return myfunc2b funcs = [] for i in range(5): funcs.append(myfunc2(i)) print Now doing the loop2 for func in funcs: func() -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled by name binding in local function
On 02/05/2013 10:18 AM, Ulrich Eckhardt wrote: Hello Pythonistas! Below you will find example code distilled from a set of unit tests, usable with Python 2 or 3. I'm using a loop over a list of parameters to generate tests with different permutations of parameters. Instead of calling util() with values 0-4 as I would expect, each call uses the same parameter 4. What I found out is that the name 'i' is resolved when Foo.test_1 is called and not substituted inside the for-loop, which finds the global 'i' left over from the loop. A simple del i after the loop proved this and gave me an according error. Now, I'm still not sure how to best solve this problem: * Spell out all permutations is a no-go. * Testing the different iterations inside a single test, is inconvenient because I want to know which permutation exactly fails and which others don't. Further, I want to be able to run just that one because the tests take time. * Further, I could generate local test() functions using the current value of 'i' as default for a parameter, which is then used in the call to self.util(), but that code is just as non-obviously-to-me correct as the current code is non-obviously-to-me wrong. I'd prefer something more stable. Any other suggestions? Thank you! Uli # example code from __future__ import print_function import unittest class Foo(unittest.TestCase): def util(self, param): print('util({}, {})'.format(self, param)) for i in range(5): def test(self): self.util(param=i) setattr(Foo, 'test_{}'.format(i), test) unittest.main() There is only one instance of i, so it's not clear what you expect. Since it's not an argument to test(), it has to be found in the closure to the function. In this case, that's the global namespace. So each time the function is called, it fetches that global. To put it another way, you're storing the same function object 5 times. If you need to have separate function objects that already know a value for i, you need to somehow bind the value into the function object. One way to do it, as you say, is with default parameters. A function's default parameters are each stored in the object, because they're defined to be evaluated only once. That's sometimes considered a flaw, such as when they're volatile, and subsequent calls to the function use the same value. But in your case, it's a feature, as it provides a standard place to store values as known at function definition time. The other way to do it is with functions.partial(). I can't readily write you sample code, as I haven't messed with it in the case of class methods, but partial is generally a way to bind one or more values into the actual object. I also think it's clearer than the default parameter approach. Notice that globals may be defined after a function that references them, which is a way of cross-checking the logic you already discovered. The names are only looked up when the function is actually called. This same logic applies to nested functions; the class definition is an unnecessary complication; of course I understand it's needed for unittest. The main place where I see this type of problem is in a gui, where you're defining a callback to be used by a series of widgets, but you have a value that IS different for each item in the series. You write a loop much like you did, and discover that the last loop value is the only one used. The two cures above work, and you can also use lambda creatively. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled by name binding in local function
Code examples are Python 3 On 2/5/2013 10:18 AM, Ulrich Eckhardt wrote: Below you will find example code distilled from a set of unit tests, usable with Python 2 or 3. I'm using a loop over a list of parameters to generate tests with different permutations of parameters. Instead of calling util() with values 0-4 as I would expect, each call uses the same parameter 4. What I found out is that the name 'i' is resolved when Foo.test_1 is called Names* in Python code are resolved when the code is executed. Function bodies are executed when the function is called. Ergo, names in function bodies are resolved when the function is called. This is sometimes called late binding. * This may exclude keyword names. Late binding of global names within functions is why the following can work instead of raising NameError. def f(): print(x) x = 3 f() 3 Only the most recent binding of x, at the time of the call matters, as long as there is one. Does the following really surprise you? x = 0 def f(): print(x) x = 3 f() 3 What do you expect this to print? x = 1 def f1(): print(x) x = 2 def f2(): print(x) x = 3 f1(), f2() Rolling the repeated code into a loop does not magically change the behavior of def statements. for i in range(1, 3): exec('''\ x = {0} def f{0}(): print(x)'''.format(i)) x = 3 print((f1(), f2())) This gives *exactly* the same output. So does this: from textwrap import dedent for i in range(1, 3): exec(dedent(''' x = {0} def f{0}(): print(x) '''.format(i))) x = 3 print((f1(), f2())) Python does not do text substitution unless you explicit ask it too, as I did above. Late binding is also why functions (and methods, such as .__init__) can call functions (methods) whose definitions follow later in the code, so don't change that this change ;-). and not substituted inside the for-loop, Now, I'm still not sure how to best solve this problem: * Spell out all permutations is a no-go. * Testing the different iterations inside a single test, is inconvenient because I want to know which permutation exactly fails and A good test framework should give specifics as to the failure. The unittest assertxxx methods do this. In fact, emitting specific messages is one reason there are so many methods. The real 'problem' with multiple tests within a test function is that the first failure ends that group of tests. But this is only a problem during development when there *are* failures. And it is possible to write a test function to run all tests and collect multiple error messages before 'failing' the test. which others don't. Further, I want to be able to run just that one because the tests take time. Whether multiple tests are buried within one function or many, running just one of them will require some editing. * Further, I could generate local test() functions using the current value of 'i' as default for a parameter, which is then used in the call to self.util(), but that code is just as non-obviously-to-me correct as the current code is non-obviously-to-me wrong. LOL. You know the easiest and correct solution, but reject it because it is not 'obvious' - though it was obvious enough for you to see it. If one understands that function definition are executable statements and that their execution is not magically changed by putting them inside loops, the problem with your code should be obvious. It creates 5 *identical* functions objects. So it should not be surprising that they behave identically. I'd prefer something more stable. The fact that default arg expressions are evaluated when the function is defined is quite stable. Ain't gonna change. Any other suggestions? Revise your obvious meter ;-). # example code from __future__ import print_function import unittest class Foo(unittest.TestCase): def util(self, param): print('util({}, {})'.format(self, param)) for i in range(5): def test(self): self.util(param=i) Executing this n times produces n identical functions. The easy fix is def test(self, j = i): self.util(param = j) setattr(Foo, 'test_{}'.format(i), test) Another fix that should work: adapt my code above and use exec within a loop within the class statement itself (and delete setattr). for i in range(5): exec(dedent(''' def test_{0}(self): self.util(param={0}) '''.format(i))) unittest.main() -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by FiPy's use of ==
On 3/26/12 12:47 PM, André Roberge wrote: In FiPy (a finite volume PDE solver), equations are magically set up as eqX = TransientTerm() == ExplicitDiffusionTerm(coeff=D) and solved via eqX.solve(...) How can eqX be anything than True or False?... This must be via a redefinition of == but I can't see how that is done. I did look at many of the source files, thinking that it must be via a redefinition of __eq__ somewhere but with no luck. Any pointers would be appreciated. It's in the root base class Term: http://matforge.org/fipy/browser/trunk/fipy/terms/term.py#L374 -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by FiPy's use of ==
On Monday, 26 March 2012 09:16:07 UTC-3, Robert Kern wrote: On 3/26/12 12:47 PM, André Roberge wrote: In FiPy (a finite volume PDE solver), equations are magically set up as eqX = TransientTerm() == ExplicitDiffusionTerm(coeff=D) and solved via eqX.solve(...) How can eqX be anything than True or False?... This must be via a redefinition of == but I can't see how that is done. I did look at many of the source files, thinking that it must be via a redefinition of __eq__ somewhere but with no luck. Any pointers would be appreciated. It's in the root base class Term: http://matforge.org/fipy/browser/trunk/fipy/terms/term.py#L374 I thought I looked at terms.py ... but I must have missed that. Thanks! -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled about the output of my demo of a proof of The Euler Series
On Aug 10, 4:57 pm, Richard D. Moores rdmoo...@gmail.com wrote: I saw an interesting proof of the limit of The Euler Series on math.stackexchange.com at http://math.stackexchange.com/questions/8337/different-methods-to-com Scroll down to Hans Lundmark's post. I thought I'd try to see this pinching down on the limit of pi**2/6. See my attempt, and output for n = 150 at http://pastebin.com/pvznFWsT. What puzzles me is that upper_bound_partial_sum (lines 39 and 60) is always smaller than the limit. It should be greater than the limit, right? If not, no pinching between upper_bound_partial_sum and lower_bound_partial_sum. I've checked and double-checked the computation, but can't figure out what's wrong. Thanks, Dick Moores The math is correct. The proof only asserts that sum(1/k^2) is between the upper and lower partial sums. The upper and lower partial sums both converge to pi^2/6 from below and since the sum(1/k^2) is between the two partial sums, it must also converge to pi^2/6. Try calculating sum(1/k^2) for k in range(1, 2**n) and compare that with the upper and lower sums. I verified it with several values up to n=20. casevh -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
MRAB pyt...@mrabarnett.plus.com wrote: I'd just like to point out that it's a convention, not a rigid rule. Reminds me of the catch-phrase from the first Pirates of the Caribbean movie: It's more of a guideline than a rule. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On 27/05/2011 07:34, Tim Roberts wrote: MRABpyt...@mrabarnett.plus.com wrote: I'd just like to point out that it's a convention, not a rigid rule. Reminds me of the catch-phrase from the first Pirates of the Caribbean movie: It's more of a guideline than a rule. Much like the Zen of Python. -- http://mail.python.org/mailman/listinfo/python-list
RE: Puzzled by list-appending behavior
I have to say, I do like Python's lack of keywords for these things I thought True/False were among the list of keywords in Python 3.x ? Or are those the only keywords? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
Prasad, Ramit wrote: I have to say, I do like Python's lack of keywords for these things I thought True/False were among the list of keywords in Python 3.x ? Or are those the only keywords? http://docs.python.org/py3k/reference/lexical_analysis.html#keywords False class finallyis return None continue forlambda try True deffrom nonlocal while anddelglobal notwith as elif if or yield assert else import pass break except in raise ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Thursday 26 May 2011 14:46:45 Uncle Ben wrote: In playing with lists of lists, I found the following: (In 3.1, but the same happens also in 2.7) list = [1,2,3] list.append ( [4,5,6] ) x = list x - [1,2,3,[4,5,6]] as expected. But the shortcut fails: list=[1,2,3] x = list.append( [4,5,6] ) x - nothing Can someone explain this to me? Uncle Ben And why do you insist on calling and instance of list, list? Even a human reader will confuse which is which. What you are showing is an example how confusing things become when a keyword (list) is over-written (with list instance). Why don't you just say lst = [1, 2, 3] rather than list =... It may be permissible, but it is not a good idea! Old (practical) Al. -- Algis http://akabaila.pcug.org.au/StructuralAnalysis.pdf -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Thu, May 26, 2011 at 2:46 PM, Uncle Ben bgr...@nycap.rr.com wrote: In playing with lists of lists, I found the following: (In 3.1, but the same happens also in 2.7) list = [1,2,3] Ben Finney has already answered the main question, but as a side point, I would generally avoid creating a variable called 'list'. That's the name of the type (Python 2) or class (Python 3) of all lists, so it might result in confusion if you have an actual list with that name. If you want the behaviour of joining two lists (or adding something to a list) and saving the result elsewhere, you can use the plain addition: a=[1,2,3] b=a+[[4,5,6]] Note that you have to add a list, and it will append the contents of that list. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Thu, May 26, 2011 at 5:20 PM, Chris Angelico ros...@gmail.com wrote: Ben Finney has already answered the main question Giving credit where credit's due, it was more Chris Rebert's post that answered the question. Sorry Chris! Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On May 26, 12:46 am, Uncle Ben bgr...@nycap.rr.com wrote: In playing with lists of lists, I found the following: (In 3.1, but the same happens also in 2.7) list = [1,2,3] list.append ( [4,5,6] ) x = list x - [1,2,3,[4,5,6]] as expected. But the shortcut fails: list=[1,2,3] x = list.append( [4,5,6] ) x - nothing Can someone explain this to me? Uncle Ben Thank you all. It is wonderful to have this community as a resource. Uncle Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Thu, May 26, 2011 at 12:23 AM, Chris Angelico ros...@gmail.com wrote: On Thu, May 26, 2011 at 5:20 PM, Chris Angelico ros...@gmail.com wrote: Ben Finney has already answered the main question Giving credit where credit's due, it was more Chris Rebert's post that answered the question. Sorry Chris! Eh, one can't fight chronology! I'm just surprised that the docstring doesn't explicitly state Returns None. by this point, given that this is such a common point of newbie confusion. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On 26/05/2011 06:17, Chris Rebert wrote: On Wed, May 25, 2011 at 9:46 PM, Uncle Benbgr...@nycap.rr.com wrote: In playing with lists of lists, I found the following: (In 3.1, but the same happens also in 2.7) list = [1,2,3] list.append ( [4,5,6] ) Note the lack of output after this line. This indicates that list.append([4,5,6]) returned None. Contrast this with, say, list.pop(). x = list x - [1,2,3,[4,5,6]] as expected. But the shortcut fails: list=[1,2,3] x = list.append( [4,5,6] ) x - nothing Can someone explain this to me? The append() method does *not* return the now-appended-to list. It is a mutator method that modifies the list object in-place; per convention, it therefore returns None to reinforce its side-effecting nature to the user (the interactive interpreter by default does not display None expression results); analogous methods in other languages return void. list.remove(), list.sort(), and list.extend() similarly return None rather than the now-modified list. I'd just like to point out that it's a convention, not a rigid rule. Sometimes it's not followed, for example, dict.setdefault. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Fri, May 27, 2011 at 1:58 AM, MRAB pyt...@mrabarnett.plus.com wrote: I'd just like to point out that it's a convention, not a rigid rule. Sometimes it's not followed, for example, dict.setdefault. dict.setdefault is more like dict.get but it also stores the result. It's probably more a name issue than a protocol issue. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On May 25, 9:46 pm, Uncle Ben bgr...@nycap.rr.com wrote: list = [1,2,3] Somewhat unrelated, but... is it a good idea to name your list list? Isn't that the name of Python's built-in list constructor method? Shadowing a built-in has contributed to more than one subtle bug in my code, and I've learned to avoid it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On 5/26/2011 3:18 AM, Algis Kabaila wrote: And why do you insist on calling an instance of list, list? Even a human reader will confuse which is which. What you are showing is an example how confusing things become when a keyword (list) is over-written (with list instance). (Minor note: 'list' is not a keyword (if it were, it could not be over-ridden) but it is a builtin.) You are correct, it is confusing. Such usage will also lead to bugs if one ever tries to access the class as 'list' later in the program. Here is a legitimate usage of builtins masking: import builtins def list(iterable): print('building list from {}: {}'.format(type(iterable),iterable)) return builtins.list(iterable) a = list((1,2,3)) b = list({1,2,3}) ### building list from class 'tuple': (1, 2, 3) building list from class 'set': {1, 2, 3} -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
RE: Puzzled by list-appending behavior
And why do you insist on calling an instance of list, list? Even a human reader will confuse which is which. What you are showing is an example how confusing things become when a keyword (list) is over-written (with list instance). (Minor note: 'list' is not a keyword (if it were, it could not be over-ridden) but it is a builtin.) You are correct, it is confusing. Such usage will also lead to bugs if one ever tries to access the class as 'list' later in the program. An example of overriding built-ins you *really* do not want to happen (python 2.6.4): True = False True == False True print True False From what I can tell, this does not work in Python 3.x (at least not in Python 3.1.1) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On 5/26/2011 11:58 AM, MRAB wrote: On 26/05/2011 06:17, Chris Rebert wrote: list.remove(), list.sort(), and list.extend() similarly return None rather than the now-modified list. I'd just like to point out that it's a convention, not a rigid rule. Sometimes it's not followed, for example, dict.setdefault. The rule for builtin collections is that mutation methods do not return the collection. If there is a member of the collection to return, they return that. Otherwise they return None. list/set.pop and dict.popitem are other mutation methods that have a (former) member to return. The rule applies to special methods like __getitem__ (returns an item) and __setitem__ (returns None). Since a.append(item) is *conceptually* equivalent to a.__setitem(len(a), item) (I know, it raises) and *actually* defined as a.__setitem(len(a):len(a), item), it should not be surprising that all three return None. I think the above should be better documented. http://bugs.python.org/issue12192 has some proposals. Comments there welcome. In another post On 5/26/2011 4:09 AM, Chris Rebert wrote: I'm just surprised that the docstring doesn't explicitly state Returns None. by this point, given that this is such a common point of newbie confusion. I never noticed. After reading the above, I added this to the proposal above. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Thu, 26 May 2011 11:27:35 -0700, John Ladasky wrote: On May 25, 9:46 pm, Uncle Ben bgr...@nycap.rr.com wrote: list = [1,2,3] Somewhat unrelated, but... is it a good idea to name your list list? Isn't that the name of Python's built-in list constructor method? Shadowing a built-in has contributed to more than one subtle bug in my code, and I've learned to avoid it. Agreed. However, there are good reasons for sometimes shadowing built- ins, and namespaces make it safe to do so if you are sufficiently careful. E.g. I have a module stats.sum() which shadows the built-in, but only in that module, which is exactly the behaviour I want. (If you do from stats import sum, then you're responsible for whatever happens next.) Or you might isolate the shadow to a function small enough that you can be sure that it won't cause any problems, e.g.: def get(list, object): Append object to a copy of list and return it. return list + [object] For one or two line functions, I think that's perfectly reasonable. Anything more than that, I'd be getting nervous. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Fri, May 27, 2011 at 11:59 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: def get(list, object): Append object to a copy of list and return it. return list + [object] For one or two line functions, I think that's perfectly reasonable. Anything more than that, I'd be getting nervous. But even for something that short, why do it? Why not call the parameter 'lst' or something? Shadowing with something completely different is seldom going to give major advantage, and has the potential to be quite confusing. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Fri, 27 May 2011 13:24:24 +1000, Chris Angelico wrote: On Fri, May 27, 2011 at 11:59 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: def get(list, object): Append object to a copy of list and return it. return list + [object] For one or two line functions, I think that's perfectly reasonable. Anything more than that, I'd be getting nervous. But even for something that short, why do it? Why not call the parameter 'lst' or something? Shadowing with something completely different is seldom going to give major advantage, and has the potential to be quite confusing. Because lst is not a real word. To native readers of languages derived from Latin or Germany, such as English, it is quite a strange word because it has no vowel. In addition, it looks like 1st (first). We use naming conventions like my_list list_ lst alist etc. to avoid shadowing the built-in list, not because they are good to use in and of themselves. (E.g. we don't write my_tree because there's no tree to shadow.) All of these are ugly to some extent, which is to say, they cause some small, or not so small, additional cognitive load to the reader. We don't use the name list_ because we like trailing underscores! We do it because it avoids the cost of shadowing a built-in. But in a small function, there's no real cost to shadowing, so why bother? Any hypothetical confusion caused is no greater than, and probably less than, the increased difficulty in reading any of the alternatives. Either way, we're talking micro-optimizations in readability here. Don't get hung up over the choice of a name. If you'd rather never shadow, I'm fine with that too. I just think never shadow is unnecessarily strict. Sometimes shadowing is harmless, and sometimes it's useful. If you're writing a tutorial for beginners, shadowing a built-in without explanation will cause confusion, but for production code, I think it reasonable to assume the reader knows Python well enough not to stumble over that choice. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Fri, May 27, 2011 at 1:52 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Because lst is not a real word. To native readers of languages derived from Latin or Germany, such as English, it is quite a strange word because it has no vowel. In addition, it looks like 1st (first). Contrived examples are always awkward; in real examples, there's often an alternative based on the list's purpose, which can then be used to offer a name. Sometimes shadowing is harmless, and sometimes it's useful. Agreed on both those halves; and obviously, the times where it's useful are very much important. I have to say, I do like Python's lack of keywords for these things; the ability to shadow is a flexibility that means that, for the most part, new builtins can be added to the language without breaking existing code. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
Uncle Ben bgr...@nycap.rr.com writes: Can someone explain this to me? Yes, the documentation for that function (‘list.append’) can explain it. In short: if a method modifies the instance, that method does not return the instance. This policy holds for the built-in types, and should be followed for user-defined types also. -- \ “[I]t is impossible for anyone to begin to learn that which he | `\thinks he already knows.” —Epictetus, _Discourses_ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by list-appending behavior
On Wed, May 25, 2011 at 9:46 PM, Uncle Ben bgr...@nycap.rr.com wrote: In playing with lists of lists, I found the following: (In 3.1, but the same happens also in 2.7) list = [1,2,3] list.append ( [4,5,6] ) Note the lack of output after this line. This indicates that list.append([4,5,6]) returned None. Contrast this with, say, list.pop(). x = list x - [1,2,3,[4,5,6]] as expected. But the shortcut fails: list=[1,2,3] x = list.append( [4,5,6] ) x - nothing Can someone explain this to me? The append() method does *not* return the now-appended-to list. It is a mutator method that modifies the list object in-place; per convention, it therefore returns None to reinforce its side-effecting nature to the user (the interactive interpreter by default does not display None expression results); analogous methods in other languages return void. list.remove(), list.sort(), and list.extend() similarly return None rather than the now-modified list. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
On 05/15/10 10:27, Adam Tauno Williams wrote: I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: handle = open('file.txt', 'rb') data = handle.read() handle.close() data 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' I presume you're using Python 2.x. What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? I can read the file using codecs as ISO8859-2, but it still doesn't seem correct. handle = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = handle.read() handle.close() data u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' When printing in the interactive interpreter, python uses __repr__ representation by default. If you want to use __str__ representation use print data (note, your terminal must support printing unicode characters); either way, even though the string looks like '\u0102' when printed on the terminal, the binary pattern inside the memory should correctly represents the accented character. f = codecs.open(in.txt, 'rb', encoding=iso8859-2) f2 = codecs.open(out.txt, 'wb', encoding=utf-8) s = f.read() f2.write(s) f.close() f2.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote: On 05/15/10 10:27, Adam Tauno Williams wrote: I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: handle = open('file.txt', 'rb') data = handle.read() handle.close() data 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' I presume you're using Python 2.x. Yes. But the days of all-unicode-strings will be wonderful when it comes. :) What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? I can read the file using codecs as ISO8859-2, but it still doesn't seem correct. handle = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = handle.read() handle.close() data u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' When printing in the interactive interpreter, python uses __repr__ representation by default. If you want to use __str__ representation use print data (note, your terminal must support printing unicode characters); Using GNOME Terminal, so Unicode characters should display correctly. And I do see the characters when I 'cat' the file. either way, even though the string looks like '\u0102' when printed on the terminal, the binary pattern inside the memory should correctly represents the accented character. Yep. But in the interpreter both unicode() and repr() produce the same output. Nothing displays the accented character. h = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = h.read() h.close() str(data) 'ascii' codec can't encode characters in position 33-34: ordinal not in range(128) unicode(data) u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' repr(data) 'u\'skyp4_filelist_10201/localit\\u0102\\xa0 termali_sortfield = NSFileName;\\n\'' I think I'm getting close. Parsing the file seems to work, and while writing it out does not error, rereading my own output fails. :( Possibly I'm 'accidentally' writing the output as UTF-8 and not ISO8859-2. I need the internal data to be UTF-8 but read as ISO8859-2 and rewritten back to ISO8859-2 [at least that is what I believe from the OpenStep files I'm seeing]. What is the 'official' way to encode something from UTF-8 to another code page. I *assumed* that if I wrote a unicode stream back through: h = codecs.open(output_filename, 'wb', encoding='iso8859-2') data = writer.store(defaults) h.write(data) h.close() that is would be re-encoded [word?]. But maybe not? f = codecs.open(in.txt, 'rb', encoding=iso8859-2) f2 = codecs.open(out.txt, 'wb', encoding=utf-8) s = f.read() f2.write(s) f.close() f2.close() -- Adam Tauno Williams awill...@whitemice.org LPIC-1, Novell CLA http://www.whitemiceconsulting.com OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba skyp4_filelist_10201/località termali_sortfield = NSFileName; -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
On 05/16/10 00:12, Adam Tauno Williams wrote: On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote: On 05/15/10 10:27, Adam Tauno Williams wrote: I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: handle = open('file.txt', 'rb') data = handle.read() handle.close() data 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' I presume you're using Python 2.x. Yes. But the days of all-unicode-strings will be wonderful when it comes. :) What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? I can read the file using codecs as ISO8859-2, but it still doesn't seem correct. handle = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = handle.read() handle.close() data u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' When printing in the interactive interpreter, python uses __repr__ representation by default. If you want to use __str__ representation use print data (note, your terminal must support printing unicode characters); Using GNOME Terminal, so Unicode characters should display correctly. And I do see the characters when I 'cat' the file. 'cat' works because 'cat' works in bytes and doesn't try to interpret the stream it is writing. You can tell python to output string instead of unicode to get the same effect. h = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = h.read() h.close() str(data) 'ascii' codec can't encode characters in position 33-34: ordinal not in range(128) this means either your terminal can't print unicode or python for some reason thinks that the terminal is ascii terminal. You can encode the string manually, e.g.: print u'\u0102\xa0'.encode('utf-8') or you should figure out a way to set your terminal properly so python recognizes it as utf-8 terminal, see http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/ when python tries to print unicode object, python first needs to encode that 'unicode' object into 'str'; by default python uses sys.stdout.encoding to determine the encoding to use when printing unicode object. unicode(data) u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' If data is a 'unicode', this is not surprising, as 'unicode(data)' simply returns 'data'. I think I'm getting close. Parsing the file seems to work, and while writing it out does not error, rereading my own output fails. :( Possibly I'm 'accidentally' writing the output as UTF-8 and not ISO8859-2. I need the internal data to be UTF-8 but read as ISO8859-2 and rewritten back to ISO8859-2 [at least that is what I believe from the OpenStep files I'm seeing]. unicode string doesn't have encoding (well, python needs some encoding to store the unicode data in RAM, but that's implementation detail). unicode string is not a stream of bytes encoded in specific way, it's an encoding-agnostic block of text. What is the 'official' way to encode something from UTF-8 to another code page. I *assumed* that if I wrote a unicode stream back through: h = codecs.open(output_filename, 'wb', encoding='iso8859-2') data = writer.store(defaults) h.write(data) h.close() what's writer.store(defaults)? It should return a 'unicode' if you want h.write() to work properly. Otherwise, if data is 'str', h.write will try to decode the 'str' to 'unicode' using the default decoder (usually ascii), then encode that 'unicode' to 'iso8859-2'. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
Adam Tauno Williams awill...@whitemice.org wrote in message news:1273932760.3929.18.ca...@linux-yu4c.site... On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote: On 05/15/10 10:27, Adam Tauno Williams wrote: [snip] Yep. But in the interpreter both unicode() and repr() produce the same output. Nothing displays the accented character. h = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = h.read() h.close() str(data) Here you are correctly reading an iso8859-2-encoded file and converting it to Unicode. Try print data. str(data) converts from Unicode strings to byte strings, but only uses the default encoding, which is 'ascii'. print will use the stdout encoding of your terminal, if known. Try these commands on your system (mine is Windows XP): import sys sys.getdefaultencoding() 'ascii' sys.stdout.encoding 'cp437' You should only attempt to print Unicode strings or byte strings encoded in the stdout encoding. Printing byte strings in any other encoding will often print garbage. [snip] I think I'm getting close. Parsing the file seems to work, and while writing it out does not error, rereading my own output fails. :( Possibly I'm 'accidentally' writing the output as UTF-8 and not ISO8859-2. I need the internal data to be UTF-8 but read as ISO8859-2 and rewritten back to ISO8859-2 [at least that is what I believe from the OpenStep files I'm seeing]. internal data is Unicode, not UTF-8. Unicode is the absence of an encoding (Python uses UTF-16 or UTF-32 internally, but that is an implementation detail). UTF-8 is a byte-encoding. If you actually need the internal data as UTF-8 (maybe you are working with a library that works with UTF-8 strings, then: f = codecs.open(in.txt, 'rb', encoding=iso8859-2) s = f.read() # s is a Unicode string. s = s.encode('utf-8') # now s is a UTF-8 byte string f.close() (process data as UTF-8 here). s = s.decode('utf-8') # s is Unicode again. f2 = codecs.open(out.txt, 'wb', encoding=iso8859-2) f2.write(s) f2.close() Note you *decode* byte strings to Unicode and *encode* Unicode into byte strings. -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
Adam Tauno Williams awilliam at whitemice.org writes: On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote: I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? Buried in the parser is a str(...) call. Replacing that with unicode(...) and now the OpenSTEP plist parser is working with Italian plists. Some observations: Italian text is much more likely to be encoded in ISO-8859-1 than ISO-8859-2. The latter covers eastern European languages (e.g. Polish, Czech, Hungarian) that use the Latin alphabet with many decorations not found in western alphabets. Let's look at the 'localit\xc3\xa0' example. Using ISO-8859-2, that decodes to u'localit\u0102\xa0'. The second-last character is LATIN CAPITAL LETTER A WITH BREVE (according to unicodedata.name()). The last character is NO-BREAK SPACE. Doesn't look like an Italian word to me. However, using UTF-8, that decodes to u'localit\xe0'. The last character is LATIN SMALL LETTER A WITH GRAVE. Looks like a plausible Italian word to me. Also to Wikipedia: A località (literally locality; plural località) is the name given in Italian administrative law to a type of territorial subdivision of a comune ... Conclusions: It's worth closely scrutinising accented characters - equivalent to ISO-8859-2 (I believe). Which variety of OpenStep plist files are you looking at: NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document, and you should be letting the XML parser decode it for you and in any case as an XML document it's most likely UTF-8, not ISO-8859-2. It's worth examining your definition of working. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
Conclusions: It's worth closely scrutinising accented characters - equivalent to ISO-8859-2 (I believe). Which variety of OpenStep plist files are you looking at: NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document, and you should be letting the XML parser decode it for you and in any case as an XML document it's most likely UTF-8, not ISO-8859-2. It's worth examining your definition of working. I came to the same conclusions after reading the OP's article. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote: I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: handle = open('file.txt', 'rb') data = handle.read() handle.close() data 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? Typical, 30 seconds after giving up and posting a message... I find the problem. Buried in the parser is a str(...) call. Replacing that with unicode(...) and now the OpenSTEP plist parser is working with Italian plists. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
Buy high quality TAG Heuer Tiger Woods Golf Watches at low price, you can not believe, but it is true. There are two models on http://www.luxuryowner.net/Replica-TAG-Heuer-Tiger-Woods-Golf-Watches.html White: Tag Heuer Tiger Woods Golf White Mens Watch WAE1112.FT6008: http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-White-Mens-Watch-WAE1112.FT6008.html Black: Tag Heuer Tiger Woods Golf Black Mens Watch WAE.FT6004 http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-Black-Mens-Watch-WAE.FT6004.html More replica watches you can refer: http://www.luxuryowner.net/ Adam Tauno Williams awill...@whitemice.org дÈëÏûÏ¢ÐÂÎÅ:mailman.193.1273883243.32709.python-l...@python.org... I'm trying to process OpenStep plist files in Python. I have a parser which works, but only for strict ASCII. However plist files may contain accented characters - equivalent to ISO-8859-2 (I believe). For example I read in the line: handle = open('file.txt', 'rb') data = handle.read() handle.close() data 'skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield = NSFileName;\n' What is the correct way to re-encode this data into UTF-8 so I can use unicode strings, and then write the output back to ISO8859-? I can read the file using codecs as ISO8859-2, but it still doesn't seem correct. handle = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = handle.read() handle.close() data u'skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield = NSFileName;\n' -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled about this regex
On Fri, Apr 17, 2009 at 7:17 PM, Jean-Claude Neveu jcn-france1...@pobox.com wrote: Hello, I wonder if someone could tell me where I am going wrong with my regular expression, please. My regex only matches the text I'm looking for (a number followed by a distance unit) when it appears at the beginning of the string. But I am not using the ^ character (which would indicate that I only want a match if it is at the start). Reading the fine manual, http://docs.python.org/library/re.html : re.match(pattern, string[, flags]) If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match. ***Note: If you want to locate a match anywhere in string, use search() instead.*** re.search(pattern, string[, flags]) Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by behaviour of class with empty constructor
On Jan 25, 5:54 pm, [EMAIL PROTECTED] wrote: On Jan 25, 5:46 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: print x.ends,y.ends,z.ends # Running the following code outputs: [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? Yes. You bound a single list to the name ends inside the class. This name is shared by all instances. If you want the instances to each have separate lists, delete the ends definition from class declaration and insert self.ends = [] into __init__. I also suggest you to have a look at the tutorial. Regards, Björn -- BOFH excuse #49: Bogon emissions Björn, Thanks for the help. I had misguidedly defined the members of all of my classes as in the example above; I never noticed the issue with any of the others because they did not have empty constructors. Thanks again for the correction. Yeah! thanks all. I did not realize the distinction either. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by behaviour of class with empty constructor
[EMAIL PROTECTED] wrote: Hello, I have a class called 'Axis' that I use as a base class for several types of axes that can be created by a grid generation program that I have written: equally-spaced grids, logarithmic grids, etc. In any case, if I use this base class by itself, I see some puzzling behaviour: # class Axis: ends = [] N = None def __init__(self): pass x = Axis() y = Axis() z = Axis() x.ends.append((0,2)) print x.ends,y.ends,z.ends # Running the following code outputs: [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? Well, you are using a class variable - Axis.ends. It's shared among all instances of Axis class. To have it separate setup it in __init__ like: class Axix: def __init__(self): self.ends = [] self.N = None You see, code inside class, but outside methods is executed only once and any variables are then linked with class, and not instances (more/less). Take look at: http://docs.python.org/tut/node11.html ~TomekP -- Someone whom you reject today, will reject you tomorrow. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by behaviour of class with empty constructor
On Jan 25, 5:46 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: print x.ends,y.ends,z.ends # Running the following code outputs: [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? Yes. You bound a single list to the name ends inside the class. This name is shared by all instances. If you want the instances to each have separate lists, delete the ends definition from class declaration and insert self.ends = [] into __init__. I also suggest you to have a look at the tutorial. Regards, Björn -- BOFH excuse #49: Bogon emissions Björn, Thanks for the help. I had misguidedly defined the members of all of my classes as in the example above; I never noticed the issue with any of the others because they did not have empty constructors. Thanks again for the correction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by behaviour of class with empty constructor
[EMAIL PROTECTED] schrieb: Hello, I have a class called 'Axis' that I use as a base class for several types of axes that can be created by a grid generation program that I have written: equally-spaced grids, logarithmic grids, etc. In any case, if I use this base class by itself, I see some puzzling behaviour: # class Axis: ends = [] N = None def __init__(self): pass x = Axis() y = Axis() z = Axis() x.ends.append((0,2)) print x.ends,y.ends,z.ends # Running the following code outputs: [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? It's simple - you didn't create an instance-variable, but instead a class-variable. You need to do this: class Axis: def __init__(self): self.ends = [] Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by behaviour of class with empty constructor
[EMAIL PROTECTED] wrote: print x.ends,y.ends,z.ends # Running the following code outputs: [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? Yes. You bound a single list to the name ends inside the class. This name is shared by all instances. If you want the instances to each have separate lists, delete the ends definition from class declaration and insert self.ends = [] into __init__. I also suggest you to have a look at the tutorial. Regards, Björn -- BOFH excuse #49: Bogon emissions -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled about floats
On Mon, 24 Sep 2007 14:13:18 -0400, Neal Becker wrote: from math import modf class nco (object): def __init__ (self, delta): self.delta = delta self.phase = 0.0 def __call__ (self): self.phase += self.delta f,i = modf (self.phase) print modf (self.phase) if (self.phase 1.0): self.phase -= 1.0 return self.phase n = nco (0.1) for x in xrange (100): print '%.12f' % n() prints out [...] (0.99978, 0.0)from modf 1.from n() I'm baffled as to why 'print modf (self.phase)' prints out the first value, but the result printed in the 2nd case is different. Without any precision spec on the first print, an approximate float value was printed, but even with %.12f, the second gives exactly 1.000 Tuples are printed with calling `repr()` on the objects: In [144]: str(0.1) Out[144]: '0.1' In [145]: repr(0.1) Out[145]: '0.10001' In [146]: '%.12f' % 0.1 Out[146]: '0.1000' In [147]: '%.50f' % 0.1 Out[147]: '0.1555111512312578270211815834045410' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled in the coding of Chinese
On Wed, 2007-09-19 at 13:57 +0800, Xing wrote: Dear list members, I am a newcomer in the world of Python. But I am attracted by Python's power in handling text! Now I apply it to handle Chinese but the Chinese character cann't be displayed on the screen. What displayed on the screen is the 16bits codes. I am so puzzled! I believe this is an easy question to most of python users and an important question to me. Thanks a lot to your help! You are not giving us any background information for troubleshooting this. Your problem could be caused by a million different things, and there is not point in us guessing. Please start by answering the following questions: 1) What operating system are you using? 2) Can any programs on your computer display Chinese characters? 3) Where are you trying to display Chinese characters? Python command line, in IDLE, in some GUI window? 4) Where are the Chinese characters you're trying to display coming from? Are they hard-coded in your script, are they read from the keyboard, from a file, from a database, from a web page? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores [EMAIL PROTECTED] writes: At 06:13 PM 8/9/2007, Ben Finney wrote: it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? For the purpose of the above statement, you should consider even the same Python on two different machines to be different implementations. As a programmer writing Python code, you should not expect any implementation-dependent behaviour to operate in any particular way. -- \ The fact that a believer is happier than a skeptic is no more | `\ to the point than the fact that a drunken man is happier than a | _o__) sober one. —George Bernard Shaw | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On 8/12/07, Ben Finney [EMAIL PROTECTED] wrote: Dick Moores [EMAIL PROTECTED] writes: At 06:13 PM 8/9/2007, Ben Finney wrote: it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? For the purpose of the above statement, you should consider even the same Python on two different machines to be different implementations. As a programmer writing Python code, you should not expect any implementation-dependent behaviour to operate in any particular way. So would a programmer EVER use is in a script? Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: On 8/12/07, *Ben Finney* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: Dick Moores [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] writes: At 06:13 PM 8/9/2007, Ben Finney wrote: it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? For the purpose of the above statement, you should consider even the same Python on two different machines to be different implementations. As a programmer writing Python code, you should not expect any implementation-dependent behaviour to operate in any particular way. So would a programmer EVER use is in a script? Sure. For example, the canonical test for None uses x is None because there is only ever one instance of type Nonetype, so it's the fastest test. Generally speaking you use is to test for identity (do these two expressions reference the same object) rather than equality (do these two expressions evaluate to equivalent objects). regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
At 08:23 AM 8/12/2007, Steve Holden wrote: Dick Moores wrote: So would a programmer EVER use is in a script? Sure. For example, the canonical test for None uses x is None because there is only ever one instance of type Nonetype, so it's the fastest test. Generally speaking you use is to test for identity (do these two expressions reference the same object) rather than equality (do these two expressions evaluate to equivalent objects). Off the top of your head, could you or others give me as many examples as you can think of? Thanks again, Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: At 08:23 AM 8/12/2007, Steve Holden wrote: Dick Moores wrote: So would a programmer EVER use is in a script? Sure. For example, the canonical test for None uses x is None because there is only ever one instance of type Nonetype, so it's the fastest test. Generally speaking you use is to test for identity (do these two expressions reference the same object) rather than equality (do these two expressions evaluate to equivalent objects). Off the top of your head, could you or others give me as many examples as you can think of? Occasionally it's necessary to test for a specific type (though in Python this is usually bad practice). Since types are also singletons the best way to do this is (e.g.): type(x) is type([]) # test specifically for a list If you want to know whether you have been told to write to standard output, one possible test is if f is not sys.stdout Similarly, of course, you can test for the other standard IO channels. The imputil module contains the test if importer is not self to determine whether a reload() should be performed in the context of the current package. When you need to establish a specific sentinel value that can never be provided by an outside caller it's normal to create an instance of object (the simplest possible thing you can create in a Python program) and test for that instance, as in sentinel = object() ... if value is sentinel: You can test whether a class is new-style as opposed to old-style, which can help to unify old-style and new-style objects: class MetaProperty(type): def __new__(cls, name, bases, dct): if bases[0] is object: # allow us to create class Property return type.__new__(cls, name, bases, dct) return property(dct.get('get'), dct.get('set'), dct.get('delete'), dct.get('__doc__')) def __init__(cls, name, bases, dct): if bases[0] is object: return type.__init__(cls, name, bases, dct) That gets you started ... regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
At 09:59 AM 8/12/2007, Steve Holden wrote: Dick Moores wrote: At 08:23 AM 8/12/2007, Steve Holden wrote: Dick Moores wrote: So would a programmer EVER use is in a script? Sure. For example, the canonical test for None uses x is None because there is only ever one instance of type Nonetype, so it's the fastest test. Generally speaking you use is to test for identity (do these two expressions reference the same object) rather than equality (do these two expressions evaluate to equivalent objects). Off the top of your head, could you or others give me as many examples as you can think of? Occasionally it's necessary to test for a specific type (though in Python this is usually bad practice). Since types are also singletons the best way to do this is (e.g.): type(x) is type([]) # test specifically for a list If you want to know whether you have been told to write to standard output, one possible test is if f is not sys.stdout Similarly, of course, you can test for the other standard IO channels. The imputil module contains the test if importer is not self to determine whether a reload() should be performed in the context of the current package. When you need to establish a specific sentinel value that can never be provided by an outside caller it's normal to create an instance of object (the simplest possible thing you can create in a Python program) and test for that instance, as in sentinel = object() ... if value is sentinel: You can test whether a class is new-style as opposed to old-style, which can help to unify old-style and new-style objects: class MetaProperty(type): def __new__(cls, name, bases, dct): if bases[0] is object: # allow us to create class Property return type.__new__(cls, name, bases, dct) return property(dct.get('get'), dct.get('set'), dct.get('delete'), dct.get('__doc__')) def __init__(cls, name, bases, dct): if bases[0] is object: return type.__init__(cls, name, bases, dct) That gets you started ... Sure does. Thanks very much, Steve. Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: At 06:13 PM 8/9/2007, Ben Finney wrote: It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? (Note that I'm jumping into this without having read the thread, so apologies if I didn't grasp the question in its proper context.) Separate Python implementations generally refers to a separate source code base for that Python build. According to that definition, current examples of Python implementations are: CPython (from python.org, C-based), Jython (Java-based), Stackless Python (I'm not that familiar to how much of the CPython source code, if any, Stackless borrows), IronPython (.NET/C#-based), possibly PyPy (Python-based, I'm not that familiar with it). Also eventually interesting might be the recently announced IronMonkey (http://wiki.mozilla.org/Tamarin:IronMonkey). Windows, Mac, Linux, etc. installations/builds/installers of a particular implementation would be different platform *builds* (my language). ActivePython is a separate (from python.org's) *distribution* of CPython -- i.e. the sample implementation as CPython (same source code). This is similar, in some respects, to SuSE, Debian, RedHat, Ubuntu, etc. being different distributions of Linux. Trent -- Trent Mick trentm at activestate.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On Fri, 10 Aug 2007 10:57:22 -0700, Dick Moores wrote: At 06:13 PM 8/9/2007, Ben Finney wrote: Others have already said that it's an implementation optimisation, which seems to partly answer your question. It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? Taken to the extreme you shouldn't rely on implementation details at all, so even the very same interpreter might cache and reuse the empty tuple in one run but not in the next. For me CPython, Iron Python and Jython are different implementations as they are all written from scratch. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
At 06:13 PM 8/9/2007, Ben Finney wrote: Content-Transfer-Encoding: base64Grzegorz SÅodkowicz [EMAIL PROTECTED] [EMAIL PROTECTED] theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. Others have already said that it's an implementation optimisation, which seems to partly answer your question. It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. I'm not clear on the meaning of implementations here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? Thanks, Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: () is () True (1,) is (1,) False Why? Thanks, Dick Moores From the docs for 'is': -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: () is () True (1,) is (1,) False Why? a = () b = () c = (1,) d = (1,) a is b True c is d False id(a) 3086553132 id(b) 3086553132 id(c) 3086411340 id(d) 3086390892 There is only one empty tuple. Does that clear it up for you? Thanks, Dick Moores -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On 2007-08-09, Dick Moores [EMAIL PROTECTED] wrote: () is () True (1,) is (1,) False Why? From _Python Reference Manual_: 5.2.4 List displays: An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object). -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Jay Loden wrote: Dick Moores wrote: () is () True (1,) is (1,) False Why? Thanks, Dick Moores From the docs for 'is': The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. So you're actually testing whether or not the identity of the object is the same, not whether (1,) == (1,): (1,) == (1,) True id((0,)) == id((0,)) False -Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
At 10:46 AM 8/9/2007, Bill Scherer wrote: Dick Moores wrote: () is () True (1,) is (1,) False Why? a = () b = () c = (1,) d = (1,) a is b True c is d False id(a) 3086553132 id(b) 3086553132 id(c) 3086411340 id(d) 3086390892 There is only one empty tuple. Does that clear it up for you? But isn't that the same as saying, That's just the reality of Python; it is what it is.? I want to know why there is only one empty tuple, but more than one (1,). Also, [] is [] False Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Dick Moores wrote: At 10:46 AM 8/9/2007, Bill Scherer wrote: Dick Moores wrote: [...] There is only one empty tuple. Does that clear it up for you? But isn't that the same as saying, That's just the reality of Python; it is what it is.? I want to know why there is only one empty tuple, but more than one (1,). Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. Also, [] is [] False In that case it would definitely NOT make sense to have them the same list. Python always ensures that the [] constructor creates a new list, since that list may be bound to one or more variables and mutated. You wouldn't want a = [] b = [] a.append(boo!) to change b so it was no longer an empty list. If you wanted a and b to reference the same list you would change the second statement to b = a regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On 15:53 Thu 09 Aug , Steve Holden wrote: Dick Moores wrote: At 10:46 AM 8/9/2007, Bill Scherer wrote: Dick Moores wrote: [...] There is only one empty tuple. Does that clear it up for you? But isn't that the same as saying, That's just the reality of Python; it is what it is.? I want to know why there is only one empty tuple, but more than one (1,). Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. Also, [] is [] False In that case it would definitely NOT make sense to have them the same list. Python always ensures that the [] constructor creates a new list, since that list may be bound to one or more variables and mutated. You wouldn't want a = [] b = [] a.append(boo!) to change b so it was no longer an empty list. If you wanted a and b to reference the same list you would change the second statement to b = a regards Steve OK fiddling around with this and reading the docs I tried:- a = 'qq' #10 q's b = 'qq' #10 q's a is b true c = 'q' * 10 c 'qq' #10 q's d = 'q' * 10 d 'qq' #10 q's c is d false So from what I've read == tests for equivalence, is tests for identity but that does not explain the behaviour above. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On Aug 9, 2:53 pm, Steve Holden [EMAIL PROTECTED] wrote: Dick Moores wrote: At 10:46 AM 8/9/2007, Bill Scherer wrote: Dick Moores wrote: [...] There is only one empty tuple. Does that clear it up for you? But isn't that the same as saying, That's just the reality of Python; it is what it is.? I want to know why there is only one empty tuple, but more than one (1,). Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. Also, [] is [] False In that case it would definitely NOT make sense to have them the same list. Python always ensures that the [] constructor creates a new list, since that list may be bound to one or more variables and mutated. You wouldn't want a = [] b = [] a.append(boo!) to change b so it was no longer an empty list. If you wanted a and b to reference the same list you would change the second statement to b = a regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - Steve, I thought you'd probably weigh in on this esoteric matter. Very illuminating, as usual. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
On 2007-08-09, John K Masters [EMAIL PROTECTED] wrote: On 15:53 Thu 09 Aug , Steve Holden wrote: Dick Moores wrote: At 10:46 AM 8/9/2007, Bill Scherer wrote: Dick Moores wrote: [...] There is only one empty tuple. Does that clear it up for you? But isn't that the same as saying, That's just the reality of Python; it is what it is.? I want to know why there is only one empty tuple, but more than one (1,). Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. Also, [] is [] False In that case it would definitely NOT make sense to have them the same list. Python always ensures that the [] constructor creates a new list, since that list may be bound to one or more variables and mutated. You wouldn't want a = [] b = [] a.append(boo!) to change b so it was no longer an empty list. If you wanted a and b to reference the same list you would change the second statement to b = a regards Steve OK fiddling around with this and reading the docs I tried:- a = 'qq' #10 q's b = 'qq' #10 q's CPython is full of cute little optimizations, and one of them is that literal strings less than a certain length are 'interned'. This makes them very fast to compare for equality, and cheaper to store (maybe?). a is b true c = 'q' * 10 c 'qq' #10 q's d = 'q' * 10 d 'qq' #10 q's c is d false So from what I've read == tests for equivalence, is tests for identity but that does not explain the behaviour above. The 10 q's constructed with string arithmetic were not interned, because they were not literals. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
[EMAIL PROTECTED] wrote: [...] Steve, I thought you'd probably weigh in on this esoteric matter. Very illuminating, as usual. Thank you! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. This could save some memory if the tuple was large (Although by the same token comparison of large tuples can be expensive). Admittedly the empty tuple is a special case but then 'Special cases aren't special enough to break the rules'. A bit odd. Best regards, Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
John K Masters wrote: OK fiddling around with this and reading the docs I tried:- a = 'qq' #10 q's b = 'qq' #10 q's a is b true c = 'q' * 10 c 'qq' #10 q's d = 'q' * 10 d 'qq' #10 q's c is d false So from what I've read == tests for equivalence, is tests for identity but that does not explain the behaviour above. Using the `is` test between non-sentinel immutable objects (e.g., integers, floats, strings) is _completely pointless_. Since immutable objects cannot be changed, it is up to the interpreter (and thus can vary from version to version and implementation to implementation) whether or not to cache the objects and reuse them, or whether or not to create new ones. You should never be testing such objects for identity (`is`); you should only be testing them for equality (`==`). The only time it makes sense to use the `is` operator with immutable objects is when you're dealing with a sentinel object, e.g., `None`, or a custom sentinel object (e.g., `mySentinel = object()`), because that is the only time you actually _are_ interested in identity. All other times you are not really interested in identity. Sample code as above is essentially showing unimportant implementation details that should never concern you. Don't use `is`, use `==`. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM, Y!M erikmaxfrancis Chance favors the trained mind. -- Louis Pasteur -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Grzegorz Słodkowicz wrote: That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. This could save some memory if the tuple was large (Although by the same token comparison of large tuples can be expensive). Admittedly the empty tuple is a special case but then 'Special cases aren't special enough to break the rules'. A bit odd. It doesn't save time if you have to check through all the existing tuples for matches ... -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM, Y!M erikmaxfrancis Chance favors the trained mind. -- Louis Pasteur -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Grzegorz Słodkowicz wrote: Why? Because. Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. This could save some memory if the tuple was large (Although by the same token comparison of large tuples can be expensive). Admittedly the empty tuple is a special case but then 'Special cases aren't special enough to break the rules'. A bit odd. It's a trade-off, preferring to optimize time rather than memory usage. If tuples were interned like some strings then tuple creation would be more expensive due to the need to search the cache when creating them which, as you rightly point out, could be very expensive for large tuples. The integers under 100 are also, IIRC, special-cased: x = 12 y = 32676 x is 12 True y is 32676 False I guess if you *make* the rules you can decide when it's reasonable to break them! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Grzegorz Słodkowicz [EMAIL PROTECTED] writes: Seriously, it's just an optimization by the implementers. There is no need for more than one empty tuple, since tuples can never be modified once created. But they decided not to create (1, ) in advance. They probably knew that hardly anybody would want to create that tuple ;-) [Seriously: if you started trying to predict which tuples would be used you would go insane, but the empty tuple is the most likely candidate]. That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. But then tuple creation would be slowed down by searching for whether an identical one already exists. In the general case, that is quite unlikely, so it's not done. (I suspect that only the requirement to store the list of all tuples somewhere would outweigh any potential gains of this strategy; and if the search were implemented as a hash table lookup, even more space would be wasted.) It's done for the empty tuple because no search is necessary, only a size test. Admittedly the empty tuple is a special case but then 'Special cases aren't special enough to break the rules'. Except no rule is being broken. As others have pointed out, since tuples are immutable, caching them is quite safe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Grzegorz Słodkowicz [EMAIL PROTECTED] writes: That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. Others have already said that it's an implementation optimisation, which seems to partly answer your question. It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. -- \ Holy priceless collection of Etruscan snoods, Batman! -- | `\ Robin | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
Ben Finney wrote: It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. Right. In the terminology of language standards, it is implementation defined. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM, Y!M erikmaxfrancis Only love is worth the risk -- Oleta Adams -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by is
John K Masters [EMAIL PROTECTED] writes: OK fiddling around with this and reading the docs I tried:- a = 'qq' #10 q's b = 'qq' #10 q's a is b true c = 'q' * 10 c 'qq' #10 q's d = 'q' * 10 d 'qq' #10 q's c is d false So from what I've read == tests for equivalence, is tests for identity but that does not explain the behaviour above. There's nothing especially to be explained, other than that's the way the compiler does it. Two equal string literals might be the same object or they might not be. It's a language implementation detail. -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled about class attribute resolution and mangling
James Stroud said unto the world upon 2005-12-09 20:39: Brian van den Broek wrote: Hi all, I've the following code snippet that puzzles me: class Base(object): __v, u = Base v, Base u def __init__(self): print self.__v, self.u class Derived(Base): __v, u = Derived v, Derived u def __init__(self): print self.__v, self.u super(Derived, self).__init__() d = Derived() When run (Python 2.4.2, IDLE 1.1.2), it produces: Derived v Derived u Base v Derived u What I expected was that all four emitted strings would contain Derived. snip me -- Brian -- speculating on locus of my confusion Thanks and best, Brian vdB This is name mangling at work. Mangling turns self.__v in the Derrived class's __init__ method to self._Derrived__v and self.__v in the Base class's __init__ method to self._Base__v. These are different names bound to different values and are reflected as such. self.u is the same name in both cases and the value was bound in the Derrived class, and not re-bound in the Base class. James Thanks for the reply, James. Rereading the relevant section of the Tutorial: Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. http://docs.python.org/tut/node11.html#SECTION001160 I'm not sure how I came to think that names were mangled only with respect to calling code from outside class definitions. As I'd been confused, I naturally started thinking of ways to clarify the docs. But, I've come to think that the error was wholly mine. Thanks for the help, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzled about class attribute resolution and mangling
Brian van den Broek wrote: Hi all, I've the following code snippet that puzzles me: class Base(object): __v, u = Base v, Base u def __init__(self): print self.__v, self.u class Derived(Base): __v, u = Derived v, Derived u def __init__(self): print self.__v, self.u super(Derived, self).__init__() d = Derived() When run (Python 2.4.2, IDLE 1.1.2), it produces: Derived v Derived u Base v Derived u What I expected was that all four emitted strings would contain Derived. I conclude that there is something about the cluster of concepts at hand this hobbyist doesn't understand :-) I suspect that the problem is with my understanding of the name mangling mechanism, but then again, I'm the confused one. I'd thought the point of the mangling was to make it sufficiently difficult for client code to access the mangled name so as to constitute a strong recommendation to leave the name alone. But, since the access is all from within method code, I didn't expect any mangling issues here. Since d is a Derived, I expected any method of d trying to find d.__v to first check if there is a Derived.__v and only then pass to Base.__v. Obviously, that's not what's happening. So, is this behaviour entirely by design and my surprise entirely the product of misconception or is there an element of side effect of the mangling mechanism at issue? Or some other consideration altogether? Thanks and best, Brian vdB This is name mangling at work. Mangling turns self.__v in the Derrived class's __init__ method to self._Derrived__v and self.__v in the Base class's __init__ method to self._Base__v. These are different names bound to different values and are reflected as such. self.u is the same name in both cases and the value was bound in the Derrived class, and not re-bound in the Base class. James -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
Bengt Richter wrote: On Mon, 11 Jul 2005 22:10:33 -0400, Colin J. Williams [EMAIL PROTECTED] wrote: The snippet of code below gives the result which follows for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) 1: name[0]= name[0] + name[1].capitalize() print '2', name name[0]= name[0].capitalize() print '3', name 1 ['logical', 'or'] 2 ['logicalOr', 'or'] 3 ['Logicalor', 'or'] I was expecting that 3 would read ['LogicalOr', 'or'] If I replace the above code with: for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) 1: name[0]= name[0].capitalize() + name[1].capitalize() print '2', name else: name[0]= name[0].capitalize() print '3', name I get the desired result. If you walk through the results, you can see what happens to name[2] on output line 2: 'logicalOr'.capitalize() 'Logicalor' I.e., help(str.capitalize) Help on method_descriptor: capitalize(...) S.capitalize() - string Return a copy of the string S with only its first character capitalized. -- meaning all the rest lowercased, which changed your trailing 'Or' So, doing .capitalize on all the pieces from split('_') and then joining them: def doit(w): return ''.join([s.capitalize() for s in w.split('_')]) ... doit('logical_or') 'LogicalOr' doit('logical') 'Logical' doit('logical_or_something') 'LogicalOrSomething' doit('UP_aNd_down') 'UpAndDown' Regards, Bengt Richter Many thanks. I missed the implication that any upper case characters after the first are changed to lower case. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
Colin J. Williams wrote: The snippet of code below gives the result which follows for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) 1: name[0]= name[0] + name[1].capitalize() print '2', name name[0]= name[0].capitalize() print '3', name 1 ['logical', 'or'] 2 ['logicalOr', 'or'] 3 ['Logicalor', 'or'] I was expecting that 3 would read ['LogicalOr', 'or'] str.capitalize() changes the first character to be uppercase and all later characters to be lower case. It does not leave the later characters alone. In [1]: str.capitalize? Type: method_descriptor Base Class: type 'method_descriptor' String Form:method 'capitalize' of 'str' objects Namespace: Python builtin Docstring: S.capitalize() - string Return a copy of the string S with only its first character capitalized. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled
On Mon, 11 Jul 2005 22:10:33 -0400, Colin J. Williams [EMAIL PROTECTED] wrote: The snippet of code below gives the result which follows for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) 1: name[0]= name[0] + name[1].capitalize() print '2', name name[0]= name[0].capitalize() print '3', name 1 ['logical', 'or'] 2 ['logicalOr', 'or'] 3 ['Logicalor', 'or'] I was expecting that 3 would read ['LogicalOr', 'or'] If I replace the above code with: for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) 1: name[0]= name[0].capitalize() + name[1].capitalize() print '2', name else: name[0]= name[0].capitalize() print '3', name I get the desired result. If you walk through the results, you can see what happens to name[2] on output line 2: 'logicalOr'.capitalize() 'Logicalor' I.e., help(str.capitalize) Help on method_descriptor: capitalize(...) S.capitalize() - string Return a copy of the string S with only its first character capitalized. -- meaning all the rest lowercased, which changed your trailing 'Or' So, doing .capitalize on all the pieces from split('_') and then joining them: def doit(w): return ''.join([s.capitalize() for s in w.split('_')]) ... doit('logical_or') 'LogicalOr' doit('logical') 'Logical' doit('logical_or_something') 'LogicalOrSomething' doit('UP_aNd_down') 'UpAndDown' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list