Re: Possible to create a read-only complex object?
On 7/11/2010 12:51 PM, [email protected] wrote: I have a complex object with attributes that contain lists, sets, dictionaries, and other objects. The lists and dictionaries may themselves contain complex objects. I would like to provide a read-only version of this type of object for other developers to query for reporting. Is there a way to prevent other developers from changing the attributes of my complex and nested object? In researching this question, I have identified __setattr__ and __delattr__ as possible ways to prevent changes to simple attributes, but I don't believe these magic methods will prevent others from fiddling with attributes containing lists and dictionaries or the contents of these lists and dictionaries. Python was not really not developed for multi-developer projects whose members are willing to stomp on each others objects. Another idea I had was to create a wrapper object to proxy all access to the original object. Is there a generic reciepe for this type of wrapper? -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to create a read-only complex object?
On Mon, 12 Jul 2010 02:56:34 -0400, Terry Reedy wrote: > On 7/11/2010 12:51 PM, [email protected] wrote: >> I have a complex object with attributes that contain lists, sets, >> dictionaries, and other objects. The lists and dictionaries may >> themselves contain complex objects. >> I would like to provide a read-only version of this type of object for >> other developers to query for reporting. Is there a way to prevent >> other developers from changing the attributes of my complex and nested >> object? >> In researching this question, I have identified __setattr__ and >> __delattr__ as possible ways to prevent changes to simple attributes, >> but I don't believe these magic methods will prevent others from >> fiddling with attributes containing lists and dictionaries or the >> contents of these lists and dictionaries. > > Python was not really not developed for multi-developer projects whose > members are willing to stomp on each others objects. I like the idea of competition-driven development, where the code that survives best in the face of hostile developers gets used. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Netbeans plugin and Python 3
Hi, I never tried python3.0 with netbeans but I use python 2.6.5 with netbean 6.7.1 Here is how I managed to change from python 2.5 (netbeans default) to 2.6.5 1) From the tools-> plugins section install python plugin 2) Once plugin is installed just restart netbeans so that plugin is activated 3) After plugin is activated, you can edit default python version by tools-> python platform 4) It will open a configure window, where you can point python to newly installed 3.0 version. I hope that helps. Thanks, nitin On Fri, Jul 9, 2010 at 9:30 PM, wrote: > Send Python-list mailing list submissions to >[email protected] > > To subscribe or unsubscribe via the World Wide Web, visit >http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to >[email protected] > > You can reach the person managing the list at >[email protected] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > Today's Topics: > > 1. python instructor (Greg) > 2. Re: ipython problem in opening a file (Youngung Jeong) > 3. Netbeans plugin and Python 3 (Chrix) > 4. Re: python instructor (Ed Keith) > 5. Last day to submit your Surge 2010 CFP! (Jason Dixon) > 6. SqlAlchemy: remote connection on problem on mysql database (Massi) > 7. do (Robin) > 8. Re: Opinions please -- how big should a single module grow? > (Tomasz Rola) > 9. Re: Python -- floating point arithmetic (Aahz) > 10. Re: 'reload M' doesn't update 'from M inport *' (Aahz) > 11. Cpp + Python: static data dynamic initialization in *nix > shared lib? (Alf P. Steinbach /Usenet) > 12. Why there is no "setdefaultencoding" in sys module? (crow) > > > -- Forwarded message -- > From: Greg > To: [email protected] > Date: Fri, 9 Jul 2010 07:09:13 -0700 (PDT) > Subject: python instructor > We're looking for a first-rate python trainer to come to our > organization for a day or two. We are a small group of geospatial/ > remote sensing scientists whose research spans the gap between > environmental accounting/monitoring and policy and human interaction. > We have about 5-10 (or so) python users (and potential python users) > who could potentially apply new skills to several in-house projects. > The difficulty for the teacher would be covering breadth of experience > we have currently. > > Any thoughts or advice would be greatly appreciated. Thanks very > much, > > Greg > > > > -- Forwarded message -- > From: Youngung Jeong > To: Eli Bendersky > Date: Fri, 9 Jul 2010 23:27:08 +0900 > Subject: Re: ipython problem in opening a file > Thanks a lot! > > Youngung > > > On Fri, Jul 9, 2010 at 10:17 PM, Eli Bendersky wrote: > >> On Fri, Jul 9, 2010 at 16:07, Youngung Jeong >> wrote: >> > Thank you for your kindness. >> > I found you're right. It's running in that folder. >> > What should I do for making this work? >> > Could you please tell me a bit more... >> > >> > Youngung >> >> You can change the "current directory" ipython executes in, by either >> executing it directly (from the command line) in the directory of your >> choice, or calling the os.chdir function with the path of your choice. >> >> Eli >> > > > > -- Forwarded message -- > From: Chrix > To: [email protected] > Date: Fri, 9 Jul 2010 07:26:24 -0700 (PDT) > Subject: Netbeans plugin and Python 3 > Hi, > > Someone knows if Netbeans will support Python 3 language features? > Nowadays, I tried Netbeans 6.9 but it only supports Python 2.5 :( > And I'd like really to develop with Python 3. > > Thanks. > > > > -- Forwarded message -- > From: Ed Keith > To: [email protected], Greg > Date: Fri, 9 Jul 2010 07:49:05 -0700 (PDT) > Subject: Re: python instructor > Where are you located? > > -EdK > > Ed Keith > [email protected] > > Blog: edkeith.blogspot.com > > > --- On Fri, 7/9/10, Greg wrote: > > > From: Greg > > Subject: python instructor > > To: [email protected] > > Date: Friday, July 9, 2010, 10:09 AM > > We're looking for a first-rate python > > trainer to come to our > > organization for a day or two. We are a small group > > of geospatial/ > > remote sensing scientists whose research spans the gap > > between > > environmental accounting/monitoring and policy and human > > interaction. > > We have about 5-10 (or so) python users (and potential > > python users) > > who could potentially apply new skills to several in-house > > projects. > > The difficulty for the teacher would be covering breadth of > > experience > > we have currently. > > > > Any thoughts or advice would be greatly appreciated. > > Thanks very > > much, > > > > Greg > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > -- Forwarded message -- > From: Jason Dixon > To: [email protected] > Date: Fri, 9 Jul 2010 11
PIL Query
Hi I was using the PIL. I found it pretty useful. I was wondering if you could please let me know, whether I could change the image size. What I mean is if suppose I have 100 points having the same latitude and longitude, the point on the map appears (for instance as a red circle). My question to you is, can I change the radius of this circle? I was also trying to figure out where in the code I can change the location where the url is served from. So instead of serving the images form http://localhost/classic/4/4,5.png how do I change it to http://localhost/username/classic/4/4,5.png where username is taken from the database. & my last question is, is it possible that I just give the PIL the latitude,longitude and the no. of points having the same latitude and longitude[i.e. intensity], instead of repeating the lat & long coordinates. Your help will be greatly appreciated Thanks Ankit -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming Conventions, Where's the Convention Waldo?
On 12Jul2010 02:43, Steven D'Aprano wrote: | On Mon, 12 Jul 2010 02:40:07 +, Steven D'Aprano wrote: | > On Mon, 12 Jul 2010 01:31:14 +0100, Mark Lawrence wrote: | >> Well said Steven, or is it Stephen, or Stephan, or Stefen, or what? | > | > For some reason, when I answer the phone and say "Hello, Steven | > speaking?" I often get called Peter. | | Er, without the question mark. Ah, so you get differing results when you use the question mark? Phonetic punctuation; Victor Borge would be proud. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ A lot of people don't know the difference between a violin and a viola, so I'll tell you. A viola burns longer. - Victor Borge -- http://mail.python.org/mailman/listinfo/python-list
Numpy now supports Python3, Scipy to follow soon
Pardon me if this has already been mentioned, but I didn't see it, and this is big big news. The latest release of numpy now supports Python 2.x and 3.x out of a single code base, and Scipy is predicted to follow soon. http://www.mail-archive.com/[email protected]/msg26524.html If I can take the liberty of quoting Pauli Virtanen: An important point is that supporting Python 3 and Python 2 in the same code base can be done, and it is not very difficult either. It is also much preferable from the maintenance POV to creating separate branches for Python 2 and 3. Well done to all those who contributed to the effort! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Design questions for C++ support for Python extensions (cppy)
Hi.
With the current cppy code the Python 3.1.1 doc's spam example extension module
looks like this (actual working code):
#include
#include
using namespace progrock;
namespace {
class Spam: public cppy::Module
{
public:
Spam(): cppy::Module( L"spam", L"blåbærsyltetøy er blått" )
{}
PyObject* system( PyObject* args )
{
const char *command;
if( !PyArg_ParseTuple( args, "s", &command ) )
{
return NULL;
}
int const sts = ::system( command );
return Py_BuildValue( "i", sts );
}
};
}// namespace
CPPY_MODULE_CROUTINE( Spam, system, L"Execute a shell command" )
PyMODINIT_FUNC PyInit_spam()
{
return cppy::safeInit< Spam >();
}
Issues:
1. Wide string literals OK?
The basic Python API often requires UTF-8 encoded byte strings. With C++
source code encoded using e.g. Windows ANSI Western, string literals with
national characters such as Norwegian ÆØÅ then become gobbledegook or cause
outright failure. I balanced the hypothetical need for string literals with
national characters, versus perceived unnaturalness of wide string literals
for *nix developers, in favor of the former, i.e. L"wide string literals".
Related issue here: in Windows MinGW g++ can not compile utf-8 encoded
source with BOM, while MSVC requires a BOM in order to detect the encoding.
Is L"this" an acceptable decision if you were to use something like cppy?
2. Exception translation OK?
The code within the 'system' member routine could conceivably be reduced to
a single short line by adding some C++ support, but that would require use
of exceptions to report errors. Translating C++ exceptions to Python
exceptions does however add some overhead to every Python -> C++ call.
Currently I do this only for the module initialization code, but should it
be done for every exported method? Or perhaps as user choice? Benefit of
translation e.g. reducing 'system' above to sweet single line. Cost is
setup of try-block (negligible) and exception translation (inefficient).
3. Some unsafety OK?
In 'PyInit_spam' there may be a window of opportunity for client code to
Mess Things Up. Within the cppy::safeInit the C++ module object is created
and creates a Python module object, and if anything fails then the C++ side
frees the Python object. And after PyInit_spam has returned to Python the
cleanup responsibility resides with the Python interpreter: freeing the
Python module object causes the C++ object to be destroyed. But if say the
client code's equivalent of 'PyInit_spam' calls cppy::safeInit and just
discards the result and returns 0 (say) to Python, then it seems to not be
documented whether Python will free the Python module, i.e. possible leak.
4. Threading?
Is it necessary to make singletons/statics thread safe? Or does Python
ensure that no other threads execute while PyInit_spam is called? Can it
be called simultaneously by two or more threads?
5. Reload of interpreter?
My impression from the documentation is that finalization and reinit of the
interpreter is something that an application shouldn't really do, and that
an extension developer need not worry about that happening. Is it so?
Cheers,
- Alf
--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Possible to create a read-only complex object?
On Mon, Jul 12, 2010 at 12:45 AM, Steven D'Aprano wrote: > On Mon, 12 Jul 2010 02:56:34 -0400, Terry Reedy wrote: >> On 7/11/2010 12:51 PM, [email protected] wrote: >>> I have a complex object with attributes that contain lists, sets, >>> dictionaries, and other objects. The lists and dictionaries may >>> themselves contain complex objects. >>> I would like to provide a read-only version of this type of object for >>> other developers to query for reporting. Is there a way to prevent >>> other developers from changing the attributes of my complex and nested >>> object? >>> In researching this question, I have identified __setattr__ and >>> __delattr__ as possible ways to prevent changes to simple attributes, >>> but I don't believe these magic methods will prevent others from >>> fiddling with attributes containing lists and dictionaries or the >>> contents of these lists and dictionaries. >> >> Python was not really not developed for multi-developer projects whose >> members are willing to stomp on each others objects. > > I like the idea of competition-driven development, where the code that > survives best in the face of hostile developers gets used. http://en.wikipedia.org/wiki/Defensive_programming Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Netbeans plugin and Python 3
On Fri, Jul 9, 2010 at 9:27 AM, Nitin Pawar wrote: > Hi, > I never tried python3.0 with netbeans but I use python 2.6.5 with netbean > 6.7.1 > Here is how I managed to change from python 2.5 (netbeans default) to 2.6.5 > 1) From the tools-> plugins section install python plugin > 2) Once plugin is installed just restart netbeans so that plugin is > activated > 3) After plugin is activated, you can edit default python version by tools-> > python platform > 4) It will open a configure window, where you can point python to newly > installed 3.0 version. > I hope that helps. > Thanks, > nitin > > On Fri, Jul 9, 2010 at 9:30 PM, wrote: >> >> Send Python-list mailing list submissions to >> [email protected] >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/python-list >> or, via email, send a message with subject or body 'help' to >> [email protected] >> >> You can reach the person managing the list at >> [email protected] >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Python-list digest..." >> >> Today's Topics: >> >> 1. python instructor (Greg) >> 2. Re: ipython problem in opening a file (Youngung Jeong) >> 3. Netbeans plugin and Python 3 (Chrix) >> 4. Re: python instructor (Ed Keith) >> 5. Last day to submit your Surge 2010 CFP! (Jason Dixon) >> 6. SqlAlchemy: remote connection on problem on mysql database (Massi) >> 7. do (Robin) >> 8. Re: Opinions please -- how big should a single module grow? >> (Tomasz Rola) >> 9. Re: Python -- floating point arithmetic (Aahz) >> 10. Re: 'reload M' doesn't update 'from M inport *' (Aahz) >> 11. Cpp + Python: static data dynamic initialization in *nix >> shared lib? (Alf P. Steinbach /Usenet) >> 12. Why there is no "setdefaultencoding" in sys module? (crow) Netiquette note: Please don't include the entire digest in future posts to the mailinglist. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy now supports Python3, Scipy to follow soon
On 12 July 2010 10:05, Steven D'Aprano wrote: > Pardon me if this has already been mentioned, but I didn't see it, and > this is big big news. > I haven't heard it yet, this is great news! Almar -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to create a read-only complex object?
On Mon, 12 Jul 2010 01:11:53 -0700, Chris Rebert wrote: > On Mon, Jul 12, 2010 at 12:45 AM, Steven D'Aprano > wrote: >> On Mon, 12 Jul 2010 02:56:34 -0400, Terry Reedy wrote: >>> On 7/11/2010 12:51 PM, [email protected] wrote: I have a complex object with attributes that contain lists, sets, dictionaries, and other objects. The lists and dictionaries may themselves contain complex objects. I would like to provide a read-only version of this type of object for other developers to query for reporting. Is there a way to prevent other developers from changing the attributes of my complex and nested object? In researching this question, I have identified __setattr__ and __delattr__ as possible ways to prevent changes to simple attributes, but I don't believe these magic methods will prevent others from fiddling with attributes containing lists and dictionaries or the contents of these lists and dictionaries. >>> >>> Python was not really not developed for multi-developer projects whose >>> members are willing to stomp on each others objects. >> >> I like the idea of competition-driven development, where the code that >> survives best in the face of hostile developers gets used. > > http://en.wikipedia.org/wiki/Defensive_programming Meh, defensive programming is designed to deal with bugs and hostile outsiders. I mean writing your functions and classes to deal with actively hostile coding *partners* who are trying to destroy your class so their class will survive to fight another day... There's probably a Dilbert cartoon about it. I'm not serious of course, if the members of your project are trying to screw your code, you're in trouble. I just like the idea of competition- driven development being the next buzzword, for when agile, test-driven, or pair-programming development is no longer enough. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
"MRAB" wrote in message news:[email protected]... Alf P. Steinbach /Usenet wrote: def foo(): print( blah ) blah = "this is both an assignment and a declaration causing it to exist" foo() Clearly when the exception is raised, referring to the variable, the variable exists. How about this: >>> def foo(): print("Before:", locals()) x = 0 print("After:", locals()) >>> foo() Before: {} After: {'x': 0} That's interesting. So in Python, you can't tell what local variables a function has just by looking at it's code: def foo(day): if day=="Tuesday": x=0 print ("Locals:",locals()) #foo("Monday") Does foo() have 1 or 2 locals? That might explain some of the difficulties of getting Python implementations up to speed. -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to create a read-only complex object?
On Mon, Jul 12, 2010 at 3:45 AM, Steven D'Aprano wrote: > On Mon, 12 Jul 2010 02:56:34 -0400, Terry Reedy wrote: > >> On 7/11/2010 12:51 PM, [email protected] wrote: >>> I have a complex object with attributes that contain lists, sets, >>> dictionaries, and other objects. The lists and dictionaries may >>> themselves contain complex objects. >>> I would like to provide a read-only version of this type of object for >>> other developers to query for reporting. Is there a way to prevent >>> other developers from changing the attributes of my complex and nested >>> object? >>> In researching this question, I have identified __setattr__ and >>> __delattr__ as possible ways to prevent changes to simple attributes, >>> but I don't believe these magic methods will prevent others from >>> fiddling with attributes containing lists and dictionaries or the >>> contents of these lists and dictionaries. >> >> Python was not really not developed for multi-developer projects whose >> members are willing to stomp on each others objects. > > I like the idea of competition-driven development, where the code that > survives best in the face of hostile developers gets used. You jest, but I've actually done this. The goal was to test security awareness among developers- we formed two tiger teams, one to develop code and one to exploit it, and had one member of the developer group as a saboteur. His goal was to put in the largest possible vulnerability without getting caught, while the others wanted to produce the most secure code they could that met spec. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: 'reload M' doesn't update 'from M inport *'
Aahz wrote: In article , Jean-Michel Pichavant wrote: PS : You're misusing the del statement. It does not remove any object >from mmory, however, it removes the reference to it, the object is still in memory. They are very few cases where del is usefull in python, so try to avoid using it as well. The first two sentences are true; the last sentence is completely wrong. I've got lots of code using del, and it's a critically useful element of dictionary manipulation. Can you please give a short example ? I'm not challenging though, just curious. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: 'reload M' doesn't update 'from M inport *'
Hi, Don't use reload, this is nothing but a trap, espacially if your using it to update your objects with the code you are writting. JM I've found "reload" very usable for development in IDLE. IDLE memorizes my input, and the variables I assign output to. If restart IDLE I lose it all and start over. That is an awfully awkward alternative to "reload", an alternative I wouldn't consider. I found "reload" tricky with several modules, because all dependencies need to be updated and which way they go isn't always obvious. Reloading all modules in the right order works for me. The reload commands come up with Alt-P as long, precisely, as I don't restart IDLE. Instead of writing your test code in the IDLE shell, write it into a file, an run this file in IDLE (from the IDLE file edit window hit F5). That way restarting from the begining is costless. If you insist on using reload, then you've already been given helpful answers, understanding the import model is always a good thing anyway :) JM -- http://mail.python.org/mailman/listinfo/python-list
round issue
A client wants to know why his db number -9.85 gets displayed by some simple code as -9.8 I looked at the number and see that >>> -9.85 -9.8496 ie I expect simple rounding to produce the observed result and indeed >>> '%.1f' % -9.85 '-9.8' however, when I use round I get an unexpected result ie >>> round(-9.85,1) -9.9004 according to its definition round(x[, n])¶ Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0). so looking at the absolute differences I see >>> abs(-9.9 - -9.85) 0.050711 >>> abs(-9.8 - -9.85) 0.048934 ie the -9.8 value appears closer and at least to a primitive test >>> abs(-9.9 - -9.85) > abs(-9.8 - -9.85) True the distance from the -9.9 result is larger, however, that may be because the model numbers for -9.8 & -9.9 differ in distance from the true 10**-n values eg >>> -9.9 -9.9004 >>> -9.8 -9.8007 What value should round(-9.85,1) return? Is the result explainable in python (ie without resort to the internal FP representations etc etc)? -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Python conference and user group statistics
Hello, I am currently working on a Python Software Foundation (PSF) project to create marketing material for Python with the aim of providing this to Python conferences and user groups. In order to come up with reasonable figures for the number of brochures and flyers to print, I'd like to get a rough idea about the number of attendees of the various Python conferences and user group meetings. It would be great, if you could report the approx. number of attendees coming to the events and the frequency with which you hold the conferences/meetings. I'm also interested in whether English as language of the marketing material would suffice or whether having the material in other languages would result in better acceptance among your attendees. These are the list of conferences and user groups I'm currently using as basis for the survey: http://www.python.org/community/workshops/ http://wiki.python.org/moin/LocalUserGroups Please reply either in private email or CC to my email address. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 12 2010) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2010-07-19: EuroPython 2010, Birmingham, UK 6 days to go ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
"Alf P. Steinbach /Usenet" wrote: > * sturlamolden, on 12.07.2010 06:52: >> On 11 Jul, 21:37, "Alf P. Steinbach /Usenet"> [email protected]> wrote: >> >>> Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. >>> Python works like Java in this respect, that's all; neither Java nor >>> Python support 'swap'. >> >> x,y = y,x >> > > We're talking about defining a 'swap' routine that works on variables. > > Since Java/Python doesn't support pass by reference of variables it's > not possible in these languages, i.e., you missed the point, or made a > joke. :-) > I think talking about a swap function is confusing the issue somewhat: you don't need to define a swap function in Python because the language supports the functionality directly, but that is just hiding the wider question of what you do in Python instead of using reference or in/out arguments. The simple answer is that Python makes it easy to return more than result from a function, so for every 'out' parameter just return one more result, and for a 'ref' parameter just bind that result back to the same name as you passed in. Note that this gives you more flexibility than languages with 'out' or 'ref' parameters as the caller of the function can decide whether to overwrite the original name or create a new one. A literal implementation of 'swap' in Python is possible but pretty pointless: def swap(a, b): return b, a ... x, y = swap(x, y) but it makes a lot of sense when you move to functions that actually do something useful: scheme, netloc, path, parms, query, fragment = urlparse(url) and there's even a convention for ignoring results we don't care about: head, _, tail = line.partition(':') -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't python's list append() method return the list itself?
On Jul 12, 5:30 am, News123 wrote: > dhruvbird wrote: > > > On a side note, is there any other way to append to a list using > > slices (apart from the one below): > > x[len(x):len(x)] = [item to append] > > dy you mean > x.extend([1,2,3]) No, I meant x.append(4) Except that I want to accomplish it using slices. (I can do it as x[lex(x):] = [item_to_append] but is there any other way?) Regards, -Dhruv. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Mon, 12 Jul 2010 09:48:04 +0100, bart.c wrote:
> That's interesting. So in Python, you can't tell what local variables a
> function has just by looking at it's code:
In the presence of "exec", you can't really tell *anything*.
>>> def f(s):
... exec s
... print locals()
...
>>> f("x = 2;y = None")
{'y': None, 'x': 2, 's': 'x = 2;y = None'}
> def foo(day):
> if day=="Tuesday":
> x=0
> print ("Locals:",locals())
>
> #foo("Monday")
>
> Does foo() have 1 or 2 locals?
That's easy for CPython: it prepares two slots for variables, but only
creates one:
>>> foo("Monday")
('Locals:', {'day': 'Monday'})
>>> foo.func_code.co_varnames
('day', 'x')
>>> foo.func_code.co_nlocals
2
So, the question is, is x a local variable or not? It's not in locals,
but the function clearly knows that it could be.
> That might explain some of the
> difficulties of getting Python implementations up to speed.
I'm not quite sure why you say that.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
Steven D'Aprano wrote: My complaint (an oddly enough the title of this thread!) concerns the fact that Python treats 0 as False and every integer above and below 0 as True. Which is another example of how *some* aspects of Python support bad coding styles. Yes, Python does support bad coding styles. The treatment of 0 as a false value is not one of them though. Well, actually some people might think otherwise. While I disagree with the OP flaming style, one could argue that muting an integer into a boolean makes no sense (I'm one of them). You can still do it, but there is no "right" way to do it. You can decide that everything else than 0 is True, but you could also pickup the integer 3 as false value, it would work as well since it makes no sense. This is just an arbitrary definition. Where the OP is fooling himself, is that you can't state that bool-ing an integer makes no sense and state the line after that 0 *should* | *has to* return True. I personally can live with 0 == False (with all due respect to our C-coding ancestors :) ), however as one of my personal coding rule I avoid using it. I prefere to explicitly write what I want to test: if myInt <> 0: or if myInt is not None: etc... That way I do not rely on a arbitrary int-to-bool mutation. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming Conventions, Where's the Convention Waldo?
rantingrick wrote: On Jul 11, 3:03 am, "Günther Dietrich" wrote: So, it is not a disadvantage that the functions you listed above are named in this way. In the contrary, it is an advantage, as it keeps newcomers from using stupid variable names. "int" for an Integer is stupid? "list" for a List is stupid? "str" for a String is stupid? What am i missing? def func154(): int32 = 24 list18 = [int32, 14] str14 = "" for int89 in list18: if int89 == int32 or int89 == 88: str14 = "I am missing everything" if str14: print str14 >>> func154() >>> "I am missing everything" JM -- http://mail.python.org/mailman/listinfo/python-list
Re: round issue
On Jul 12, 10:52 am, Robin Becker wrote:
> What value should round(-9.85,1) return? Is the result explainable in python
> (ie
> without resort to the internal FP representations etc etc)?
As you observe, the closest float to -9.85 is actually just a little
smaller (i.e., closer to 0) than -9.85:
Python 2.7 (r27:82500, Jul 11 2010, 22:38:53)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> decimal.Decimal(-9.85)
Decimal('-9.8496447286321199499070644378662109375')
So you're right: round(-9.85, 1) *should* return -9.8. The 2.x (for x
<= 6) version of round is a bit deficient in that respect.
Internally, it's doing the obvious thing: namely, multiplying by
10.0, rounding to the nearest integer, then dividing by 10.0. The
problem is that this not-quite-9.85 value, when multiplied by 10,
becomes (as a result of rounding error) *exactly* 98.5, which then
gets rounded *up* to 99 instead of down to 98.
This is fixed in Python 2.7, and in Python 3.x. (The code that was
introduced for the new short float repr made it easy to fix.)
That said, if your client really *means* -9.85 (rather than some
binary approximation to it), and wants it to round in a predictable
manner, the right way to fix this would be to use Decimal instead of
float to represent the number. That way, you can also specify what
rounding mode you want (instead of relying on the default round-half-
away-from-zero in 2.x or round-half-to-even in 3.x.)
>>> decimal.Decimal('-9.85').quantize(decimal.Decimal('0.1'),
>>> rounding=decimal.ROUND_HALF_UP)
Decimal('-9.9')
>>> decimal.Decimal('-9.85').quantize(decimal.Decimal('0.1'),
>>> rounding=decimal.ROUND_HALF_EVEN)
Decimal('-9.8')
--
Mark
--
http://mail.python.org/mailman/listinfo/python-list
Re: Only one forum app in Python?
On Sat, 10 Jul 2010 18:37:00 +0200, Bruno Desthuilliers wrote: >There are almost a dozen of Python "forum apps" for Django alone, and >Python is known as "the language with more web frameworks than keywords". Thanks for the tip. I'll head that way. -- http://mail.python.org/mailman/listinfo/python-list
Re: grailbrowser now running under python 2.5 (probably above too)
On Jul 12, 1:21 am, rantingrick wrote: > On Jul 11, 5:28 pm,Fuzzyman wrote: > > > But why hijack someone else's announcement to do that? Congratulations > > alone would have been great. However good your intentions your message > > came across as "but it would really have been better if you had been > > doing something else instead...". > > Micheal i think you're just simply projecting some inner feelings on > to my post resulting in a complete mis-understanding. And i *did not* > say the project was useless, on the contrary i am very happy the OP > resurrected this lost script. I only suggested a similar project that > the OP *may* find to be interesting. Maybe not, but lets leave the > decision for the OP, Ok. Plenty of people have told you in multiple threads how you come across. Eventually you have to realise that they aren't *all* projecting... :-) Michael -- http://www.voidspace.org.uk/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Only one forum app in Python?
On Mon, Jul 12, 2010 at 8:49 PM, Gilles Ganault wrote: >>There are almost a dozen of Python "forum apps" for Django alone, and >>Python is known as "the language with more web frameworks than keywords". Speaking of frameworks and python forums, sahriswiki 91) is not a forum, but it's goals are to have a best-of-mix of features from blogging, wiki and cms engines. cheers James 1. http://sahriswiki.org/ -- -- James Mills -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't python's list append() method return the list itself?
dhruvbird writes: > No, I meant x.append(4) > Except that I want to accomplish it using slices. > > (I can do it as x[lex(x):] = [item_to_append] but is there any other > way?) It seems that you've found a way to do so, so why do you need another way? Are you after elegance? Efficiency? Brevity? Here are some other ways to express the same, and all use slices in some way: x[slice(len(x), None)] = [item_to_append] x.__setitem__(slice(len(x), None), [item_to_append]) x.__setslice__(len(x), len(x), [item_to_append]) ...but I have no idea why any of them would make any more sense than x[len(x):] = [item_to_append]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
"Steven D'Aprano" wrote in message news:[email protected]... On Mon, 12 Jul 2010 09:48:04 +0100, bart.c wrote: That's interesting. So in Python, you can't tell what local variables a function has just by looking at it's code: def foo(day): if day=="Tuesday": x=0 print ("Locals:",locals()) #foo("Monday") Does foo() have 1 or 2 locals? That's easy for CPython: it prepares two slots for variables, but only creates one: foo("Monday") ('Locals:', {'day': 'Monday'}) foo.func_code.co_varnames ('day', 'x') foo.func_code.co_nlocals 2 So, the question is, is x a local variable or not? It's not in locals, but the function clearly knows that it could be. So Alf P.S. could be right; x exists, but Python pretends it doesn't until it's assigned to. That might explain some of the difficulties of getting Python implementations up to speed. I'm not quite sure why you say that. Only that an implementation might be obliged to keep these various tables updated during function execution, instead of just at entry and exit. -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't python's list append() method return the list itself?
Stephen: I'm not adverse to being able to do that, but the number of times that I've wanted to do that is greatly outweighed by the number of times I've had to pass a function "(somestring,)" or call "if isinstance(foo, basestring): ..." to avoid producing a bug. The more abstract and adaptive the code you are writing, the more annoying it gets - you end up with a rats nest of string instance checks and strings wrapped in tuples. Looking at my code, I don't have a lot of use cases for string slicing or iterating character by character. Most of the time I use the string methods, they're faster and (IMO) clearer - lower, index/rindex, find, etc. One use case that I avoid is extracting substrings, by slicing out the results of rfind. There's a good case for this but I feel it's brittle so I usually just jump to regular expressions (and it could be performed equally well with a substring method). That doesn't mean I don't think it's useful, just that as it stands the default language behavior is bug producing, and in my opinion people would be equally well served with an as_list method on strings that makes the behavior explicit. Chris: Let's not run around questioning people's math skills, that's actually my area of expertise, and it's impolite besides :) While having all([]) return True from a formal standpoint "makes sense" it typically reduces people to writing "if all(something) and something:", because feeding an iterable that has been filtered in some way (and thus has a range between 0 and n, where n is the length of the original iterable) is an incredibly common use case. In fact, I'm going to go out on a limb here and say there are a lot of bugs floating around that haven't been caught because the code author used all() under the assumption that it would be passed a non-empty list. -- http://mail.python.org/mailman/listinfo/python-list
iptcinfo: Can not import: Newbie not really knowing what he is doing
My Code
`import os
from PIL import Image
from iptcinfo import IPTCInfo
info = IPTCInfo('test.jpg')
print info.keywords, info.supplementalCategories, info.contacts
caption = info.data['caption/abstract']
print caption`
running Win XP SP3
I get the message
No module: iptcinfo
I have downloaded iptcinfo and placed it in python27\Lib\site-packages
\iptcinfo
I guessed that was the right place, because that is where PIL ended
up, but that had a fancy installer with it.
As you will appreciate, I am very much an amateur in all this. I can
code a bit of python, but where everything goes and links is a
complete mystery. All I want is to write a quick script which
extracts the Caption field from a directory of JPEGS. I get the
filenames and the dimensions with PIL, but I need IPTCinfo to get at
the Caption field.
If anyone can throw any light on what I need to do or which stupid
mistake I have made, I would be most grateful.
Richard
--
http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
On 2010-07-09, Les Schaffer wrote: > i have been asked to guarantee that a proposed Python application will > run continuously under MS Windows for two months time. And i am looking ^^ IMO, that's going to be your main problem. -- Grant Edwards grant.b.edwardsYow! PIZZA!! at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On 2010-07-11, Thomas Jollans wrote: > On 07/11/2010 08:45 PM, wheres pythonmonks wrote: >> On #3: Sorry this is confusing, but I was browsing some struct array >> code from numpy, in which one of the columns contained strings, but >> the type information, supplied in numpy.array's dtype argument, >> specified the type as a an "object" not a string. A string is an object. >> Just wondering why one would do that. > > No expert on numpy, but maybe storing object references is cheaper than > storing strings here ? Strings are objects. IIRC, numpy has special homogeneous array types to hold certain scalar values: byte, int, float, complex. Those special array types allow for very efficient storage and operations. If you want an array of any other type, or a heterogeneous array, then you use an array of objects and then you can put anything into the array (including strings). -- Grant Edwards grant.b.edwardsYow! The PINK SOCKS were at ORIGINALLY from 1952!! gmail.comBut they went to MARS around 1953!! -- http://mail.python.org/mailman/listinfo/python-list
ValueError: invalid literal for float(): -1.#IND (pickle.py)
Hello together, python: 2.5.1 palttform: winXP I'm using pickle.dump and pickle.load with data that is created in a wrapped (boost.python) piece of C++ code. pickle.dump works fine. pickle.load creates the following exception: [...] data = pickle.load(input) File "C:\Python25\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python25\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python25\lib\pickle.py", line 954, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): -1.#IND - I'm not sure what -1.#IND means. Can somebody assist? - As pickle write the data I'm a bit confused, that is can't be unpickled it. Is that a bug or a feature? BTW: I'm tied to version 2.5 of python Thank and regards Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: invalid literal for float(): -1.#IND (pickle.py)
On 2010-07-12, Alexander Eisenhuth wrote: > python: 2.5.1 > palttform: winXP > > I'm using pickle.dump and pickle.load with data that is created in a > wrapped (boost.python) piece of C++ code. pickle.dump works fine. > pickle.load creates the following exception: > > [...] > data = pickle.load(input) >File "C:\Python25\lib\pickle.py", line 1370, in load > return Unpickler(file).load() >File "C:\Python25\lib\pickle.py", line 858, in load > dispatch[key](self) >File "C:\Python25\lib\pickle.py", line 954, in load_float > self.append(float(self.readline()[:-1])) > ValueError: invalid literal for float(): -1.#IND > > - I'm not sure what -1.#IND means. That's an infinity. > Can somebody assist? In Python 2.x, pickle doesn't handle infinities and NaNs. > - As pickle write the data I'm a bit confused, that is can't be > unpickled it. Is that a bug or a feature? IMO, it's a bug. It's been fixed in 3.x. > BTW: I'm tied to version 2.5 of python If you want to pickle floating point data that includes infinities and NaNs, you need to write your own handler for floating point values. When pickling you need to check for infinities and NaNs and output some defined strings. When unpickling, you need to check for those strings and generate infinities and NaNs as appropriate. The CPython 2.x version of pickle just uses the underlying C library routines to print and parse floating point values. If those libraries are broken in the way that they represent infinity and NaN, then pickle is broken in the same manner. Windows standard libraries are broken. When formatting floating point values, it produces strings that it can't parse as input. IIRC, Linux works better -- but if you want something that you know is going to work (and work cross-platform), then you need to write your own floating point pickle/unpickle methods, and hook them into the pickle module. -- Grant Edwards grant.b.edwardsYow! Uh-oh!! I'm having at TOO MUCH FUN!! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: invalid literal for float(): -1.#IND (pickle.py)
On 2010-07-12, Grant Edwards wrote: > On 2010-07-12, Alexander Eisenhuth wrote: > >> python: 2.5.1 >> palttform: winXP >> >> I'm using pickle.dump and pickle.load with data that is created in a >> wrapped (boost.python) piece of C++ code. pickle.dump works fine. >> pickle.load creates the following exception: >> >> [...] >> data = pickle.load(input) >>File "C:\Python25\lib\pickle.py", line 1370, in load >> return Unpickler(file).load() >>File "C:\Python25\lib\pickle.py", line 858, in load >> dispatch[key](self) >>File "C:\Python25\lib\pickle.py", line 954, in load_float >> self.append(float(self.readline()[:-1])) >> ValueError: invalid literal for float(): -1.#IND >> >> - I'm not sure what -1.#IND means. > > That's an infinity. Oops, I just noticed that I misread that. 1.#INF is an infinity, 1.#IND is an "indefinite", or what everybody outside of Microsoft calls a NaN (Not-a-Number). -- Grant Edwards grant.b.edwardsYow! ONE LIFE TO LIVE for at ALL MY CHILDREN in ANOTHER gmail.comWORLD all THE DAYS OF OUR LIVES. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On 12 Jul, 07:51, "Alf P. Steinbach /Usenet" wrote: > We're talking about defining a 'swap' routine that works on variables. I did not miss the point. One cannot make a swap function that rebinds its arguments in the calling stack frame. But a swap function can swap values, given that the type is not immutable: def swap(a,b): a[0],b[0] = b[0],a[0] >>> a,b = [1],[2] >>> swap(a,b) >>> print a,b [2] [1] -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: invalid literal for float(): -1.#IND (pickle.py)
Alexander Eisenhuth stacom-software.de> writes: >File "C:\Python25\lib\pickle.py", line 954, in load_float > self.append(float(self.readline()[:-1])) > ValueError: invalid literal for float(): -1.#IND > > - I'm not sure what -1.#IND means. Can somebody assist? It's the Windows way of representing a NaN (not a number). A NaN is typically what you get when you try to perform an invalid floating-point operation, like taking the square root of a negative number, or dividing 0.0 by 0.0. Some people also use NaNs to represent uninitialized values, or as placeholders for missing data. > - As pickle write the data I'm a bit confused, that is can't > be unpickled it. Is that a bug or a feature? Well, it's certainly not ideal. It shouldn't be a problem in Python 2.6 or 2.7, though; unfortunately, Python 2.5 is no longer receiving bugfixes, so it's not going to change there. > BTW: I'm tied to version 2.5 of python Have you tried using pickle protocol 1 or 2, instead of pickle protocol 0? That may well solve your problem. (Those protocols write out the binary form of a float directly, instead of reading and writing a string representation.) -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: iptcinfo: Can not import: Newbie not really knowing what he is doing
Hi Richard! I have downloaded iptcinfo and placed it in python27\Lib\site-packages \iptcinfo I guessed that was the right place, because that is where PIL ended up, but that had a fancy installer with it. You did place it in the right path, but the "fancy installer" does one more thing, it registers the package into the python-path, so python can get to it. I've long switched from windows unfortunately and can't remember the way it does this though, so you can do it manually. Have some good news though: I looked in the IPTCinfo package and it does indeed include a setup.py, which is a standard way of installing python packages. All you need to do is unpack the package to any folder and run setup.py install from that folder, which should take care of everything for you. Some documentation on installing packages for you to read: http://docs.python.org/install/ Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: round issue
On 07/12/2010 02:52 AM, Robin Becker wrote: A client wants to know why his db number -9.85 gets displayed by some simple code as -9.8 I looked at the number and see that >>> -9.85 -9.8496 ie I expect simple rounding to produce the observed result and indeed >>> '%.1f' % -9.85 '-9.8' however, when I use round I get an unexpected result ie >>> round(-9.85,1) -9.9004 according to its definition round(x[, n])¶ Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0). so looking at the absolute differences I see >>> abs(-9.9 - -9.85) 0.050711 >>> abs(-9.8 - -9.85) 0.048934 Do you *seriously* need to ask a computer if -9.85 is half-way between -9.9 and -9.8. Just look at the numbers man! Of course it's equally close to both, so rounding to -9.9 is correct according to the definition. Do you actually *believe* that -9.9 - -9.85 = 0.050711. Of course you know it's really 0.05. All you've done here is demonstrate the fallible nature of (the last several digits of) floating point arithmetic on a computer. Don't let that distract you from using your common sense. Gary Herron ie the -9.8 value appears closer and at least to a primitive test >>> abs(-9.9 - -9.85) > abs(-9.8 - -9.85) True the distance from the -9.9 result is larger, however, that may be because the model numbers for -9.8 & -9.9 differ in distance from the true 10**-n values eg >>> -9.9 -9.9004 >>> -9.8 -9.8007 What value should round(-9.85,1) return? Is the result explainable in python (ie without resort to the internal FP representations etc etc)? -- http://mail.python.org/mailman/listinfo/python-list
Re: grailbrowser now running under python 2.5 (probably above too)
On 07/12/2010 01:44 AM, rantingrick wrote: > On Jul 11, 11:31 am, Thomas Jollans wrote: >> On 07/11/2010 07:44 AM, rantingrick wrote: > >>> Congratulations on this effort Luke. However you know what project i >>> would really like to see the community get around? ...dramatic pause >>> here... a cross platform Python file browser! >> >> Cross platform file manager. Hmm. Does "cross platform" involve UNIX and >> something that isn't UNIX, say, Windows? >> Erm, no. No, no, no. It won't work... trying to >> support both UNIX and Windows is NOT a good idea. > > Why is that a bad idea, Python does it all the time? Many software so > it all the time. This sounds like more fear than anything. Python is not a file manager. > > If you attempt to be full-featured, keeping it in one >> code base, let alone in one user interface, is destined to be a >> nightmare and induce suicides. > > Thats False! > >> The above might have been very slightly exaggerated. > > Thats True! > -- http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
On 7/12/2010 7:19 AM, Grant Edwards wrote: On 2010-07-09, Les Schaffer wrote: i have been asked to guarantee that a proposed Python application will run continuously under MS Windows for two months time. And i am looking ^^ IMO, that's going to be your main problem. If you're doing a real-time job, run a real-time OS. QNX, a real-time variant of Linux, Windows CE, Windows Embedded, LynxOS, etc. There's too much background junk going on in a consumer OS today. Yesterday, I was running a CNC plasma cutter that's controlled by Windows XP. This is a machine that moves around a plasma torch that cuts thick steel plate. A "New Java update is available" window popped up while I was working. Not good. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Node based architecture
Hi, I am planning to build a generic node based framework using python. I would start with a simple image editing application. I hope that experienced users understands what am I trying to say here. In simple words: LoaderNode : Load Image from disk OperatorNode : Performs a specific task on data and spit output(data) OutputNode : Get the data from OperatorNode(output) and writes image to disk. Graph : A collection Nodes that are inter connected. The question is how to process graph? Here is a simple representation: class Integer(object): """ A simple integer node. """ def __init__(self, value=0): self.value = value def output(self): return self.value class OperatorAdd(object): """ A simple operator node """ def __init__(self, integerInst1=None, integerInst2=None): self.a = integerInst1.output() self.b = integerInst2.output() def compute(self): return Integer(self.a + self.b) def output(self): return self.compute() "Integer" is data node and "OperatorAdd" is a compute node. Imagine I have created two integer nodes and their output is going to "OperatorNode". One way to solve is to represent every node using a string and then you can write these series of string which actually is a python code that you can execute and get the result. Example: compute = """ i1 = Integer(2) i2 = Integer(3) i3 = OperatorAdd(i1, i2).output() """ Now you can execute "compute" variable using exec(compute) or something like that. This would do the job but I would like to know the opinion of more experienced users. One advantage of above mentioned string method is that it can be saved to disk and later you can load/compute it again. Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* sturlamolden, on 12.07.2010 16:59: On 12 Jul, 07:51, "Alf P. Steinbach /Usenet" wrote: We're talking about defining a 'swap' routine that works on variables. I did not miss the point. One cannot make a swap function that rebinds its arguments in the calling stack frame. But a swap function can swap values, given that the type is not immutable: def swap(a,b): a[0],b[0] = b[0],a[0] a,b = [1],[2] swap(a,b) print a,b [2] [1] OK, that's missing the point. I thought you were joking. Cheers & hth., - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems running VirtualEnv under Windows.
I've resolved this issue by deleting the *.py file association in Windows. You can do this either by associating *.py with something like textpad, using a utility such as http://defaultprogramseditor.com/ or doing so in the registry. Note that when using the command like you need to issue commands with a preceding `python` keyword. For example in a normal installation enviroment the following is possible `django-admin.py startproject MyProject`, however in a VirtualEnv with *.py associations removed one must do `python django- admin.py startproject MyProject` otherwise Windows will attempt to open the file in the default application even if there isn't one. Thanks, Ash On Jul 12, 1:55 am, ashconnor wrote: > Hello, > > After reading 'Practical Django Projects' I decided that I want to > implement the VirtualEnv tip suggested in order to properly segregate > code/modules in different projects. I am however having problems with > my django installations not using site-packages within the virtualenv > but rather attempting to use site-packages in the default python > installation directory. > > Recreating the problem: > > 1) Install Python 2.7 via the Windows installer. Add C:/Python27;C:/ > Python27/Scripts to Windows PATH. > 2) Install setuptools-0.6c11-py2.7.egg via the Windows installer. > 3) Install VirtualEnv through `pip install virtualenv` > 4) Create an VirtualEnv via `virtualenv --no-site-packages MyEnvName` > 5) Activate VirtualEnv via `../MyEnvName/Scripts/activate.bat` > 6) Install django via `pip install django` > 7) Run django-admin.py startproject ProjectName > 8) Error results stating django.core module does not exist. > > NB: This error will not occur if django is installed in your root > directory. > NB2: Running the Python interpreter in active VirtualEnv to print the > sys.path shows the correct paths. Which has just futher added to my > confusion. > > I'd appreciate any insight or troubleshooting assistance. > > Thanks > > Ash -- http://mail.python.org/mailman/listinfo/python-list
Re: round issue
On 7/12/2010 2:52 AM Robin Becker said... What value should round(-9.85,1) return? Per round's definition, -9.9. String interpolation for %n.mf doesn't appear to define it's rounding behavior, so a peek at the source would answer what's being done. It does look inconsistent however, and it seems to me rounding and interpolation should behave similarly. So I'd call it a bug. Emile >>> def display(val): ... print "%.1f" % val ... print round(val,1) ... >>> display(1.45) 1.5 1.5 >>> display(-1.45) -1.5 -1.5 >>> display(-1.85) -1.9 -1.9 >>> display(1.85) 1.9 1.9 >>> display(-7.85) -7.8 -7.9 >>> display(-9.85) -9.8 -9.9 >>> -- http://mail.python.org/mailman/listinfo/python-list
GUIs (was: grailbrowser now running under python 2.5 (probably above too))
MRAB writes: > John Bokma wrote: [..] >> Can't think of why not. Of course not all operations are shared by each >> OS, but /I/ know that I can't do chmod on Windows. But it doesn't mean >> that on Windows I can't make a file only readable by me. Just give me >> the Windows security options on Windows, and chmod on *nix and I would >> be very happy. >> > On Windows the root folders of the different drives could be treated as > subfolders of a 'root' folder. Yup, instead of a single tree there is a forrest. Wouldn't confuse me, and I doubt anyone else. >> Especially if all can be done via a context menu a la RISC OS. >> > Ah, RISC OS! :-D. > > I'd heard how user-friendly the Mac was, but when I was first introduced > to the Mac (circa MacOS 8) I was very surprised that even it still used > old-fashioned Open and Save dialog boxes with their own little file > browsers like on a Windows PC instead of drag-and-drop like I'd become > used to on RISC OS. And that menu bar not even at the top of the window > but at the top of the _screen_! And the way that bringing one Finder > window to the front brought _all_ the Finder windows in front of the > other windows! I was distinctly underwhelmed... :-( > It's on top of the screen because of Fitts's law: it's easier to move accurately to the top of the screen than to the top of the window (unless it's located in the top or bottom of the screen). However, personally I think that a context menu even scores better: it's easier to click a mouse button than to roll up and then move to the correct menu entry. Yes, RISC OS has some very good ideas: 1) context menus instead of menus at the top of the Windows/screen 2) clearly defined operations of each of the three mouse buttons: left = select, middle = context menu, right = adjust 3) the ability to select items in a menu and keep the menu open 4) drag & drop saving/loading (including between applications) 5) direction of scrollbars depends on mouse button: left = expected direction, right = reverse. Based on this I would say that the designers of RISC OS understood Fitts's Law way better. I am aware of ROX but haven't checked it out yet. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* Steven D'Aprano, on 12.07.2010 04:39: On Mon, 12 Jul 2010 03:12:10 +0200, Alf P. Steinbach /Usenet wrote: * MRAB, on 12.07.2010 00:37: [...] In Java a variable is declared and exists even before the first assignment to it. In Python a 'variable' isn't declared and won't exist until the first 'assignment' to it. That is a misconception. In Python a variable is declared by having an assignment to it, which for a local variable may be anywhere within a routine. Oh, I'm going to regret being sucked into this... In *CPython*, but not necessarily other implementations, variables which are local to a function are not kept in a dictionary-based namespace, but in slots in the code object (not to be confused with __slots__ used for classes). Python has STORE_FAST and LOAD_FAST byte-codes for accessing locals. This is intended as a speed, and possibly memory, optimization. I don't believe this is a requirement though, so implementations may not do this. It is true that the slot is created at compile time, and in *that sense*, local variables exist before they are bound. I'm not entirely convinced that this is the only sense that matters, but never mind. The error message given exposes this to the user: def f(): ... print x ... x = 1 ... f() Traceback (most recent call last): File "", line 1, in File "", line 2, in f UnboundLocalError: local variable 'x' referenced before assignment If you try this with a global, you get this: def f(): ... global x ... print x ... f() Traceback (most recent call last): File "", line 1, in File "", line 3, in f NameError: global name 'x' is not defined In this case, there's no doubt that global variable "x" doesn't exist at all -- there is no key "x" in the global namespace. Yes. What I disproved was the statement that every Python variable is created by the execution of an assignment. Some (the global ones) are. :-) It seems to me that "a slot to hold the variable is created for local variables" is an implementation detail, not a language feature. Yes. However, any Python implementation has to implement the same user level semantics in some way (note: use level semantics do not include "space reserved" for an unassigned variable, or even for all assigned variables since with single assignment a sufficiently smart compiler can optimize away the space, but user level semantics do include existence and resultant effect). As I see it it doesn't matter whether the implementation is CPython call frame slots or that mechanism called something else or a different mechanism called the same or a different mechanism called something different; what IMO matters is same semantics, that any assignment to a variable within a routine serves as a compile time declaration, creating that local variable in advance, unless, with Python 3.x., that name has been declared as a 'global' or 'nonlocal'. So, this is a possible point of disagreement. I say the semantics of local variable creation are part of the language definition, but I get the /impression/ that maybe you think it's CPython-specific, that e.g. def foo(): x x = 0 might not raise an unassigned variable exception with some conforming Python implementation, i.e. different effect for same code with different implementations, that this is at least /unspecified behavior/ in Python? CPython could easily hide the difference by changing the exception from UnboundLocalError to: NameError: local name 'x' does not exist and nobody would be any wiser. (Well, perhaps people who catch UnboundLocalError, but why would you do that?) I also note that UnboundLocalError is a subclass of NameError, so "variable exists but is not bound" is considered to be a special case of "variable doesn't exist" rather than a completely independent case. In that sense, I think I'm on solid ground to say that in Python variables don't exist until they are bound to a value, and leave it to pedants like you and I to mention that for CPython local variables have space reserved for them by the compiler before they are bound. He he. I wouldn't say "space reserved". That is an implementation detail. Cheers, - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
On Jul 12, 1:16 pm, John Nagle wrote: > On 7/12/2010 7:19 AM, Grant Edwards wrote: > > > On 2010-07-09, Les Schaffer wrote: > > >> i have been asked to guarantee that a proposed Python application will > >> run continuously under MS Windows for two months time. And i am looking > > ^^ > > > IMO, that's going to be your main problem. > > If you're doing a real-time job, run a real-time OS. QNX, > a real-time variant of Linux, Windows CE, Windows Embedded, LynxOS, > etc. There's too much background junk going on in a consumer OS > today. > > Yesterday, I was running a CNC plasma cutter that's controlled > by Windows XP. This is a machine that moves around a plasma torch that > cuts thick steel plate. A "New Java update is available" window > popped up while I was working. Not good. > > John Nagle I'm not sure I can like that example any better. -- http://mail.python.org/mailman/listinfo/python-list
Re: round issue
Emile van Sebille fenx.com> writes: > > On 7/12/2010 2:52 AM Robin Becker said... > > > What value should round(-9.85,1) return? > > Per round's definition, -9.9. No. The float that's represented by the literal '-9.85' *isn't* exactly -9.85, for all the usual binary floating-point reasons. The value that gets stored is a tiny amount smaller (i.e., closer to zero) than -9.85, so according to the definition it should round *down*, to -9.8. (Or rather, to a float that's very close to, but not exactly equal to, -9.8.) > String interpolation for %n.mf doesn't > appear to define it's rounding behavior, so a peek at the source would > answer what's being done. In Python 2.6, the string interpolation delegates to the system, so it does whatever C string formatting does. Usually that's rounding to nearest, with exact halfway cases rounded to even. In Python 2.7 and 3.x, Python has its own code for string formatting, and again it rounds to nearest, rounding ties to even. > It does look inconsistent however, and it seems to me rounding and > interpolation should behave similarly. Agreed. In this case it's a minor bug that round(-9.85, 1) produces -9.9 instead of -9.8; both string formatting and round should give -9.8. This bug is fixed in Python 2.7 and in Python 3.x. Note that in 2.7 there's still a legitimate difference: round rounds halfway cases away from 0, while string formatting rounds them to even. So the following results are correct: Python 2.7 (r27:82500, Jul 11 2010, 22:38:53) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> round(1.25, 1) 1.3 >>> '%.1f' % 1.25 '1.2' (1.25 *is* an exact halfway case, since it's exactly representable as a binary float.) In Python 3.x, round always does round-half-to-even, so string formatting and round should agree (and if they don't, it's definitely a bug: please report it!) With all this said, asking for *decimal* rounding of *binary* approximations to *decimal* halfway cases to give the results you expect is ... optimistic, to say the least. Use the decimal module if you care about which way your (almost) halfway cases get rounded. [I already replied to this earlier through Google groups, but I'm not sure whether it went through properly. Apologies for the duplication, if so.] -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't python's list append() method return the list itself?
On Jul 12, 4:20 pm, Hrvoje Niksic wrote: > dhruvbird writes: > > No, I meant x.append(4) > > Except that I want to accomplish it using slices. > > > (I can do it as x[lex(x):] = [item_to_append] but is there any other > > way?) > > It seems that you've found a way to do so, so why do you need another > way? Are you after elegance? Efficiency? Brevity? Actually, the reason I ask is because I think a lot of things can be done using slices and its support for negative indexes. Basically putting constants in the slices (as opposed to variables like len(x), etc... which depend upon the variable name). So, was just trying to cogitate on whether append can be implemented that way or not. Regards, -Dhruv. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't python's list append() method return the list itself?
On 7/11/2010 5:24 PM, Steven D'Aprano wrote: On Sun, 11 Jul 2010 08:59:06 -0700, dhruvbird wrote: Why doesn't python's list append() method return the list itself? For that matter, even the reverse() and sort() methods? I found this link (http://code.google.com/edu/languages/google-python- class/lists.html) which suggests that this is done to make sure that the programmer understands that the list is being modified in place, but that rules out constructs like: ([1,2,3,4].reverse()+[[]]).reverse() Yes. So what? Where's the problem? List methods work in place. ... Not everything needs to be a one-liner. It's interesting that all Python functions are considered to return a value. Arguably, if a function just does a "return", it should be an error to try to use its return value. Some languages have a very functional orientation, and everything is considered to return some value, even control structures. LISP is like that. But Python isn't one of those languages. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: iptcinfo: Can not import: Newbie not really knowing what he is doing
On Jul 12, 4:11 pm, Nick Raptis wrote: > Hi Richard!> I have downloaded iptcinfo and placed it in > python27\Lib\site-packages > > \iptcinfo > > > I guessed that was the right place, because that is where PIL ended > > up, but that had a fancy installer with it. > > You did place it in the right path, but the "fancy installer" does one > more thing, it registers the package into the python-path, so python can > get to it. > I've long switched from windows unfortunately and can't remember the way > it does this though, so you can do it manually. > > Have some good news though: I looked in the IPTCinfo package and it does > indeed include a setup.py, which is a standard way of installing python > packages. > All you need to do is unpack the package to any folder and run > setup.py install > from that folder, which should take care of everything for you. > > Some documentation on installing packages for you to > read:http://docs.python.org/install/ > > Nick What a star. It is all now working. I will try to look at the reference you mentioned, but at the moment I can not even figure out why 'python' on its own does not work. I would have thought the installation would have set the appropriate environment variables, but it does not seem to have. I have to give the full path name to python.exe. Just remembered SET at DOS prompt, but no mention of PYTHON anywhere. Thank you very much again - I now have a list of all my JPEGS and their CAPTIONS. Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Mon, 12 Jul 2010 13:56:38 +0100, bart.c wrote: "Steven D'Aprano" wrote in message news:[email protected]... On Mon, 12 Jul 2010 09:48:04 +0100, bart.c wrote: That's interesting. So in Python, you can't tell what local variables a function has just by looking at it's code: def foo(day): if day=="Tuesday": x=0 print ("Locals:",locals()) #foo("Monday") Does foo() have 1 or 2 locals? That's easy for CPython: it prepares two slots for variables, but only creates one: foo("Monday") ('Locals:', {'day': 'Monday'}) foo.func_code.co_varnames ('day', 'x') foo.func_code.co_nlocals 2 So, the question is, is x a local variable or not? It's not in locals, but the function clearly knows that it could be. So Alf P.S. could be right; x exists, but Python pretends it doesn't until it's assigned to. CPython, not Python. And as Steven said, x *doesn't* exist. Allowance is made by that specific implementation of the interpreter because x *might* exist, but in this particular case it doesn't and a more dynamic implementation might choose not to reserve a slot just in case. x is created until it's actually used. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
how to delete "\n"
Hi, I just want to delete "\n" at each line. My operating system is ubuntu
9.1. The code is as follows
#!/usr/bin/python
import string
fileName=open('Direct_Irr.txt', 'r') # read file
directIrr = fileName.readlines()
fileName.close()
for line in directIrr:
line.rstrip('\n')
print directIrr
But I found there is still "\n" . Could someone help me why it is not
correct?
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
John Nagle writes: >Yesterday, I was running a CNC plasma cutter that's controlled > by Windows XP. This is a machine that moves around a plasma torch that > cuts thick steel plate. A "New Java update is available" window > popped up while I was working. Not good. You can blame that one on Sun (or Oracle nowadays). Good example though. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
I hope this could help:
>>> f = open('powersave.sh')
>>> map(lambda s: s.strip(), f.readlines())
['echo 1 > /sys/module/snd_hda_intel/parameters/power_save', 'echo
min_power > /sys/class/scsi_host/host0/link_power_management_policy',
'echo 1 > /sys/module/snd_hda_intel/parameters/power_save']
I know for sure someone else will address you to other better solutions :)
On Mon, Jul 12, 2010 at 10:27 PM, Jia Hu wrote:
> Hi, I just want to delete "\n" at each line. My operating system is ubuntu
> 9.1. The code is as follows
>
> #!/usr/bin/python
> import string
> fileName=open('Direct_Irr.txt', 'r') # read file
> directIrr = fileName.readlines()
> fileName.close()
> for line in directIrr:
> line.rstrip('\n')
> print directIrr
>
> But I found there is still "\n" . Could someone help me why it is not
> correct?
>
> Thank you
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
Matteo Landi
http://www.matteolandi.net/
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
On Mon, Jul 12, 2010 at 2:27 PM, Jia Hu wrote:
> Hi, I just want to delete "\n" at each line. My operating system is ubuntu
> 9.1. The code is as follows
>
> #!/usr/bin/python
> import string
> fileName=open('Direct_Irr.txt', 'r') # read file
> directIrr = fileName.readlines()
> fileName.close()
> for line in directIrr:
> line.rstrip('\n')
> print directIrr
>
> But I found there is still "\n" . Could someone help me why it is not
> correct?
The print statement automatically adds a newline to each line. If you
want the lines written verbatim, use sys.stdout.write(line)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Sun, 11 Jul 2010 18:17:49 +, Duncan Booth wrote: > wheres pythonmonks wrote: > >> I'm an old Perl-hacker, and am trying to Dive in Python. I have some >> easy issues (Python 2.6) >> which probably can be answered in two seconds: without going into details on how to do these things in python(many suggestions have already been made) i think you need to take a step back Why do you want to do these particular things in this way? is it because this is what is needed to get the job done or is it because this is what's needed to get the job done in perl? if the later then step back and think what is the real goal & program accordingly. Each language does things differently ( if they didn't we wouldn't have different languages!) what is Best for perl (or c , java, pascal or malbolge) may not necessarily be the best for Python & vice Versa. -- backups: always in season, never out of style. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On 7/12/2010 4:48 AM, bart.c wrote:
>>> def foo():
print("Before:", locals())
x = 0
print("After:", locals())
>>> foo()
Before: {}
After: {'x': 0}
That's interesting. So in Python, you can't tell what local variables a
function has just by looking at it's code:
You are being fooled by the multiple meanings of the overloaded term
'variable'. Thing are clearer with the two terms 'name' and 'namespace'
(a set of name-object bindings).
Before compiling function code, an interpreter must read it and make a
classified list of *names*. The interpreter has to know the fixed set of
local names in order to know what to do with assignment statements. If
the interpreter can tell how many local names there are, so can you.
Before a function begins execution, all parameter names must be bound,
with no arguments left over. At that point, the local namespace consists
of those parameter-object bindings. During the execution of the
function, bindings may be added and deleted. The size of the local
namespace varies.
def foo(day):
if day=="Tuesday":
x=0
print ("Locals:",locals())
#foo("Monday")
Does foo() have 1 or 2 locals?
foo has 2 local names. Its local namespace starts with 1 binding and may
get another, depending of the value of the first.
If the size of the local namespace at some point of execution depends on
unknown information, then of course the size at that point is also unknown.
Here is another example:
>>> def f(a):
print(locals())
del a
print(locals())
a = None
print(locals())
>>> f(2)
{'a': 2}
{}
{'a': None}
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
On Mon, Jul 12, 2010 at 1:27 PM, Jia Hu wrote:
> Hi, I just want to delete "\n" at each line. My operating system is ubuntu
> 9.1. The code is as follows
>
> #!/usr/bin/python
> import string
> fileName=open('Direct_Irr.txt', 'r') # read file
> directIrr = fileName.readlines()
> fileName.close()
> for line in directIrr:
> line.rstrip('\n')
> print directIrr
>
> But I found there is still "\n" . Could someone help me why it is not
> correct?
.rstrip() returns a *new* string without trailing whitespace (which
you are currently then throwing away); it does *not* modify string
objects in-place. Python strings objects are entirely immutable and
unmodifiable; all operations on them merely produce /new/ strings.
Assuming you still want to use .readlines(), you'd do:
directIrr = fileName.readlines()
fileName.close()
directIrr = [line.rstrip('\n') for line in directIrr]
print directIrr
For how third line works, google "python list comprehensions".
Cheers,
Chris
--
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Numpy now supports Python3, Scipy to follow soon
On 7/12/2010 4:05 AM, Steven D'Aprano wrote: Pardon me if this has already been mentioned, but I didn't see it, and this is big big news. The latest release of numpy now supports Python 2.x and 3.x out of a single code base, and Scipy is predicted to follow soon. http://www.mail-archive.com/[email protected]/msg26524.html If I can take the liberty of quoting Pauli Virtanen: An important point is that supporting Python 3 and Python 2 in the same code base can be done, and it is not very difficult either. It is also much preferable from the maintenance POV to creating separate branches for Python 2 and 3. Well done to all those who contributed to the effort! There are extensive notes on the transition at http://projects.scipy.org/numpy/browser/trunk/doc/Py3K.txt I am sure that some of this should be added to the current HowTo on porting CAPI to Py3. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* Rhodri James, on 12.07.2010 22:19: On Mon, 12 Jul 2010 13:56:38 +0100, bart.c wrote: "Steven D'Aprano" wrote in message news:[email protected]... On Mon, 12 Jul 2010 09:48:04 +0100, bart.c wrote: That's interesting. So in Python, you can't tell what local variables a function has just by looking at it's code: def foo(day): if day=="Tuesday": x=0 print ("Locals:",locals()) #foo("Monday") Does foo() have 1 or 2 locals? That's easy for CPython: it prepares two slots for variables, but only creates one: foo("Monday") ('Locals:', {'day': 'Monday'}) foo.func_code.co_varnames ('day', 'x') foo.func_code.co_nlocals 2 So, the question is, is x a local variable or not? It's not in locals, but the function clearly knows that it could be. So Alf P.S. could be right; x exists, but Python pretends it doesn't until it's assigned to. CPython, not Python. And as Steven said, x *doesn't* exist. Allowance is made by that specific implementation of the interpreter because x *might* exist, but in this particular case it doesn't and a more dynamic implementation might choose not to reserve a slot just in case. x is created until it's actually used. You are conflating existence with space allocation. It's up to the implementation whether to allocate memory for the variable's reference in any particular case where that memory isn't strictly required. This is known as "optimization". Optimization depends on the implementation. Existence of a variable means, among other things, that * You can use the value, with guaranteed effect (either unassigned exception or you get a proper value): in particular, you won't be accessing a global if you're using the name of a local declared by a later assignment. * You can assign to it. How the Python implementation implements that is an implementation detail. In short, how CPython does things is completely irrelevant to the language's semantics, so you're conflating things here. Cheers & hth., - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
multitask http server (single-process multi-connection HTTP server)
for several reasons, i'm doing a cooperative multi-tasking HTTP server: git clone git://pyjs.org/git/multitaskhttpd.git there probably exist perfectly good web frameworks that are capable of doing this sort of thing: i feel certain that twisted is one of them. however, the original author of rtmplite decided to rip twisted out and to use multitask.py and i'm one of those strange people that also likes the idea of using 900 lines of awesome elegant code rather than tens of thousands of constantly-moving-target. one of the things that's slightly unfortunate is that i'm going to have to copy SimpleHTTPServer.py and slightly modify it; CGIHTTPServer.py as well. this is Generally Bad Practice. can anyone think of a way of monkey-patching or otherwise using SimpleHTTPRequestHandler and CGIHTTPRequestHandler and overriding the base class from which those two are derived? i have had to pull bits out of BaseHTTPRequestHandler to make them use the "yield" logic of multitask.py already, which was painful enough. ideas, anyone? l. -- http://mail.python.org/mailman/listinfo/python-list
Standard distutils package problems with MSVC / lacking functionality?
I let the setup.py script talk: # 03_1__noddy from distutils.core import setup, Extension import distutils.ccompiler compilerName = distutils.ccompiler.get_default_compiler() options = [] if compilerName == "msvc": # * distutils sets warning level 3: # Overriding with warning level 4 generates command line warning D9025... # There's no good away around that, it needs fix/extension of distutils # or the config file(s) that distutil uses (perhaps that's a makefile?). options.append( "/W4" ) # Must be done in this script. # * distutils forgets to enable exception handling: options.append( "/EHsc" ) # Could be done via CL env. var. # * distutils forgets to enable RTTI: options.append( "/GR" ) # Could be done via CL env. var. # * distutils forgets to enable standard 'for' loop and 'wchar_t' type: options.append( "/Zc:forScope,wchar_t" )# Could be done via CL env. var. module1 = Extension( name = "noddy", sources = [ "noddy.cpp" ], extra_compile_args = options ) setup( name= "noddy", version = '1.0', description = 'This is a demo package', ext_modules = [module1] ) Cheers, - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: Lua is faster than Fortran???
On the positive side, Lua supports tail call optimization and coroutines are built in by default. -- дамјан ((( http://damjan.softver.org.mk/ ))) Education is one of the "prices" of freedom that some are unwilling to pay. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
Jia, print ''.join( open( 'Direct_Irr.txt' ).read().split() ) Broken out: - open(): open file - read(): read its entire contents as one string - split(): split the contents into a list of lines (splits lines at \n; does not include \n in split values) - ''.join(): join list of lines with an empty char Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
Thank you. It works now.
if I use 'print' to print the whole list, 'print' will add newline
at the end of the list but not each item in the list. right?
For the code:
for line in fileName:
line = line.rstrip('\n')
I think this will affect 'fileName' because it assign the value to 'line' ?
But when I print fileName, "\n" still exists at each item in the list.
Because each line in my txt file are numeric values. is there any other
better way to get each
numerical value at each line? for example using numpy or changing string
list to numerical list?
Thank you for help.
On Mon, Jul 12, 2010 at 4:45 PM, Chris Rebert wrote:
> On Mon, Jul 12, 2010 at 1:27 PM, Jia Hu wrote:
> > Hi, I just want to delete "\n" at each line. My operating system is
> ubuntu
> > 9.1. The code is as follows
> >
> > #!/usr/bin/python
> > import string
> > fileName=open('Direct_Irr.txt', 'r') # read file
> > directIrr = fileName.readlines()
> > fileName.close()
> > for line in directIrr:
> >line.rstrip('\n')
> > print directIrr
> >
> > But I found there is still "\n" . Could someone help me why it is not
> > correct?
>
> .rstrip() returns a *new* string without trailing whitespace (which
> you are currently then throwing away); it does *not* modify string
> objects in-place. Python strings objects are entirely immutable and
> unmodifiable; all operations on them merely produce /new/ strings.
>
> Assuming you still want to use .readlines(), you'd do:
> directIrr = fileName.readlines()
> fileName.close()
> directIrr = [line.rstrip('\n') for line in directIrr]
> print directIrr
>
> For how third line works, google "python list comprehensions".
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
On 07/12/2010 11:29 PM, [email protected] wrote: > Jia, > > print ''.join( open( 'Direct_Irr.txt' ).read().split() ) > > Broken out: > > - open(): open file > - read(): read its entire contents as one string > - split(): split the contents into a list of lines > (splits lines at \n; does not include \n in split values) also splits at other whitespace. > - ''.join(): join list of lines with an empty char > > Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: multitask http server (single-process multi-connection HTTP server)
Hi lkcl, Do you have any documentation or overview for your project? Questions I would be interested in: - List of features already working - list of features under development - list of features being in in the near future lkcl wrote: > for several reasons, i'm doing a cooperative multi-tasking HTTP > server: > git clone git://pyjs.org/git/multitaskhttpd.git > > there probably exist perfectly good web frameworks that are capable of > doing this sort of thing: i feel certain that twisted is one of them. > however, the original author of rtmplite decided to rip twisted out > and to use multitask.py and i'm one of those strange people that also > likes the idea of using 900 lines of awesome elegant code rather than > tens of thousands of constantly-moving-target. > > one of the things that's slightly unfortunate is that i'm going to > have to copy SimpleHTTPServer.py and slightly modify it; > CGIHTTPServer.py as well. this is Generally Bad Practice. > > can anyone think of a way of monkey-patching or otherwise using > SimpleHTTPRequestHandler and CGIHTTPRequestHandler and overriding the > base class from which those two are derived? > > i have had to pull bits out of BaseHTTPRequestHandler to make them use > the "yield" logic of multitask.py already, which was painful enough. > > ideas, anyone? > > l. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
Thomas, > split() also splits at other whitespace. Doh! Corrected version follows: print ''.join( open( 'Direct_Irr.txt' ).read().splitlines() ) Broken out: - open(): open file - read(): read its entire contents as one string - splitlines(): split the contents into a list of lines (splits lines at \n; does not include \n in split values) - ''.join(): join list of lines with an empty char Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Why did I Embrace Islam?
Why did I Embrace Islam? This is an extract from Dr. Gronier, a French MP, who embraced Islam. Revealing the reason of embracing Islam he said, I read all of the Ayat (Quranic verses), which have a relation to medical, health, and natural sciences that I studied before and have a wide knowledge of. I found that these verses are totally compatible with and give a picture of our modern sciences. Thus, I embraced Islam as it was obvious that Muhammad revealed the Absolute Truth more than a thousand years ago. Had every specialist, artist or scientist compared those Quranic verses to his own specialization, beyond the shadow of doubt he would embrace Islam, especially if he has a sound mentality and goodwill to search for the truth and not a mentally defective person with the intentions of malevolent aims>> Islam is the last religion to be sent to the world , every religion had proofs that authenticated its Divine source . God foreordained that Islam would be the last message to the world , so it must comprise many miracles that could be categorized under six categories , among them in this age , being the age of science , what is termed as the scientific miracles which science has recently proved them amazingly . let alone the scientific miracle , as we are going to talk about the unseen matters news . Prophet Mohummed had depicted and given prophecies concerning our generation and the many generation to come . In fact , these prophecies which can't be easily enumerated , have come true . As to the miracle of the unseen news , prophet Mohummed gave a large number of them ; some of them happened during his life , others directly after his death . Every age witnessed the fulfilment some of these . The large portion of these prophecies go to our age . Insha Allah , we will tackle these in the coming studies. Some of these prophecies , as prophet Mohummed determined , are portents of the of the doomsday . we ,now , are approaching that day according to the Devine calculation . The miracle of the unseen tackled that the different phases of life , these tackled the social life , economic life , techmological life , political strifes and wars . Though ther are fearful , they prove the true phrophethood of prophet Mohummed . What we are giving here are just two portents that reflect the social and economic life .The Bedouins , in the life of prophet Mohummed , used to lead a very simple life . They used to live in very simple houses out of mud and palm leaves . The discovery of oil made a revolution in every thing in the life of the bedouin . Contraray to the life they used to lead , they ,now , live in very tall structures but even they compete in building very high structures a picture of a tall building in the arabia Here are two Hadith ( traditional sayings of prophet mohummed ) that talk about two prophecies that have come true . It is narrated in Sahih Muslim that Allah's Apostle (peace be upon him) said to his companions ( through a long conversation about the signs of the last hour) ask me but the companions of the prophet embarrassed to ask him. Then there appeared before us a man and sat with the Apostle (peace be upon him) He knelt before him placed his palms on his thighs and said: Muhammad, inform me about al-Islam. The Messenger of Allah (peace be upon him) said: Al-Islam implies that you testify that there is no god but Allah and that Muhammad is the messenger of Allah, and you establish prayer, pay Zakat, observe the fast of Ramadan. He (the inquirer) said: You have told the truth. He (the inquirer) said: Inform me about Iman (faith). He (the Holy Prophet) replied: That you affirm your faith in Allah, in His angels, in His Books, in His Apostles, in the Day of Judgment, and you affirm your faith in the Divine Decree about good and evil. He (the inquirer) said: You have told the truth. He (the inquirer) again said: Inform me about al-Ihsan (performance of good deeds). He (the Holy Prophet) said: That you worship Allah as if you are seeing Him, for though you don't see Him, He, verily, sees you. He (the enquirer) again said: Inform me about the hour (of the Doom). He (the Holy Prophet) remarked: One who is asked knows no more than the one who is inquiring (about it). He (the inquirer) said: Tell me some of its indications. He (the Holy Prophet) said: That the slave-girl will give birth to her mistress and master, that you will find barefooted, destitute goat- herds vying with one another in the construction of magnificent buildings . Man installed hundreds of marine stations to study the characteristics of various seas. Scientists have found out that the differences in these characteristics distinguished one sea from another. But why do these seas not mix and become homogeneous in spite of the effect of tide and ebb that moves sea water twice a day, and causes seas to move forward and backward turbulently, besides other factors that cause sea water to be in continuous movement and turbulence, such as su
Help choosing license for new projects
I'm starting a new python code project. What license do you suggest? I am searching, but I'm not finding a simple comparison of licenses. So I don't know which to use. Maybe MIT or Apache or LGPL or BSD? Are there certain licenses to avoid using because of interaction problems between libraries using GPL2 / GPL3 / MIT / LGPL. / BSD with my own? I want: 1] Pretty much let anyone use it. Users do not have to include source code, as long as I get credit. (which I think normallly is a textfile with project url + name?) 2] (if it matters) I will be using different combinations of pyglet, pygame, wxPython, etc. 3] I want the option to use my own code in something commercial at a later date. Does #3 complicate things, or is fine when including author info? The choices for google code projects are: Apache License 2.0 Eclipse license 1.0 GPLv2 GPLv3 GNU lesser GPL MIT license Mozilla Public license 1.1 New BSD License thanks for advice, -- ninmonkey -- http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
On 07/12/2010 12:16 PM, John Nagle wrote: On 7/12/2010 7:19 AM, Grant Edwards wrote: On 2010-07-09, Les Schaffer wrote: i have been asked to guarantee that a proposed Python application will run continuously under MS Windows for two months time. And i am looking ^^ IMO, that's going to be your main problem. Yesterday, I was running a CNC plasma cutter that's controlled by Windows XP. This is a machine that moves around a plasma torch that cuts thick steel plate. A "New Java update is available" window popped up while I was working. Not good. Hi, it looks like you're attempting to cut something with a plasma torch. Would you like help? (_) inserting a steel plate to cut (_) severing the tip of your finger [ ] Don't show me this tip again. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Why did I Embrace Islam?
On Mon, 12 Jul 2010 14:54:00 -0700, nais-saudi wrote: > Why did I Embrace Islam? Very interesting & good fro you but I cannot find any thing related to python here. -- This place just isn't big enough for all of us. We've got to find a way off this planet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
Perhaps I'm misunderstanding, but ... On Jul 12, 2010, at 13:57 , Alf P. Steinbach /Usenet wrote: > > Existence of a variable means, among other things, that > > * You can use the value, with guaranteed effect (either unassigned exception >or you get a proper value) Surely by that definition any variable in any Python program "exists" -- you are guaranteed to get one of NameError, UnboundLocalError, or a value. That seems to argue away the meaning of the word entirely, and renders it not particularly useful. > > How the Python implementation implements that is an implementation detail. > > In short, how CPython does things is completely irrelevant to the language's > semantics, so you're conflating things here. > As I'd understood the previous discussion, it is the CPython implementation that reserves local names and produces UnboundLocalErrors. The language semantics don't call for it, and another implementation might choose to handle function locals the same way as globals, through a namespace dictionary -- in which case the variable *wouldn't* exist in any way, shape, or form until it was assigned to. What am I getting wrong here? - Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: multitask http server (single-process multi-connection HTTP server)
On Mon, Jul 12, 2010 at 4:59 PM, lkcl wrote: > for several reasons, i'm doing a cooperative multi-tasking HTTP > server: > git clone git://pyjs.org/git/multitaskhttpd.git > > there probably exist perfectly good web frameworks that are capable of > doing this sort of thing: i feel certain that twisted is one of them. > however, the original author of rtmplite decided to rip twisted out > and to use multitask.py and i'm one of those strange people that also > likes the idea of using 900 lines of awesome elegant code rather than > tens of thousands of constantly-moving-target. > > one of the things that's slightly unfortunate is that i'm going to > have to copy SimpleHTTPServer.py and slightly modify it; > CGIHTTPServer.py as well. this is Generally Bad Practice. > > can anyone think of a way of monkey-patching or otherwise using > SimpleHTTPRequestHandler and CGIHTTPRequestHandler and overriding the > base class from which those two are derived? > > i have had to pull bits out of BaseHTTPRequestHandler to make them use > the "yield" logic of multitask.py already, which was painful enough. > > ideas, anyone? > > l. I may not be fully understanding what you're doing, but is there a reason that one of the mixins can't be used? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Python 3 grammar, function parameters
Greetings to Python users,
I'm trying to parse Python code using the grammar supplied with the
documentation set, and have a question on the grammar for function
parameters:
funcdef: 'def' NAME parameters ['->' test] ':' suite
parameters: '(' [typedargslist] ')'
typedargslist: ((tfpdef ['=' test] ',')*
('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef]
| '**' tfpdef)
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
tfpdef: NAME [':' test]
>From what I understand, a naked asterisk - i.e. it is not a prefix to an
identifier - is not a valid parameter, but the grammar explicitly
allows it by making the identifier that immediately follows the
asterisk optional.
Are there cases where naked asterisk is allowed as a function
parameter? If not, would it be correct for the grammar to specify the
identifier trailing asterisk as mandatory?
Thanks for any insight.
Jay
--
http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* Rami Chowdhury, on 13.07.2010 00:14: Perhaps I'm misunderstanding, but ... On Jul 12, 2010, at 13:57 , Alf P. Steinbach /Usenet wrote: Existence of a variable means, among other things, that * You can use the value, with guaranteed effect (either unassigned exception or you get a proper value) Surely by that definition any variable in any Python program "exists" -- you are guaranteed to get one of NameError, UnboundLocalError, or a value. That seems to argue away the meaning of the word entirely, and renders it not particularly useful. No, you're conflating non-existence (NameError) with accessing the value of an existing but unassigned variable (UnboundLocalError). It is like arguing that vacuum is the same as cement because sticking your head into it for ten minutes or so yields an effect -- you're dead -- that in many ways is just about the same. However, the tangible existence of cement means that one can pour it over your head, /adding/ the cement, while it's difficult to pour vacuum over your head; rather, for the latter effect one would need to /remove/ the air around your head. OK, the analogy halts a little. But I think you'll get it. Similarly, you can add a variable and thereby cause am UnboundLocalError, and you can remove a variable and thereby cause a NameError. How the Python implementation implements that is an implementation detail. In short, how CPython does things is completely irrelevant to the language's semantics, so you're conflating things here. As I'd understood the previous discussion, it is the CPython implementation that reserves local names and produces UnboundLocalErrors. The language semantics don't call for it, and another implementation might choose to handle function locals the same way as globals, through a namespace dictionary -- in which case the variable *wouldn't* exist in any way, shape, or form until it was assigned to. What am I getting wrong here? The bit about the language semantics not specifying the effect. From the 3.1.1 language reference §4.1: "When a name is not found at all, a NameError exception is raised. If the name refers to a local variable that has not been bound, a UnboundLocalError exception is raised. UnboundLocalError is a subclass of NameError." And it goes on to elaborate on that, a little later: "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations." In short, Stephen D'Aprano's remarks were technically on the spot, while Rhodri James's follow up, that it seems influenced your response, was meaningless mumbo-jumbo with strong emphasis added repeatedly to denials of reality. This is the usual reaction of the religious when exposed to reality. Cheers & hth., - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: Help choosing license for new projects
On Mon, Jul 12, 2010 at 6:00 PM, Jake b wrote: > I'm starting a new python code project. What license do you suggest? I > am searching, but I'm not finding a simple comparison of licenses. So > I don't know which to use. Maybe MIT or Apache or LGPL or BSD? Fair warning: I like and use the GPL a lot, so I'm biased. Take my advice with a grain of salt and recognize that while everybody has some semi-rational basis for the license they choose, in the end the decision is likely to be made on dogmatic grounds. > Are there certain licenses to avoid using because of interaction > problems between libraries using GPL2 / GPL3 / MIT / LGPL. / BSD with > my own? Generally, GPL'd code likes GPL'd code and BSD/MIT etc are more free-form. Depending on what you leverage this may or may not be a problem for you. > I want: > 1] Pretty much let anyone use it. Users do not have to include source > code, as long as I get credit. (which I think normallly is a textfile > with project url + name?) GPL is pretty much out then. CC-BY-* may be the way to go. > 2] (if it matters) I will be using different combinations of pyglet, > pygame, wxPython, etc. Not going to dig through those to find the licenses for you. Be aware that their choices impact yours. > 3] I want the option to use my own code in something commercial at a later > date. Not generally an issue. Even GPL lets you sell your stuff. > Does #3 complicate things, or is fine when including author info? If you have many contributors it can. > The choices for google code projects are: > Apache License 2.0 Good choice, not my flavor but it does preserve attribution. > Eclipse license 1.0 Small license, doesn't give you the same degree of legal muscle that some others will if it gets violated. > GPLv2 > GPLv3 Both out on the source-not-required part. Personally, I like them (and the Artistic License) for exactly that reason. > GNU lesser GPL Fewer restrictions on linking, etc, but probably not what I would recommend here. > MIT license Good choice, well understood and widely used. Note that attribution is not preserved, although copyright is. That may or may not be enough for you. > Mozilla Public license 1.1 I'd avoid it, same caveats for the eclipse license and few obvious advantages. > New BSD License Also a good choice, same caveat as the X11 license. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: multitask http server (single-process multi-connection HTTP server)
On Mon, Jul 12, 2010 at 10:13 PM, geremy condra wrote:
> On Mon, Jul 12, 2010 at 4:59 PM, lkcl wrote:
>> for several reasons, i'm doing a cooperative multi-tasking HTTP
>> server:
>> git clone git://pyjs.org/git/multitaskhttpd.git
>>
>> there probably exist perfectly good web frameworks that are capable of
>> doing this sort of thing: i feel certain that twisted is one of them.
>> however, the original author of rtmplite decided to rip twisted out
>> and to use multitask.py and i'm one of those strange people that also
>> likes the idea of using 900 lines of awesome elegant code rather than
>> tens of thousands of constantly-moving-target.
> I may not be fully understanding what you're doing, but is there a
> reason that one of the mixins can't be used?
yes: they're threaded. or forking. this is *single-process*
cooperative multitasking. but that's not quite an answer, i know.
perhaps i should explain the three use-cases:
1) pyjamas-web.
pyjamas-web was an experiment i did, last year, to port pyjamas
http://pyjs.org to run the *exact* same app which normally is either
compiled to javascript (to run in the web browser), or is run as a
desktop app that *exact* same app i wanted to run it
*server-side*.
the reason for doing this is so that javascript would not be needed.
remember that the apps _really_ look like GTK apps:
RootPanel().add(HTML("Hello World")
so there's a python application, and i re-implemented all of the
widgets to add to an XML document (actually an eltree instance) and i
tidied things up with BeautifulSoup, voila, splat, spew forth some
HTML, output it from the web framework. i'd picked mod_python.
did it work? why yes it did! right up until i had pressed refresh a
few times, or pressed a few application "buttons".
at that point, it all fell over, because, why? ing threads,
that's why. HTTP is totally stateless. each mod_python thread is
arbitrarily picked to run an incoming request. i had totally
forgotten this, and had "associated" the pyjamas application instance
with the python thread's local storage memory. oh... shit :)
so, one person could be viewing an app, then next minute, someone
else connects to the server, and they get the other person's app!!
the only sane way round this, especially because if you want to
serialise the data structures of the pyjamas app you might have to
dump... what... 100k into a database or so (!!) and retrieve it, is to
have a SINGLE PROCESS multitasking web server, where all the apps are
stored in the SAME PROCESS.
then, you can store the apps in a dictionary, and look them up by a
session cookie identifier.
problem is solved.
2) rtmplite itself
rtmplite currently does RTMP only (port 1935). for the exact same
reasons as 1) the real-time audio/video streams need to be passed
across from client to client, and it needs to be done QUICKLY.
passing A/V data across unix domain sockets or shared memory in a
_portable_ fashion... does anyone _know_ how to do data sharing
portably using python? i don't! i'd love to know! :)
so to avoid the problem, easy: just design the app to be
single-process, handling multiple RTMP clients simultaneously.
now i would like to see rtmplite extended to support HTTP (RTMP can be
proxied over HTTP and HTTPS).
3) persistent database connections with per-user credentials
this is the _real_ reason why i'm doing this. the GNUmed team are
looking to create a web version of GNUmed. however, their current
system relies on postgresql "roles" for security. as a
python-wxWidgets app, that's of course absolutely fine.
but, for a _web_ app, it's not in the slightest bit fine, because
_all_ web frameworks assume "global" database credentials.
also, they're counting on the database connections being persistent.
how in hell's name, when using a stateless protocol like HTTP, do you
cross-associate *persistent* and multiple per-user database
connections with a user's browser, when all the web frameworks out
there only really do "global" single-username, single-password
database logins??
and the answer is: by using a cooperative multitasking httpd, which
adds a session cookie to each incoming connection, and uses that to
create an in-memory "application instance" which will STAY in memory
(of the single-process http server).
in that in-memory application instance, you can do whatever you like:
have a login form which takes user/pass as input, then uses that on
the POST to create a database connection, and stores the resultant
authenticated psycopg2 "pool" connection into the app instance.
the app instance is always always looked up in the dictionary of app
instances, using the cookie session id as a key, and thus, each
browser will _always_ be directed at the correct app instance.
i hate to think how this would be done using any of the standard
MixIns. even if you wrote a special MixIn which did single-instance
socket handling, you couldn't use it because the BaseHTTPHandler
Re: Help choosing license for new projects
Jake b writes: > I want: > 1] Pretty much let anyone use it. Users do not have to include source > code, as long as I get credit. (which I think normallly is a textfile > with project url + name?) The simplest effective license that requires nothing more that attribution is “under the terms of the Expat license” http://www.jclark.com/xml/copying.txt>. The terms are effectively the same as some of the MIT/X11 licenses, but: * It's even shorter and simpler, while still being widely regarded as effective. * The name “Expat license” is far less ambiguous, because MIT have released X11 under several different licenses, not all of them free. > 2] (if it matters) I will be using different combinations of pyglet, > pygame, wxPython, etc. You'll need to check the license terms on anything that you combine your work with, to see what the effective combination of terms will be. > 3] I want the option to use my own code in something commercial at a > later date. All free software licenses are commercial licenses, by definition. Preventing selling the work, or other commercial use, would make the license terms non-free. So if you choose any free software license this isn't a problem. > Does #3 complicate things, or is fine when including author info? You may be wanting to talk about making the work non-free (proprietary), in which case you're on your own :-) -- \ “My mind is incapable of conceiving such a thing as a soul. I | `\ may be in error, and man may have a soul; but I simply do not | _o__) believe it.” —Thomas Edison | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Mon, 12 Jul 2010 20:28:49 +0200, Alf P. Steinbach /Usenet wrote: > As I see it it doesn't matter whether the implementation is CPython call > frame slots or that mechanism called something else or a different > mechanism called the same or a different mechanism called something > different; what IMO matters is same semantics, that any assignment to a > variable within a routine serves as a compile time declaration, creating > that local variable in advance, unless, with Python 3.x., that name has > been declared as a 'global' or 'nonlocal'. > > So, this is a possible point of disagreement. > > I say the semantics of local variable creation are part of the language > definition, but I get the /impression/ that maybe you think it's > CPython-specific, that e.g. > >def foo(): >x >x = 0 > > might not raise an unassigned variable exception with some conforming > Python implementation, i.e. different effect for same code with > different implementations, that this is at least /unspecified behavior/ > in Python? Almost. I believe that "any assignment to a variable within a routine serves as a compile time declaration" is a promise of the language, but what an implementation does in response to that declaration is unspecified. So long as foo() raises NameError, or a subclass of it, it will be a conforming Python implementation. That's what Python 1.5 does, and I think if some competing implementation targeted 1.5 we'd still be happy to call it Python. (Although we might wonder about the author's sanity...) Implementations are free to subclass NameError, as CPython does with UnboundLocalError, but mustn't raise a completely unrelated error, or no error at all. E.g. I don't think it would be acceptable to implicitly create new names and bind them to some arbitrary default value. E.g. an implementation might do something like this: * when parsing the function, prior to compiling the byte-code, tag every name with a sigil representing whether it is local or non-local; * compile a single byte-code for name lookup; * when executing that instruction, if the name is tagged as a local, search only the local namespace, otherwise search the nonlocal, global and builtin namespaces; * when displaying names to the user (say, in tracebacks) suppress the sigil. Under this implementation, no variable actually exists until it is assigned to. This is equivalent to shifting the decision to use LOAD_FAST or LOAD_GLOBAL to runtime rather than compile time, so it would probably hurt performance rather than increase it, but it would still be a conforming implementation. But of course I'm not Guido, and he has the final word on what counts as acceptable behaviour. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: multitask http server (single-process multi-connection HTTP server)
On Jul 12, 9:52 pm, Gelonida wrote: > Hi lkcl, > > Do you have any documentation or overview for your project? git clone git://pyjs.org/git/multitaskhttpd.git i only started it today, but yes, there's a README. the primary reason it's being developed is because GNUmed are looking to create a web service but they want to use the same psycopg2-based middleware that's taken them pretty much forever to develop. see my reply to geremy condra for more details. if this turns out to be something that _really_ hasn't been done before, then i'm happy for other people to pitch in and help out. > Questions I would be interested in: > - List of features already working * simple HTTP GET of files and subdirs (because i blatantly copied SimpleHTTPServer.py) * JSONRPC services (i blatantly copied SimpleJSONRPCServer.py, it's something i found, it's based on SimpleXMLRPCService.py) > - list of features under development the time between "under development" and "in future" is so short it's hardly worthwhile stating. i added JSONRPC in about 90 minutes for example. tomorrow i'll add HTTP POST multi-part forms and it will take me about... 50 mins i should imagine, by looking at something like turbogears or django. i'm not going to "waste time reinventing" stuff when i can pretty much cut/paste it. web servers have been _done_ already - it's just that cooperative multitasking seems most definitely _not_ to have been done before. > - list of features being in in the near future * HTTP POST with multi-part forms (just like standard web frameworks) * a better API once i have a clearer idea of what's needed * use of regex matching on apps, just like django urls.py l. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help choosing license for new projects
On Mon, 12 Jul 2010 17:00:22 -0500, Jake b wrote: > I'm starting a new python code project. What license do you suggest? I > am searching, but I'm not finding a simple comparison of licenses. So I > don't know which to use. Maybe MIT or Apache or LGPL or BSD? http://www.dwheeler.com/essays/gpl-compatible.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Mon, 12 Jul 2010 22:57:10 +0200, Alf P. Steinbach /Usenet wrote: > Existence of a variable means, among other things, that > >* You can use the value, with guaranteed effect (either unassigned >exception > or you get a proper value): in particular, you won't be accessing a > global if you're using the name of a local declared by a later > assignment. That is too strong. Given the global code: x (where x doesn't exist in the global namespace, and therefore does not exist, as you agreed earlier) Python promises to raise NameError. By the above definition, this counts as "variable x exists". But surely that is undesirable -- that implies that *all* variables exist. Even $...@*@( is a variable that exists, as that is guaranteed to raise SyntaxError. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* Steven D'Aprano, on 13.07.2010 01:50: On Mon, 12 Jul 2010 22:57:10 +0200, Alf P. Steinbach /Usenet wrote: Existence of a variable means, among other things, that * You can use the value, with guaranteed effect (either unassigned exception or you get a proper value): in particular, you won't be accessing a global if you're using the name of a local declared by a later assignment. That is too strong. Given the global code: x (where x doesn't exist in the global namespace, and therefore does not exist, as you agreed earlier) Python promises to raise NameError. By the above definition, this counts as "variable x exists". But surely that is undesirable -- that implies that *all* variables exist. Even $...@*@( is a variable that exists, as that is guaranteed to raise SyntaxError. Hm, I already answered someone else here committing that logic error. In one case an exception is generated by removing a variable. In the other case an exception is generated by adding a variable. Cheers & hth., - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
* Steven D'Aprano, on 13.07.2010 01:34: On Mon, 12 Jul 2010 20:28:49 +0200, Alf P. Steinbach /Usenet wrote: As I see it it doesn't matter whether the implementation is CPython call frame slots or that mechanism called something else or a different mechanism called the same or a different mechanism called something different; what IMO matters is same semantics, that any assignment to a variable within a routine serves as a compile time declaration, creating that local variable in advance, unless, with Python 3.x., that name has been declared as a 'global' or 'nonlocal'. So, this is a possible point of disagreement. I say the semantics of local variable creation are part of the language definition, but I get the /impression/ that maybe you think it's CPython-specific, that e.g. def foo(): x x = 0 might not raise an unassigned variable exception with some conforming Python implementation, i.e. different effect for same code with different implementations, that this is at least /unspecified behavior/ in Python? Almost. I believe that "any assignment to a variable within a routine serves as a compile time declaration" is a promise of the language, but what an implementation does in response to that declaration is unspecified. So long as foo() raises NameError, or a subclass of it, it will be a conforming Python implementation. That's what Python 1.5 does, and I think if some competing implementation targeted 1.5 we'd still be happy to call it Python. (Although we might wonder about the author's sanity...) Implementations are free to subclass NameError, as CPython does with UnboundLocalError, but mustn't raise a completely unrelated error, or no error at all. E.g. I don't think it would be acceptable to implicitly create new names and bind them to some arbitrary default value. E.g. an implementation might do something like this: * when parsing the function, prior to compiling the byte-code, tag every name with a sigil representing whether it is local or non-local; * compile a single byte-code for name lookup; * when executing that instruction, if the name is tagged as a local, search only the local namespace, otherwise search the nonlocal, global and builtin namespaces; * when displaying names to the user (say, in tracebacks) suppress the sigil. Under this implementation, no variable actually exists until it is assigned to. This is equivalent to shifting the decision to use LOAD_FAST or LOAD_GLOBAL to runtime rather than compile time, so it would probably hurt performance rather than increase it, but it would still be a conforming implementation. But of course I'm not Guido, and he has the final word on what counts as acceptable behaviour. The 3.1.1 docs explicitly require UnboundLocalError (I just checked). So, at least for 3.x it is not an implementation detail. Anyway, your phrase "actually exist" presumably refers to storage allocation. That is an implementation detail. As a similar implementation scheme, a compiler can in certain cases detect that a variable is only assigned once, and substitute the value whereever that variable is used, not allocating any storage for it. This is the case in Python, in C++ and in almost any language. We don't start doubting the existence of variables in general (as some in the Python community do) on such grounds. More to the point of this sub-thread, it would be impossible to reason about things if one had to take into account the particular implementation's details at all times. Doing that renders most terms, including "exist", pretty meaningless and useless, since you would have to check whether each particular variable was optimized away or not: for the purpose of discussing existence in Python, what matters is portable effect. Summing up, how CPython implements the required semantics, is irrelevant. :-) Cheers from Norway, - Alf -- blog at http://alfps.wordpress.com> -- http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
On Mon, 12 Jul 2010 12:34:46 +0200, Jean-Michel Pichavant wrote: > Well, actually some people might think otherwise. While I disagree with > the OP flaming style, one could argue that muting an integer into a > boolean makes no sense (I'm one of them). You can still do it, but there > is no "right" way to do it. > You can decide that everything else than 0 is True, but you could also > pickup the integer 3 as false value, it would work as well since it > makes no sense. This is just an arbitrary definition. Choosing 3 as a false value would be arbitrary, but the choice of 0 is anything but arbitrary. The distinction that Python makes is between values which are Something (true values) and those which are Nothing (false values). Python has an infinite number of ways of spelling Something: True, 1, 2, 3.1415, "abc", (2, 4), [None, 1, "A"], ... and a smaller number of ways of spelling Nothing: False, None, 0, 0.0, "", (), [], ... The fact that False == 0 (as opposed to, say, [] != 0) is due to the need for backwards compatibility. That bools are implemented as a subclass of int is a historical accident. The fundamental distinction in Python is between objects which are Something and those that are Nothing, and that's not an arbitrary distinction, it's a very deep distinction. This is why virtually all low-level languages treat 0 as a false flag and 1 (or sometimes -1) as a true flag. I say "virtually all", not because I know of any exceptions, but because in the history of computer languages you can probably find every design mistake, arbitrary choice, and perverse decision imaginable made by *somebody*. Consider branch statements. Forth jumps to the "true" branch on any integer flag, and to the "false" branch on 0, but the canonical true value is either 1 ( 1 in binary) or -1 ( ). Early versions of BASIC used -1 as true and 0 as false. With Pascal's strong type-checking, you were forced to use the boolean type in branches, but (if I recall correctly) the language guaranteed that false was 0 and true was 1: a packed array of bools would use a 0 bit for false and 1 for true, and an unpacked array would use eight zero bits versus seven zeroes and an one. So there's historical precedent from other languages, backwards compatibility with early Python versions, and a fundamental philosophical distinction all in favour of using 0 for false. Not arbitrary at all. > I prefere to explicitly write what I want to test: > > if myInt <> 0: I would argue against that. Why do you, the coder, care about the specific details of treating ints in a boolean context? The int type itself knows, leave the decision to it. Sure, in the specific case of ints, the distinction is so fundamental, so basic, and so unlikely to change, that there's no real harm in the explicit test. But consider some other type: if myValue.count <= 0 and myValue.next is None and myValue.blob == "": # myValue is considered false versus: if not myValue: Which would you prefer? I think the choice is obvious: the type knows whether it is equivalent to true or false, leave it up to the object to decide. Why bother making an exception for ints, or strings? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy questions from a python beginner
On Jul 12, 2010, at 15:55 , Alf P. Steinbach /Usenet wrote: > * Rami Chowdhury, on 13.07.2010 00:14: >> Perhaps I'm misunderstanding, but ... >> >> On Jul 12, 2010, at 13:57 , Alf P. Steinbach /Usenet wrote: >>> >>> Existence of a variable means, among other things, that >>> >>> * You can use the value, with guaranteed effect (either unassigned >>> exception >>>or you get a proper value) >> >> Surely by that definition any variable in any Python program "exists" -- you >> are guaranteed to get one of NameError, UnboundLocalError, or a value. That >> seems to argue away the meaning of the word entirely, and renders it not >> particularly useful. > > No, you're conflating non-existence (NameError) with accessing the value of > an existing but unassigned variable (UnboundLocalError). It is like arguing > that vacuum is the same as cement because sticking your head into it for ten > minutes or so yields an effect -- you're dead -- that in many ways is > just about the same. Right -- but you're playing with the definition of "existence" there, and since you're not using it quite consistently, I wasn't sure what you meant. Your discussion of the language reference below helps clear it up. > >>> How the Python implementation implements that is an implementation detail. >>> >>> In short, how CPython does things is completely irrelevant to the language's >> semantics, so you're conflating things here. >>> >> >> As I'd understood the previous discussion, it is the CPython implementation >> that reserves local names and produces UnboundLocalErrors. The language >> semantics don't call for it, and another implementation might choose to >> handle >> function locals the same way as globals, through a namespace dictionary -- in >> which case the variable *wouldn't* exist in any way, shape, or form until it >> was assigned to. >> >> What am I getting wrong here? > > The bit about the language semantics not specifying the effect. > > From the 3.1.1 language reference §4.1: > > "When a name is not found at all, a NameError exception is raised. If the > name refers to a local variable that has not been bound, a UnboundLocalError > exception is raised. UnboundLocalError is a subclass of NameError." > > And it goes on to elaborate on that, a little later: > > "If a name binding operation occurs anywhere within a code block, all uses of > the name within the block are treated as references to the current block. > This can lead to errors when a name is used within a block before it is > bound. This rule is subtle. Python lacks declarations and allows name binding > operations to occur anywhere within a code block. The local variables of a > code block can be determined by scanning the entire text of the block for > name binding operations." Ah, interesting. Thank you for pointing that out -- I didn't know that. I notice the same paragraph is in the 2.7 reference, so it presumably holds for 2.x implementations as well. > This is the usual reaction of the religious when exposed to reality. > > Cheers & hth. It does, thank you. Although the repeated references to the "religious" and their "refusal to accept reality" are less than helpful. > > -- > blog at http://alfps.wordpress.com> > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
Steven D'Aprano writes: > This is why virtually all low-level languages treat 0 as a false ... OK, but is Python a low-level language, and if not, why are low-level languages appropriate examples to follow? >> if myInt <> 0: > > I would argue against that. Why do you, the coder, care about the > specific details of treating ints in a boolean context? The int type > itself knows, leave the decision to it. There is a horrible (IMO) thing that Perl, Lua, and Javascript all do, which is automatically convert strings to numbers, so "12"+3 = 15. Python has the good sense to throw a type error if you attempt such an addition, but it goes and converts various types to bool automatically, which is more Perl-like than I really enjoy. In fact Python 3 added yet another automatic conversion, of int to float on division, so 1/2 = 0.5. Obviously it's a point in the design space where various decisions are possible, but I can get behind the "explicit is better than implicit" idea and say that none of those conversions should be automatic, and if 1/2 = 0 was confusing people in Python 2 enough to justify changing divison semantics in Python 3, the preferable change would be for int division to raise TypeError rather than quietly converting to float. The same thing goes for bool conversion, though we are all used to it by now, and it would be way too disruptive a change. > if myValue.count <= 0 and myValue.next is None and myValue.blob == "": > # myValue is considered false > versus: > if not myValue: > Which would you prefer? I'd personally prefer if not bool(myValue): which would call the myValue's __bool__ method if it chose to implement one. Explicit is better than implicit. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete "\n"
On Mon, Jul 12, 2010 at 2:33 PM, Jia Hu wrote:
> Thank you. It works now.
>
> if I use 'print' to print the whole list, 'print' will add newline
> at the end of the list but not each item in the list. right?
>
> For the code:
> for line in fileName:
> line = line.rstrip('\n')
> I think this will affect 'fileName' because it assign the value to 'line' ?
No it does not. Python assignments never modify anything other than
the enclosing namespace.
"for line in fileName" reads a line from the file and creates a
string. That string resides in memory somewhere, who knows where. It
does not reside inside fileName- it is a separate object. That string
is then bound to the name "line" in the current namespace (the
module's namespace in this case). Variables in Python are just entries
in a dictionary. In fact, you can do globals()["line"] and it will
return the string associated with that name.
line.rstrip("\n") gets the object associated with the name "line" and
accesses the object with the name "rstrip" that's associated with the
object named "line". It then calls that object (in this case a
builtin_function_or_method object) with the string "\n" as a
parameter.
rstrip then generates a new string.
The line = (that new string that was just generated) associates the
new string with the name "line". The old string hasn't changed at all
(in fact, the object will get deleted almost immediately since it's
reference count just dropped to 0). And the file hasn't changed
either.
> But when I print fileName, "\n" still exists at each item in the list.
>
> Because each line in my txt file are numeric values. is there any other
> better way to get each
> numerical value at each line? for example using numpy or changing string
> list to numerical list?
>
> Thank you for help.
>
> On Mon, Jul 12, 2010 at 4:45 PM, Chris Rebert wrote:
>>
>> On Mon, Jul 12, 2010 at 1:27 PM, Jia Hu wrote:
>> > Hi, I just want to delete "\n" at each line. My operating system is
>> > ubuntu
>> > 9.1. The code is as follows
>> >
>> > #!/usr/bin/python
>> > import string
>> > fileName=open('Direct_Irr.txt', 'r') # read file
>> > directIrr = fileName.readlines()
>> > fileName.close()
>> > for line in directIrr:
>> > line.rstrip('\n')
>> > print directIrr
>> >
>> > But I found there is still "\n" . Could someone help me why it is not
>> > correct?
>>
>> .rstrip() returns a *new* string without trailing whitespace (which
>> you are currently then throwing away); it does *not* modify string
>> objects in-place. Python strings objects are entirely immutable and
>> unmodifiable; all operations on them merely produce /new/ strings.
>>
>> Assuming you still want to use .readlines(), you'd do:
>> directIrr = fileName.readlines()
>> fileName.close()
>> directIrr = [line.rstrip('\n') for line in directIrr]
>> print directIrr
>>
>> For how third line works, google "python list comprehensions".
>>
>> Cheers,
>> Chris
>> --
>> http://blog.rebertia.com
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list
write a .txt file
Hello:
I have a problem about how to generate a specific.txt file. I use the
following code:
#!/usr/bin/python
# OS: Ubuntu
import subprocess
fileName = open ('final.txt', 'a')
fileName.write ('%s %s %s \n' % (12,25,9))
desLrr = subprocess.Popen('echo "hello" >> final.txt ', shell=True)
fileName.seek(0,2)
fileName.write ('%s %s %s \n' % (85,25,12))
fileName.close()
The above code generates the following result:
12 25 9
85 25 12
hello
What I want is:
12 25 9
hello
85 25 12
Could someone provies some suggestions about this problem?
Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
On Mon, Jul 12, 2010 at 6:18 PM, Steven D'Aprano wrote: >> I prefere to explicitly write what I want to test: >> >> if myInt <> 0: > > I would argue against that. Why do you, the coder, care about the > specific details of treating ints in a boolean context? The int type > itself knows, leave the decision to it. I think you're missing the point. He's not using ints in a boolean context. If it were a boolean context, he would be using bools in the first place. What he is objecting to is the practice of testing for special cases of ints (i.e. 0) by treating them as bools. The specific details of converting ints to bools are very much relevant here; as long as 0 is false, it works. If -1 is false (a semantic I have actually seen used), then it does not. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Check if a command is valid
Hello,
I have to figure out if a string is callable on a Linux system. I'm
actually doing this:
def is_valid_command(command):
retcode = 100 # initialize
if command:
retcode = subprocess.call(command, shell=True)
if retcode is 0:
print "Valid command."
else:
print "Looks not so good..."
is_valid_command("ls")
Never mind the code, because this is not the original.
The side effect of subprocess.call() is that it *actually* executes
it, but I just need the return code. What are better ways of doing
this?
--
http://mail.python.org/mailman/listinfo/python-list
Re: any issues with long running python apps?
On 7/12/10 10:16 AM, John Nagle wrote: >Yesterday, I was running a CNC plasma cutter that's controlled > by Windows XP. This is a machine that moves around a plasma torch that > cuts thick steel plate. A "New Java update is available" window > popped up while I was working. Not good. That's downright frightening. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
On Mon, Jul 12, 2010 at 6:36 PM, Paul Rubin wrote: > There is a horrible (IMO) thing that Perl, Lua, and Javascript all do, > which is automatically convert strings to numbers, so "12"+3 = 15. > Python has the good sense to throw a type error if you attempt such an > addition, but it goes and converts various types to bool automatically, > which is more Perl-like than I really enjoy. In fact Python 3 added yet > another automatic conversion, of int to float on division, so 1/2 = 0.5. > > Obviously it's a point in the design space where various decisions are > possible, but I can get behind the "explicit is better than implicit" > idea and say that none of those conversions should be automatic, and if > 1/2 = 0 was confusing people in Python 2 enough to justify changing > divison semantics in Python 3, the preferable change would be for int > division to raise TypeError rather than quietly converting to float. I don't think it's any more egregious than automatic conversions of mixed-type expressions, such as 3 + 4.5. If you don't want your ints automatically converted to floats on division, then use the integer division operator. 1 // 2 is still 0 in Python 3. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: write a .txt file
Jia Hu wrote:
Hello:
I have a problem about how to generate a specific.txt file. I use the
following code:
#!/usr/bin/python
# OS: Ubuntu
import subprocess
fileName = open ('final.txt', 'a')
fileName.write ('%s %s %s \n' % (12,25,9))
desLrr = subprocess.Popen('echo "hello" >> final.txt ', shell=True)
fileName.seek(0,2)
fileName.write ('%s %s %s \n' % (85,25,12))
fileName.close()
The above code generates the following result:
12 25 9
85 25 12
hello
What I want is:
12 25 9
hello
85 25 12
Could someone provies some suggestions about this problem?
Thank you.
When "echo" is called the file is still open, so the might not be able
to write to it. Try closing the file before starting the subprocess and
then reopen it afterwards.
By the way, it slightly confusing that you call the variable "fileName",
but it doesn't contain the name of a file! :-)
--
http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
Ian Kelly writes: > I don't think it's any more egregious than automatic conversions of > mixed-type expressions, such as 3 + 4.5. That could also be explicit: float(3) + 4.5, or 3 + int(4.5). > If you don't want your ints automatically converted to floats on > division, then use the integer division operator. 1 // 2 is still 0 > in Python 3. Sure, I do that, but the issue was that 1/2 was confusing newbies who don't understand the different characteristics of int and floating types. If the idea is to change Python to fix this problem in a newbie-friendly way, the right fix is to create enlightment by raising an exception that points out the problem, not sweep it under the rug with an automatic conversion. -- http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
On 12Jul2010 17:36, Paul Rubin wrote:
| Steven D'Aprano writes:
| > This is why virtually all low-level languages treat 0 as a false ...
|
| OK, but is Python a low-level language,
Not particularly, but true/false and Boolean login are low level ideas.
If it works well in a low level language (where all you might have are
ints of various flavours and thus some equivalence notion is required),
why would you _change_ the conventions in a high level language without
a compelling reason? The more commonality in concepts there are, for
all that they are just conventions, the easier it is remember how to
do things.
| and if not, why are low-level
| languages appropriate examples to follow?
They may not be in any inherent sense, but they are examples and if the
usage doesn't cause pain are they inappropriate?
Steven:
| >> if myInt <> 0:
| >
| > I would argue against that. Why do you, the coder, care about the
| > specific details of treating ints in a boolean context? The int type
| > itself knows, leave the decision to it.
[...snip...]
This I'm only halfway with. I, the coder, _must_ know. The "if"
statement has an intent, and I need to know that "if myInt:" matches my
intent. Of course, using the right idioms it will match a lot of the
time. But I've certainly been bitten by writing:
if myDict:
intending:
if myDict is not None:
but also getting:
if myDict != {}:
Clearly the fault was mine, but I, the coder, _must_ care about the
details of using non-Booleans in a Boolean context.
Cheers,
--
Cameron Simpson DoD#743
http://www.cskk.ezoshosting.com/cs/
It is Texas law that when two trains meet each other at a railroad crossing,
each shall come to a full stop, and neither shall proceed until the other has
gone.
--
http://mail.python.org/mailman/listinfo/python-list
Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!
On Mon, Jul 12, 2010 at 7:14 PM, Paul Rubin wrote: > Ian Kelly writes: > > I don't think it's any more egregious than automatic conversions of > > mixed-type expressions, such as 3 + 4.5. > > That could also be explicit: float(3) + 4.5, or 3 + int(4.5). > > > If you don't want your ints automatically converted to floats on > > division, then use the integer division operator. 1 // 2 is still 0 > > in Python 3. > > Sure, I do that, but the issue was that 1/2 was confusing newbies who > don't understand the different characteristics of int and floating > types. If the idea is to change Python to fix this problem in a > newbie-friendly way, the right fix is to create enlightment by raising > an exception that points out the problem, not sweep it under the rug > with an automatic conversion. > Behind this automatic conversion is the concept that there is really one type: Number. The fact that the language has both int and float is merely as there is no good, solid way of storing the Number type, and thus we have float, Decimal, Rational, and probably other less common types. Calculating 1/2 does not give you 0, 1/10 won't give you 0.10001 (or whatever the number stored in float is). The fact that integers and real numbers are separate in the language is an optimization and intended to improve functionality while providing a simple default (you can choose to use Decimal instead of float if you know you will be dealing with decimal numbers). Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
