Re: Python is DOOMED! Again!
Rustom Mody writes: > However Peyton Jones is known to have said that for Haskell, > Haskell is on a Damas-Milner cusp He's talking about the hairy recent stuff that edge Haskell towards dependent types. E.g. type families (type-level functions) plus type-level numbers, etc. I don't think anyone has suggested pressing Python type hints to anywhere near such lengths. Really, I think the examples to look to are Erlang (Dialyzer) and Racket (Typed Racket), not Haskell. Clojure's static types are adapted from Racket's and should work in about the same way. These (unlike Haskell) are all examples of optional static types, where you can mix static and dynamic code or leave out all the annotations if you want. I have to say that my personal experience with the Erlang dialyzer wasn't all that great, but I was new to it and I think it's probably more effective when used the "right" way, i.e. by people who are more used to it than I was. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On 22/01/2015 7:37 PM, Nicholas Cole wrote: Still, it would have been nicer to be able to write something like this (where the Unions are implicit): Coincidentally, you also demonstrate what makes this a lesser idea :) def handle_employees(employees, rasie): ^ # raise: float, Sequence[float] ^ There is a distinct advantage in not repeating yourself. -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python Events Calendar - Please submit your 2015 events
Hi all I wrote this script that can read the Python Calendars and shows the geolocated info on a map and on a timeline. http://lmorillas.github.io/python_events/ Enjoy Saludos, -- luismiguel (@lmorillas) 2015-01-13 22:18 GMT+01:00 M.-A. Lemburg : > [Please help spread the word by forwarding to other relevant mailing lists, > user groups, etc. world-wide; thanks :-)] > > > ANNOUNCING > > Python Events Calendars - Please submit your 2015 events > >maintained by the Python Software Foundation (PSF) > and a group of volunteers > > > INTRODUCTION > > As some of you may know, the PSF has a team of volunteers who are > maintaining a set of central Python event calendars. We currently have > two calendars in place: > > * Python Events Calendar - meant for conferences and larger gatherings >focusing on Python or a related technology (in whole or in part) > > * Python User Group Calendar - meant for user group events and other >smaller local events > > The calendars are displayed on http://pycon.org/ and also on the new > https://python.org/ website at https://www.python.org/events/python-events/ > and https://www.python.org/events/python-user-group/. > > You can subscribe to the calendars using iCal and RSS feeds and also > embed the calendar widgets on your sites. We have also added a > Twitter feed @PythonEvents to get immediate updates whenever a new > event is added. Please see our wiki page for details: > >https://wiki.python.org/moin/PythonEventsCalendar > > The calendars are open to the world-wide Python community, so you > can have local user group events, as well as regional and > international conference events added to the calendars. > > > NEWS > > Looking back on 2014, the calendars have proven to be a great tool > for the Python community to connect, with more than 60 conferences > and more than a hundred of user group events listed. > > We would therefore like to encourage everyone to submit their > 2015 events, so that the Python community can get a better overview > over what's happening in Python land. > > > ADDING EVENTS > > Please see the instructions at > https://wiki.python.org/moin/PythonEventsCalendar#Available_Calendars > for details on how to > submit an event. We've made it really easy for you: just need to send > an email to our team address using the email template we > provide for this. Thanks. > > > MORE INFORMATION > > More information on the calendars, the URLs, feed links, IDs, embedding, > etc. is available on the wiki: > > https://wiki.python.org/moin/PythonEventsCalendar > > Enjoy, > -- > Marc-Andre Lemburg > Director > Python Software Foundation > http://www.python.org/psf/ > > -- > https://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
Chris Angelico wrote: > On Fri, Jan 23, 2015 at 1:16 AM, Steven D'Aprano > wrote: >> Mario Figueiredo wrote: >> >>> def handle_employees(emp: Union[Employee, Sequence[Employee]], raise: >>> Union[float, Sequence[float]]) -> Union[Employee, Sequence[Employee], >>> None]: >> >> Using >> floats for money is Just Wrong and anyone who does so should have their >> licence to program taken away. > > But using a float to specify a percentage raise that an employee (or > class of employees) gets would be reasonable. I don't think that a raise of 0.10001 (10%), 0.035003 (3.5%) or 0.070007 (7%) is quite what people intended. :-) (Don't use binary floating point numbers for anything related to money. Just don't.) -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python Events Calendar - Please submit your 2015 events
On 23.01.2015 11:54, Luis Miguel Morillas wrote: > Hi all > > I wrote this script that can read the Python Calendars and shows the > geolocated info on a map and on a timeline. > > http://lmorillas.github.io/python_events/ Very cool :-) Thanks. I'll add a link to our wiki page. > Enjoy > > Saludos, > > -- luismiguel (@lmorillas) > > > 2015-01-13 22:18 GMT+01:00 M.-A. Lemburg : >> [Please help spread the word by forwarding to other relevant mailing lists, >> user groups, etc. world-wide; thanks :-)] >> >> >> ANNOUNCING >> >> Python Events Calendars - Please submit your 2015 events >> >>maintained by the Python Software Foundation (PSF) >> and a group of volunteers >> >> >> INTRODUCTION >> >> As some of you may know, the PSF has a team of volunteers who are >> maintaining a set of central Python event calendars. We currently have >> two calendars in place: >> >> * Python Events Calendar - meant for conferences and larger gatherings >>focusing on Python or a related technology (in whole or in part) >> >> * Python User Group Calendar - meant for user group events and other >>smaller local events >> >> The calendars are displayed on http://pycon.org/ and also on the new >> https://python.org/ website at https://www.python.org/events/python-events/ >> and https://www.python.org/events/python-user-group/. >> >> You can subscribe to the calendars using iCal and RSS feeds and also >> embed the calendar widgets on your sites. We have also added a >> Twitter feed @PythonEvents to get immediate updates whenever a new >> event is added. Please see our wiki page for details: >> >>https://wiki.python.org/moin/PythonEventsCalendar >> >> The calendars are open to the world-wide Python community, so you >> can have local user group events, as well as regional and >> international conference events added to the calendars. >> >> >> NEWS >> >> Looking back on 2014, the calendars have proven to be a great tool >> for the Python community to connect, with more than 60 conferences >> and more than a hundred of user group events listed. >> >> We would therefore like to encourage everyone to submit their >> 2015 events, so that the Python community can get a better overview >> over what's happening in Python land. >> >> >> ADDING EVENTS >> >> Please see the instructions at >> https://wiki.python.org/moin/PythonEventsCalendar#Available_Calendars >> for details on how to >> submit an event. We've made it really easy for you: just need to send >> an email to our team address using the email template we >> provide for this. Thanks. >> >> >> MORE INFORMATION >> >> More information on the calendars, the URLs, feed links, IDs, embedding, >> etc. is available on the wiki: >> >> https://wiki.python.org/moin/PythonEventsCalendar >> >> Enjoy, >> -- >> Marc-Andre Lemburg >> Director >> Python Software Foundation >> http://www.python.org/psf/ >> >> -- >> https://mail.python.org/mailman/listinfo/python-announce-list >> >> Support the Python Software Foundation: >> http://www.python.org/psf/donations/ -- Marc-Andre Lemburg Director Python Software Foundation http://www.python.org/psf/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On Fri, Jan 23, 2015 at 9:59 PM, Steven D'Aprano wrote: > I don't think that a raise of 0.10001 (10%), > 0.035003 (3.5%) or 0.070007 (7%) is quite what > people intended. > > :-) I also don't think it'll make any appreciable difference, especially if the actual salary is stored as an integer :-) > (Don't use binary floating point numbers for anything related to money. Just > don't.) While I generally agree, it's not quite as hard-and-fast as that. It's just important to know that binary floating point can't accurately represent many commonly-used real numbers... the same consideration that they always need. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On 01/15/2015 09:05 AM, Ian Kelly wrote: On Thu, Jan 15, 2015 at 12:23 AM, Andrew Robinson wrote: Can you name any other language that *does* allow subclassing of booleans or creation of new boolean values? Yes. Several off the top of my head -- and I have mentioned these before. They generally come with the extra subclasses pre-created and the user doesn't get to create the classes, but only use them; none the less -- they have more than two values with which to do logic equations with. VHDL, Verilog, HDL, Silos III, and there are IEEE variants also. C/C++ historically allowed you to do it with instances included, although I am not sure it still does. Sorry, let me rehprase my question. Of course there will be special-purpose languages that allow you to do interesting things with the logic values and operators. Can you name any other *general-purpose* language that allows subclassing of booleans or creation of new boolean values? If not, it seems rather unfair to single out Python and marvel that this isn't allowed when it's actually quite normal to disallow it. Unless you care to provide an example, I am fairly sure your claim of C/C++ is wrong. The bool type in C++ is a primitive type, none of which can be inherited from. C doesn't even have a bool type; at most you have macros for true and false to 1 and 0, so the "booleans" there are just ordinary integers. Ian, I agree with you mostly; there is good reason to pick on other languages, too, with respect to what a bool is. Although, I have to laugh -- Verilog can syntheze a CPU -- implement memory -- and then load a program and run python on the virtual machine. When the pentium was first developed, I watched as Intel actually booted up MS-DOS under using Xilinx chips to run the verilog program's output they could physically run anything a pentium processor could run. That's *IS* what I consider "general purpose". But you're sort of confounding my need for type information in my new class as a way to advertise compatability with bool, with subclassing -- which is only one way that I was exploring to get the 'type' name attached to the new object; That's a mistake that D'Aprano seems to be repetitively making as well. But please note: Type checking for 'bool' is only needed for legacy/compatability reasons -- but new code can use any type; so subtyping is not strictly necessary if there is another way to get the 'bool' type attached to my return object for advertising purposes; for what I am interested in is an object who presents as bool for legacy code, but new code can convert it to anything at all.. C++ *DOES* allow the necessary kind of type checking and subclassing for what I need to do in spite of not having a subclass mechanism built into the language for base types; eg: C++ allows a semantic subclass to be constructed which can be typecast to a bool for compatibility, but otherwise presents extra data and the type the enhanced object reports is irrelevant. As I've mentioned before, people can do object oriented programming in C, So, to satisfy your curiosity -- I'll show you a mixed C/C++ example, where I make a semantic subclass that has five values AllFalse, PartFalse, Uncertain, PartTrue, True ; and these five values will have a typeid() of bool and be 100% compatible with legacy C++ bool; but upon request, they these 'bool' types will re-cast into a semantic subtype that provides additional certainty data. See the program at end of e-mail. It compiles with gcc 4.8.2 with no warnings; g++ filename.cc ; ./a.out But let me explain a bit more why I'm picking on Python: For even if we set the electronic engineering concerns aside that I've raised (and they are valid, as OOP is supposed to model reality, not reality be bent to match OOP) -- People's facile explanations about why Python's version of bool is the way it is -- still bothers me here in the python mail list -- because people seem to have a very wrong idea about bool's nature as a dualton being somehow justified solely by the fact that there are only two values in Boolean logic; For, singletons style programming is not justified by the number of values an object has in reality -- And I know Charles bool didn't use singletons in his algebra, -- just read his work and you'll see he never mentions them or describes them, but he does actually use dozens of *instances* of the True and False objects he was talking about -- for the obvious reason that he would have needed special mirrors, dichroic or partially silvered, to be even able to attempt to make one instance of True written on paper show up in multiple places; And that's silly to do when there's no compelling reason to do it. Yet -- people here seem to want to insist that the bool type with only two *instances* is some kind of pure re-creation of what Charles Bool did -- when clearly it isn't. It's a amalgamation of enhancements such as binary words instead o
Re: Random ALL CAPS posts on this group
Ben Finney wrote: > Chris Angelico writes: > >> On Tue, Jan 20, 2015 at 11:38 AM, Rick Johnson >> wrote: >> > That's the beauty of free speech: "We have right to be annoyed, and >> > the author has the right not to give a damn". The only alternative >> > is fascist censorship, and I'll happily endure these annoyances to >> > prevent that! >> >> Free speech also gives the freedom to not listen. > > Freedom of expression entails an obligation on the state to not quash > anyone's expression. It does not affect anyone who is not the state; it > imposes no obligation on the PSF. By this reasoning, you would be perfectly comfortable with a state of affairs where a media monopoly suppressed any and all dissenting viewpoints, provided that it was a *privately owned* monopoly and not the government. To quote Bill Cole: Here in the US, we are so schizoid and deeply opposed to government censorship that we insist on having unaccountable private parties to do it instead. Since I am pretty sure that you don't actually consider private censorship to be a good thing, perhaps we can agree that the question of free speech is a little more complicated than just the state versus non-state. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Fri, Jan 23, 2015 at 10:46 PM, Andrew Robinson wrote: > 4. and he has made bool into the default return type for base type > comparison operators; which means that general programmers expect a bool for > base types and may check for it, even if Python's built in functions do not. I don't get this. They're specifically documented as NOT being required to return a bool, so if any code is type-checking the return values, that code is buggy. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
On Fri, Jan 23, 2015 at 10:50 PM, Steven D'Aprano wrote: >> Freedom of expression entails an obligation on the state to not quash >> anyone's expression. It does not affect anyone who is not the state; it >> imposes no obligation on the PSF. > > By this reasoning, you would be perfectly comfortable with a state of > affairs where a media monopoly suppressed any and all dissenting > viewpoints, provided that it was a *privately owned* monopoly and not the > government. To quote Bill Cole: > > Here in the US, we are so schizoid and deeply opposed to > government censorship that we insist on having unaccountable > private parties to do it instead. > > > Since I am pretty sure that you don't actually consider private censorship > to be a good thing, perhaps we can agree that the question of free speech > is a little more complicated than just the state versus non-state. It's definitely not "state vs non-state". Freedom of expression should allow me to say anything I like in my own home, but it doesn't guarantee that I can walk into someone else's place of business and start insulting the customers. Or, more strictly, he has the right to throw me out, and I can't hide behind "freedom of speech" as a right to say whatever I like. But he has that right because I'm in his place of business. I'm fully allowed to leave, and say my piece somewhere else. It's even more obvious when he has to expend resources to allow my voice to be heard; not every letter to the editor will be published in the newspaper, for instance, and nobody would expect them all to be. Yes, the newspaper is quite possibly biased in its selection of which to print; that's just something you have to accept. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On 23/01/2015 11:46, Andrew Robinson wrote: Unless I've missed something all you've done is show that you haven't got the faintest idea what you're talking about. Would you either please go away before I die laughing, or tell me where you get the stuff that you're taking. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On 1/23/15, Steven D'Aprano wrote: > Terry Reedy wrote: > >> On 1/22/2015 10:59 PM, Chris Angelico wrote: >>> On Fri, Jan 23, 2015 at 2:22 PM, Terry Reedy wrote: This idea is so brilliant that it is already an option in mypy and is part of the new type-hint proposal. The separate type-hint files are called 'stub files'. >>> >>> It's worth pointing out, too, that the idea isn't panaceaic - it's >>> just another tool in the box. Any time you break related things into >>> separate places, especially separate files, the tendency for them to >>> get out of sync grows dramatically. >> >> The same could be said of putting tests in a separate file. > > I agree! > > Python has doctests, which live right there with the function. It also has > assertions, which can be considered a form of continuous testing. > > Eiffel has syntax for design-by-contract (testing pre-conditions, > post-conditions and invariants) there in the body of the function or > method: > > https://docs.eiffel.com/book/method/et-design-contract-tm-assertions-and-exceptions#Expressing_assertions > > > Contracts are a form of testing, since they are designed to be disabled in > production. Other languages with syntactic support for Design By Contract > include Clojure, Cobra, D, Mercury, Perl6 and Racket. > > Cobra is especially close to Python-like syntax, and supports unit tests as > well: > > > def sqroot(i as int) as float > require >i > 0 > ensure >result > 0 > tests >assert sqroot(25) == 5.0 > body > ... > > It would be nice to be able to include at least *some* tests right there in > the code rather than in a separate file. I completely agree. A cobra-style type hinting implementation would satisfy everyone who doesn't want to make function signatures noisy (including me) and would also satisfy those who advocate for the actual feature (type hinting) without worrying much about the implementation detail. These two groups are overlapping by the way :) In any case, I'm pretty sure it was said before, but I can't really find it anywhere, can someone tell me what the rationale is for *function signature* type hinting? I totally get type hinting in general, but why does it have to be in the function signature? Any reason for that specifically? Are there lots of folks who actually insist on the type hints being in the function signature and definitely want to see it there and not somewhere else? I'd say cobra-style type hinting would be great, but also something which is property looking: @official_type_hinting_by_the_psf( arg1: str, arg2: int, returns: bool ) def myfunction( arg1, arg2 ): return True I really like the idea that in python I don't have lots of choices in many areas, certain things are dictated. The big advantage is that when I read other people's code I know what to expect so me being restricted is a small price to pay that is totally worth it. So I'd come down on the side of the complainers in this case, the type hinting pep introduces noisy and not so readable features (I understand these are optional) which if used will make readability suffer. If there is a pep for it, people will use it, so the fact that it is optional is irrelevant, it will be used, so people will be faced with it when reading other people's code, whether they like it or not. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- https://mail.python.org/mailman/listinfo/python-list
[OT] absolute vs. relative URI
I'm maintaining a web app were the original author(s) went to a little bit of trouble to always use absolute URIs in links in the pages. First, the code checks the port number the server is listening on and extrapolates the protocol being used (http or https). Then it grabs the server value from the request and sets a more-or-less global variable 'wwwroot' something like this: if port in (443,8433) proto = 'https' else proto = 'http' wwwroot = "%s://%s/" % (proto,server) If the user orignally entered a URL with the literal IP address 10.0.0.99, then wwwroot ends up with a value of "http://10.0.0.99/"; Then, throughout the rest of the code that variable is used so that all links are absolute (including protocol, host, and absolute path): "Whatever I've never had any problems with links like that. Is there some case where that doesn't work right and I've just been stupidly lucky? -- Grant Edwards grant.b.edwardsYow! It don't mean a at THING if you ain't got gmail.comthat SWING!! -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
Grant Edwards : > I'm not an HTLM/HTTP guru, but I've tinkered with web pages for 20+ > years, and for links within sites, I've always used links either > relative to the current location or an absolute _path_ relative to the > current server: > > Whatever > > I've never had any problems with links like that. Is there some case > where that doesn't work right and I've just been stupidly lucky? An ancient HTML spec (https://tools.ietf.org/html/rfc1866>) specifies: HREF gives the URI of the head anchor of a hyperlink. It refers to the URI spec (https://tools.ietf.org/html/rfc1630>): Partial (relative) form Within a object whose URI is well defined, the URI of another object may be given in abbreviated form, where parts of the two URIs are the same. This allows objects within a group to refer to each other without requiring the space for a complete reference, and it incidentally allows the group of objects to be moved without changing any references. [...] The rules for the use of a partial name relative to the URI of the context are: [...] Bottom line: you are safe. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 5:18:32 PM UTC+5:30, Andrew Robinson wrote: > On 01/15/2015 09:05 AM, Ian Kelly wrote: > > On Thu, Jan 15, 2015 at 12:23 AM, Andrew Robinson wrote: > >> Can you name any other language that *does* allow subclassing of > >> booleans or creation of new boolean values? > >> > >> Yes. Several off the top of my head -- and I have mentioned these before. > >> They generally come with the extra subclasses pre-created and the user > >> doesn't get to create the classes, but only use them; none the less -- they > >> have more than two values with which to do logic equations with. > >> > >> VHDL, Verilog, HDL, Silos III, and there are IEEE variants also. > >> C/C++ historically allowed you to do it with instances included, although I > >> am not sure it still does. > > Sorry, let me rehprase my question. Of course there will be > > special-purpose languages that allow you to do interesting things with > > the logic values and operators. Can you name any other > > *general-purpose* language that allows subclassing of booleans or > > creation of new boolean values? If not, it seems rather unfair to > > single out Python and marvel that this isn't allowed when it's > > actually quite normal to disallow it. Unless you care to provide an > > example, I am fairly sure your claim of C/C++ is wrong. The bool type > > in C++ is a primitive type, none of which can be inherited from. C > > doesn't even have a bool type; at most you have macros for true and > > false to 1 and 0, so the "booleans" there are just ordinary integers. > Ian, > I agree with you mostly; there is good reason to pick on other > languages, too, with respect to what a bool is. > > Although, I have to laugh -- Verilog can syntheze a CPU -- implement > memory -- and then load a program and run python on the virtual > machine. When the pentium was first developed, I watched as Intel > actually booted up MS-DOS under using Xilinx chips to run the verilog > program's output they could physically run anything a pentium processor > could run. That's *IS* what I consider "general purpose". > > But you're sort of confounding my need for type information in my new > class as a way to advertise compatability with bool, with subclassing -- > which is only one way that I was exploring to get the 'type' name > attached to the new object; That's a mistake that D'Aprano seems to be > repetitively making as well. > But please note: Type checking for 'bool' is only needed for > legacy/compatability reasons -- but new code can use any type; so > subtyping is not strictly necessary if there is another way to get the > 'bool' type attached to my return object for advertising purposes; for > what I am interested in is an object who presents as bool for legacy > code, but new code can convert it to anything at all.. > > C++ *DOES* allow the necessary kind of type checking and subclassing for > what I need to do in spite of not having a subclass mechanism built into > the language for base types; eg: C++ allows a semantic subclass to be > constructed which can be typecast to a bool for compatibility, but > otherwise presents extra data and the type the enhanced object reports > is irrelevant. As I've mentioned before, people can do object oriented > programming in C, So, to satisfy your curiosity -- I'll show you a > mixed C/C++ example, where I make a semantic subclass that has five > values AllFalse, PartFalse, Uncertain, PartTrue, True ; and these five > values will have a typeid() of bool and be 100% compatible with legacy > C++ bool; but upon request, they these 'bool' types will re-cast into a > semantic subtype that provides additional certainty data. > > See the program at end of e-mail. It compiles with gcc 4.8.2 with no > warnings; g++ filename.cc ; ./a.out > > But let me explain a bit more why I'm picking on Python: For even if we > set the electronic engineering concerns aside that I've raised (and they > are valid, as OOP is supposed to model reality, not reality be bent to > match OOP) -- People's facile explanations about why Python's version of > bool is the way it is -- still bothers me here in the python mail list > -- because people seem to have a very wrong idea about bool's nature as > a dualton being somehow justified solely by the fact that there are only > two values in Boolean logic; For, singletons style programming is not > justified by the number of values an object has in reality -- And I know > Charles bool didn't use singletons in his algebra, -- just read his > work and you'll see he never mentions them or describes them, but he > does actually use dozens of *instances* of the True and False objects he > was talking about -- for the obvious reason that he would have needed > special mirrors, dichroic or partially silvered, to be even able to > attempt to make one instance of True written on paper show up in > multiple places; And that's silly to do when there's
Re: [OT] absolute vs. relative URI
On 2015-01-23, Marko Rauhamaa wrote: > Grant Edwards : > >> I'm not an HTLM/HTTP guru, but I've tinkered with web pages for 20+ >> years, and for links within sites, I've always used links either >> relative to the current location or an absolute _path_ relative to the >> current server: >> >> Whatever >> >> I've never had any problems with links like that. Is there some case >> where that doesn't work right and I've just been stupidly lucky? > > An ancient HTML spec (https://tools.ietf.org/html/rfc1866>) > specifies: [...] > It refers to the URI spec (https://tools.ietf.org/html/rfc1630>): [...] > > Bottom line: you are safe. Thanks, I was pretty sure that was the case. But, I'm still baffled why the original author(s) went to the extra work to always generate absolute URIs. The pages were originally developed by a web development company we contracted to do the initial design for us. We were _assuming_ they knew more about that sort of thing than we old-school EE types. [I must admit that I have learned a lot from their code about how to use CSS to avoid putting layout/presentation info directly in the HTML tags the way we did in days of yore.] -- Grant Edwards grant.b.edwardsYow! I have a TINY BOWL in at my HEAD gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On 2015-01-22, Ian Kelly wrote: > On Thu, Jan 22, 2015 at 10:13 AM, Automn wrote: >> The graphics have been licensed for this. > > Really? I'm surprised Square-Enix would even give consideration to > licensing something like this. The graphics have all been purchased. I forgot to tell that the game and its codebase are GPL version 2 and PFL 2.0. -- my blog : http://thediaryofelvishhealer.blogspot.com/ Time heals. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On Fri, Jan 23, 2015 at 4:40 PM, Grant Edwards wrote: > On 2015-01-23, Marko Rauhamaa wrote: >> Grant Edwards : >> >>> I'm not an HTLM/HTTP guru, but I've tinkered with web pages for 20+ >>> years, and for links within sites, I've always used links either >>> relative to the current location or an absolute _path_ relative to the >>> current server: >>> >>> Whatever >>> >>> I've never had any problems with links like that. Is there some case >>> where that doesn't work right and I've just been stupidly lucky? >> >> An ancient HTML spec (https://tools.ietf.org/html/rfc1866>) >> specifies: > [...] >> It refers to the URI spec (https://tools.ietf.org/html/rfc1630>): > [...] >> >> Bottom line: you are safe. Technically, there is one way to break things: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base However, nobody really uses that. Determining the protocol and server URL is a lot of effort, but it does not give any advantages over plain "/Whatever". Moreover, it would be safer and more future-proof to use a protocol-relative "//example.com/Whatever" URL instead of determining the protocol by ports (why 8433? I can serve (insecure) HTTP there; hell: I can be a complete jerk and swap ports 80 and 443!). But, this webapp completely ignores a pitfall in the process: it assumes the app lives in the web server root. You can easily change this via your favorite HTTP daemon. > Thanks, I was pretty sure that was the case. But, I'm still baffled > why the original author(s) went to the extra work to always generate > absolute URIs. The pages were originally developed by a web > development company we contracted to do the initial design for us. We > were _assuming_ they knew more about that sort of thing than we > old-school EE types. Hah! Those people certainly don’t look “experienced”. "
Re: Check for running DHCP daemon?
Hmm, okay. What you are saying makes sense. I'm actually wondering if it might be more beneficial for me to check if the local DHCP port (udp 67) is bound and in use. I had tried to do this some time ago, and couldn't get it working right (it would always test true, even when it shouldn't have). Can anyone steer me in the right direction on port status? Jason Bailey Network Technician Emery Telcom Office: (435) 636-0052 [email protected] On 01/21/2015 09:39 PM, Chris Angelico wrote: On Thu, Jan 22, 2015 at 2:58 PM, Jason Bailey wrote: How would I get a list of running processes with the subprocess module? The documentation wasn't clear to me. Using the ps command. :) rosuav@dewey:~$ python3 Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. import subprocess b" dhcpd\n" in subprocess.check_output(["ps","-A"]) False rosuav@sikorsky:~$ python3 Python 3.5.0a0 (default:4709290253e3, Jan 20 2015, 21:48:07) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. import subprocess b" dhcpd\n" in subprocess.check_output(["ps","-A"]) True There's a DHCP server running on Sikorsky, but not on Dewey. :) Of course, this can be faked. Any process can call itself 'dhcpd' and pretend to be the DHCP server. It's up to you to decide how to deal with that. (Probably by not caring, I would expect. Unless you actually expect someone to maliciously try to confuse your script, it's not worth the hassle of protecting yourself.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On 1/23/2015 6:46 AM, Andrew Robinson wrote:
-- because people seem to have a very wrong idea about bool's nature as
a dualton being somehow justified solely by the fact that there are only
two values in Boolean logic; For, singletons style programming is not
justified by the number of values an object has in reality -- And I know
Charles bool didn't use singletons in his algebra, -- just read his
work and you'll see he never mentions them or describes them, but he
does actually use dozens of *instances* of the True and False objects he
In mathematics, as conceived by most mathematicians, there is only one
instance of each immutable value. Value is identity. There is only one
immutable empty set. (This, without the assumed 'immutable' added, is a
quote from beginning set theory texts written to counteract the beginner
mistake, here repeated by you, of thinking that there might be more than
one.) There is only one 0, one 1, one (immutable) set {0, 1}, and one
one symbol 'a'. The notion of identity separate from value is only
needed for mutable objects, which generally do not appear in math. So
unless Boole was an oddball among mathematicians, he considered multiple
instances of the word 'True' to be multiple references to the one and
only logical value True.
In Python, any immutable instance *could be* a singleton. In current
CPython, the ints -10 to 256 *are* singletons. In 'x = 1 + 1', the two
1s are the same 1. Other ints are not made to be singletons only
because the cost would be greater than the benefit. Similarly, ascii
chars are singletons and some other strings are interned to make them
singletons. Also, the empty tuple is a singleton. Empty lists cannot
be because they are mutable and each instance must be separately mutable.
>>> x = 'a'; y = 'a'; x is y
True
>>> x = (); y = (); x is y
True
was talking about -- for the obvious reason that he would have needed
special mirrors, dichroic or partially silvered, to be even able to
attempt to make one instance of True written on paper show up in
multiple places;
This is engineer talk. From a mathematical point of view, the above is
nonsense. Math values are generally seen as timeless spaceless platonic
values.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On Thu, Jan 22, 2015 at 7:59 PM, Rustom Mody wrote: > PS Ian for a hot thread like this its good to put quotes carefully > You are quoting Steven quoting somebody -- dunno who that somebody is I include quote that only for context to Steven's quote. Since I'm not replying to it, I don't care who wrote it, and if I don't care, then why should the reader? So I'm sorry, but I'm more likely to simply delete that context than mess around with multiple levels of attribution. -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: > Can you tell me what of the following code does not satisfy your requirements? > [Needs python 3.4] > > from enum import IntEnum class B4(IntEnum): > F1 = 0 > F2 = 0 > F3 = 0 > T = 1 This strikes me as a potential problem: >>> B4.F1 is B4.F2 is B4.F3 True >>> list(B4) [, ] Enum members with the same values are just aliases for one another, not distinct entities. -- https://mail.python.org/mailman/listinfo/python-list
Case-insensitive sorting of strings (Python newbie)
I notice that the string method 'lower' seems to convert some strings (input from a text file) to Unicode but not others. This messes up sorting if it is used on arguments of 'sorted' since Unicode strings come before ordinary ones. Is there a better way of case-insensitive sorting of strings in a list? Is it necessary to convert strings read from a plaintext file to Unicode? If so, how? This is Python 2.7.8. Regards John Sampson -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
On Sat, Jan 24, 2015 at 3:02 AM, Jason Bailey wrote: > I'm actually wondering if it might be more beneficial for me to check if the > local DHCP port (udp 67) is bound and in use. I had tried to do this some > time ago, and couldn't get it working right (it would always test true, even > when it shouldn't have). Can anyone steer me in the right direction on port > status? You can check with netstat: $ sudo netstat -n4lp|grep ':67 ' udp0 0 0.0.0.0:67 0.0.0.0:* 22466/dhcpd On my system, there's a /proc/net/udp which carries this information. Everything's in hex, so port 67 is shown as 0043: $ grep :0043 /proc/net/udp 5755: :0043 : 07 : 00: 00 8334454 2 880403e60b40 0 You'd have to check your own system to know what's truly reliable and worth using. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: > On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: > > Can you tell me what of the following code does not satisfy your > > requirements? > > [Needs python 3.4] > > > > > from enum import IntEnum > class B4(IntEnum): > > F1 = 0 > > F2 = 0 > > F3 = 0 > > T = 1 > > This strikes me as a potential problem: > > >>> B4.F1 is B4.F2 is B4.F3 > True > >>> list(B4) > [, ] > > Enum members with the same values are just aliases for one another, > not distinct entities. Yeah The only workaround I have been able to come up with is: class B4(IntEnum): > F1 = 0 > F2 = "" > F3 = None > T = 1 which is not bad; its ridiculous [Like going around with a broken broom searching for falsey objects :-) ] -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Sat, Jan 24, 2015 at 12:23 AM, Fetchinson . wrote: > In any case, I'm pretty sure it was said before, but I can't really > find it anywhere, can someone tell me what the rationale is for > *function signature* type hinting? > > I totally get type hinting in general, but why does it have to be in > the function signature? Any reason for that specifically? Is there any particular reason for the number of arguments to be part of the function signature? I totally get the notion of declaring how many arguments a function takes, but why does it have to be in the function signature? Data types are just as much a part of that signature as argument count is. You could argue that the function's return type isn't part of that, but that's about it. > If there is a pep for it, people will use it, so the fact that > it is optional is irrelevant... Function annotations were introduced in 2006 (Python 3.0) with PEP 3107: https://www.python.org/dev/peps/pep-3107/ They were optional then, they are still optional now. Have you been overrun with them for the past decade? If not, why do you expect now to be? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive sorting of strings (Python newbie)
John Sampson wrote: > I notice that the string method 'lower' seems to convert some strings (input > from a text file) to Unicode but not others. > This messes up sorting if it is used on arguments of 'sorted' since Unicode > strings come before ordinary ones. I doubt that. Can you provide a short example? > Is there a better way of case-insensitive sorting of strings in a list? Is it > necessary to convert strings read from a plaintext file > to Unicode? If so, how? This is Python 2.7.8. Well, if you have non-ASCII chars for many Unicode characters str.lower() won't give reasonable results. So binary strings containing an encoding of Unicode character entities should be decoded to Unicode strings first. Ciao, Michael. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On 2015-01-23, Chris Warrick wrote: > > Hah! Those people certainly don’t look “experienced”. > >"https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Sat, Jan 24, 2015 at 4:03 AM, Rustom Mody wrote: > The only workaround I have been able to come up with is: > > class B4(IntEnum): >> F1 = 0 >> F2 = "" >> F3 = None >> T = 1 > > which is not bad; its ridiculous It's ridiculous because you declared an IntEnum and then started using non-integer values that boolify to the same value (and don't intify). If that even works, it's a total hack, and it might stop working in a future version... for example, it doesn't seem to work on my Python 3.5: >>> class B4(IntEnum): ... F1=0 ... F2="" ... F3=None ... T=1 ... Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.5/enum.py", line 152, in __new__ enum_member = __new__(enum_class, *args) ValueError: invalid literal for int() with base 10: '' Using Enum instead of IntEnum does work, but it's still hardly a normal use of an enumeration. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: > On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: > > Can you tell me what of the following code does not satisfy your > > requirements? > > [Needs python 3.4] > > > > > from enum import IntEnum > class B4(IntEnum): > > F1 = 0 > > F2 = 0 > > F3 = 0 > > T = 1 > > This strikes me as a potential problem: > > >>> B4.F1 is B4.F2 is B4.F3 > True Thanks for pointing that out I saw the problem but not where/why/how Strikes me that making enumerations is-equal rather than just =-equal is a bit heavy-handed and unnecessary What do you think? [BTW Changing IntEnum to (plain) Enum does not help] -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 10:54:06 PM UTC+5:30, Chris Angelico wrote: > On Sat, Jan 24, 2015 at 4:03 AM, Rustom Mody wrote: > > The only workaround I have been able to come up with is: > > > > class B4(IntEnum): > >> F1 = 0 > >> F2 = "" > >> F3 = None > >> T = 1 > > > > which is not bad; its ridiculous > > It's ridiculous because you declared an IntEnum and then started using > non-integer values that boolify to the same value (and don't intify). > If that even works, it's a total hack, and it might stop working in a > future version... for example, it doesn't seem to work on my Python > 3.5: > > >>> class B4(IntEnum): > ... F1=0 > ... F2="" > ... F3=None > ... T=1 > ... > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.5/enum.py", line 152, in __new__ > enum_member = __new__(enum_class, *args) > ValueError: invalid literal for int() with base 10: '' > > Using Enum instead of IntEnum does work, but it's still hardly a > normal use of an enumeration. > > ChrisA I mis-cut-n-pasted. Should have been Enum not IntEnum -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Sat, Jan 24, 2015 at 4:22 AM, Rustom Mody wrote: > Strikes me that making enumerations is-equal rather than just > =-equal is a bit heavy-handed and unnecessary > What do you think? *Normal* use of an enumeration does make sense for them to be identical. Classic use would be like this: class AnsiColor(IntEnum): black = 0 red = 1 green = 2 orange = 3 # ... blue, magenta, cyan, white bold_black = 8 bold_red = 9 # etc etc etc bold_orange = 11 yellow = 11 # On many screens, bold orange looks more yellow There is absolutely no difference between the ANSI color "bold orange" and the ANSI color "yellow". So you would expect them to be identical: >>> AnsiColor.yellow >>> AnsiColor.yellow is AnsiColor.bold_orange True And they are. There's simply no use-case for equal-but-distinct tokens, when you're primarily using this to give names to numbers. For another example, you could localize all the color names, or use "bright" instead of "bold", or drop the underscores; but ultimately, if you send "\e[11m" to the console, you're going to get the same color, whether that 11 was called "bold_orange" or "jaune". What you're trying to do here is a hack, so it's no surprise that the system doesn't properly support it. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On Sat, Jan 24, 2015 at 3:00 AM, Chris Warrick wrote:
> 5. especially old-style %-based string formatting!
Please. There's nothing wrong with %-style formatting. It's not
deprecated, and never will be; and it has the advantage of being
cross-language compatible. I was speaking with a Python student
yesterday who didn't understand the {} notation, but grokked "%d + %d
= %d" % (x, y, x+y) instantly, thanks to experience with other
languages.
Use of % formatting is not a bug.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 11:07:48 PM UTC+5:30, Chris Angelico wrote: > On Sat, Jan 24, 2015 at 4:22 AM, Rustom Mody wrote: > > Strikes me that making enumerations is-equal rather than just > > =-equal is a bit heavy-handed and unnecessary > > What do you think? > > *Normal* use of an enumeration does make sense for them to be > identical. Classic use would be like this: > > class AnsiColor(IntEnum): > black = 0 > red = 1 > green = 2 > orange = 3 > # ... blue, magenta, cyan, white > bold_black = 8 > bold_red = 9 > # etc etc etc > bold_orange = 11 > yellow = 11 # On many screens, bold orange looks more yellow > > There is absolutely no difference between the ANSI color "bold orange" > and the ANSI color "yellow". So you would expect them to be identical: > > >>> AnsiColor.yellow > > >>> AnsiColor.yellow is AnsiColor.bold_orange > True > > And they are. There's simply no use-case for equal-but-distinct > tokens, when you're primarily using this to give names to numbers. For > another example, you could localize all the color names, or use > "bright" instead of "bold", or drop the underscores; but ultimately, > if you send "\e[11m" to the console, you're going to get the same > color, whether that 11 was called "bold_orange" or "jaune". > > What you're trying to do here is a hack, so it's no surprise that the > system doesn't properly support it. > > ChrisA No disagreement with the 'hack' As for "no use case for equal but distinct tokens" - thats a strange view given this thread -- https://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive sorting of strings (Python newbie)
John Sampson wrote:
> I notice that the string method 'lower' seems to convert some strings
> (input from a text file) to Unicode but not others.
> This messes up sorting if it is used on arguments of 'sorted' since
> Unicode strings come before ordinary ones.
>
> Is there a better way of case-insensitive sorting of strings in a list?
> Is it necessary to convert strings read from a plaintext file
> to Unicode? If so, how? This is Python 2.7.8.
The standard recommendation is to convert bytes to unicode as early as
possible and only manipulate unicode. This is more likely to give correct
results when slicing or converting a string.
$ cat tmp.txt
ähnlich
üblich
nötig
möglich
Maß
Maße
Masse
ÄHNLICH
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> for line in open("tmp.txt"):
... line = line.strip()
... print line, line.lower()
...
ähnlich ähnlich
üblich üblich
nötig nötig
möglich möglich
Maß maß
Maße maße
Masse masse
ÄHNLICH Ähnlich
Now the same with unicode. To read text with a specific encoding use either
codecs.open() or io.open() instead of the built-in (replace utf-8 with your
actual encoding):
>>> import io
>>> for line in io.open("tmp.txt", encoding="utf-8"):
... line = line.strip()
... print line, line.lower()
...
ähnlich ähnlich
üblich üblich
nötig nötig
möglich möglich
Maß maß
Maße maße
Masse masse
ÄHNLICH ähnlich
Unfortunately this will not give the order that you (or a german speaker in
the example below) will probably expect:
>>> print "".join(sorted(io.open("tmp.txt"), key=unicode.lower))
Masse
Maß
Maße
möglich
nötig
ähnlich
ÄHNLICH
üblich
For case-insensitive sorting you get better results with locale.strxfrm() --
but this doesn't accept unicode:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'de_DE.UTF-8'
>>> print "".join(sorted(io.open("tmp.txt"), key=locale.strxfrm))
Traceback (most recent call last):
File "", line 1, in
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position
0: ordinal not in range(128)
As a workaround you can sort first:
>>> print "".join(sorted(open("tmp.txt"), key=locale.strxfrm))
ähnlich
ÄHNLICH
Maß
Masse
Maße
möglich
nötig
üblich
You should still convert the result to unicode if you want to do further
processing in Python.
--
https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On Sat, Jan 24, 2015 at 1:47 AM, Grant Edwards wrote: > I'm maintaining a web app were the original author(s) went to a little > bit of trouble to always use absolute URIs in links in the pages. The advantage is that someone who downloads the bare page will still be referencing images, CSS, other links, etc, from the original server. The disadvantage is... exactly the same. These days, it's MUCH better to use relative links, and then let something like wget rewrite them as necessary. In fact, if all your links are relative (not even the leading slash - use ../../../ as many times as is necessary), they don't even need rewriting, and you can test your web site by just pointing your browser at the file system. The original code seems rather fragile. The port number isn't incorporated, so incoming requests on 8443 will end up going through to https:// with the default port of 443. Any other port will be sent back through 80. Strongly recommend not doing this. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive sorting of strings (Python newbie)
On Sat, Jan 24, 2015 at 4:53 AM, Peter Otten <[email protected]> wrote: > Now the same with unicode. To read text with a specific encoding use either > codecs.open() or io.open() instead of the built-in (replace utf-8 with your > actual encoding): > import io for line in io.open("tmp.txt", encoding="utf-8"): > ... line = line.strip() > ... print line, line.lower() In Python 3, the built-in open() function sports a fancy encoding= parameter like that. for line in open("tmp.txt", encoding="utf-8"): If you can, I would recommend using Python 3 for all this kind of thing. The difference may not be huge, but there are all sorts of little differences here and there that mean that Unicode support is generally better; most of it stems from the fact that the default quoted string literal is a Unicode string rather than a byte string, which means that basically every function ever written for Py3 has been written to be Unicode-compatible. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Fri, Jan 23, 2015 at 4:46 AM, Andrew Robinson
wrote:
> Although, I have to laugh -- Verilog can syntheze a CPU -- implement memory
> -- and then load a program and run python on the virtual machine. When the
> pentium was first developed, I watched as Intel actually booted up MS-DOS
> under using Xilinx chips to run the verilog program's output they could
> physically run anything a pentium processor could run. That's *IS* what I
> consider "general purpose".
Turing-complete and "general purpose" are not the same. Would you
write a web application or a banking system in Verilog? Using Verilog
to host a virtual machine that runs such a program written in some
other language doesn't count; the actual application is still written
in that other language. You could implement the same Pentium virtual
machine in Brainf*** if you chose, but it will still be an esoteric
language, not a general-purpose one.
> But you're sort of confounding my need for type information in my new class
> as a way to advertise compatability with bool, with subclassing -- which is
> only one way that I was exploring to get the 'type' name attached to the new
> object; That's a mistake that D'Aprano seems to be repetitively making as
> well.
No, I'm just responding specifically to the complaint you've been
making about not being able to subclass bool.
> C++ *DOES* allow the necessary kind of type checking and subclassing for
> what I need to do in spite of not having a subclass mechanism built into the
> language for base types; eg: C++ allows a semantic subclass to be
> constructed which can be typecast to a bool for compatibility, but otherwise
> presents extra data and the type the enhanced object reports is irrelevant.
> As I've mentioned before, people can do object oriented programming in C,
> So, to satisfy your curiosity -- I'll show you a mixed C/C++ example, where
> I make a semantic subclass that has five values AllFalse, PartFalse,
> Uncertain, PartTrue, True ; and these five values will have a typeid() of
> bool and be 100% compatible with legacy C++ bool; but upon request, they
> these 'bool' types will re-cast into a semantic subtype that provides
> additional certainty data.
>
> See the program at end of e-mail. It compiles with gcc 4.8.2 with no
> warnings; g++ filename.cc ; ./a.out
I'm not convinced this is generally safe. Unaware client code that
uses these values will lose the certainty values, even if the values
are later passed back into aware code.
const bool& is_p_equal_np() {
return Uncertain;
}
void some_other_sbool_aware_code(const SBool& value) {
if (SBool(PartFalse) < value) {
cout << "Success: value is greater than PartFalse" << endl;
} else {
cout << "Failure: value is not greater than PartFalse" << endl;
}
}
void some_sbool_unaware_code() {
bool uncertainty = is_p_equal_np();
some_other_sbool_aware_code(uncertainty);
}
Calling some_sbool_unaware_code() prints the Failure message because
the bool reference gets lost, and the typecast to SBool in
some_other_sbool_aware_code consequently results in AllFalse.
To the extent that this does work, it seems to be based on pointer
arithmetic, which is intentionally and explicitly something that
Python doesn't support. If Python had the means to distinguish name
bindings, then I see no other reason the same approach couldn't work.
> But let me explain a bit more why I'm picking on Python: For even if we set
> the electronic engineering concerns aside that I've raised (and they are
> valid, as OOP is supposed to model reality, not reality be bent to match
> OOP) -- People's facile explanations about why Python's version of bool is
> the way it is -- still bothers me here in the python mail list -- because
> people seem to have a very wrong idea about bool's nature as a dualton being
> somehow justified solely by the fact that there are only two values in
> Boolean logic; For, singletons style programming is not justified by the
> number of values an object has in reality -- And I know Charles bool didn't
> use singletons in his algebra, -- just read his work and you'll see he
> never mentions them or describes them, but he does actually use dozens of
> *instances* of the True and False objects he was talking about -- for the
> obvious reason that he would have needed special mirrors, dichroic or
> partially silvered, to be even able to attempt to make one instance of True
> written on paper show up in multiple places; And that's silly to do when
> there's no compelling reason to do it.
Writing down the word true multiple times doesn't create multiple
"instances" of the mathematical true. Mathematically, they're all the
same platonic object.
> As far a subtyping goes; The very fact that Guido used subtyping to create
> bool in the first place (subtype of int), precludes any real claim that bool
> should not itself be subclassable just because bools only have two values;
> I mean, seriously -- Guido's 'st
Re: Case-insensitive sorting of strings (Python newbie)
John Sampson wrote:
> I notice that the string method 'lower' seems to convert some strings
> (input from a text file) to Unicode but not others.
I don't think so. You're going to have to show an example.
I *think* what you might be running into is an artifact of printing to a
terminal, which may (or may not) interpret some byte sequences as UTF-8
characters, but I can't replicate it. So I'll have to see an example.
Please state what OS you are running on, and what encoding your terminal is
set to. Also, are you opening the file in text mode or binary mode?
> This messes up sorting if it is used on arguments of 'sorted' since
> Unicode strings come before ordinary ones.
>
> Is there a better way of case-insensitive sorting of strings in a list?
> Is it necessary to convert strings read from a plaintext file
> to Unicode? If so, how? This is Python 2.7.8.
Best practice is to always convert to Unicode, even if you know your text is
pure ASCII. You *may* be able to get away with not doing so if you know you
have ASCII, but that's still the lazy way. And of course you need to know
what encoding has been used.
There is some overhead with decoding to Unicode, so if performance really is
critical, *and* your needs are quite low, you may be able to get away with
just treating the strings as ASCII byte strings:
with open("my file.txt") as f:
for line in f:
print line.lower()
will correctly lowercase ASCII strings. It won't lowercase non-ASCII
letters, and there's a good chance that they may display as raw bytes in
some encoding. Otherwise, I think the best way to approach this may be:
import io
with io.open("my file.txt", encoding='utf-8') as f:
for line in f:
print line.lower()
Assuming the file actually is encoded with UTF-8, that ought to work
perfectly.
But to really know what is going on we will need more information.
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Sat, Jan 24, 2015 at 4:45 AM, Rustom Mody wrote: > No disagreement with the 'hack' > As for "no use case for equal but distinct tokens" - thats a strange > view given this thread Look at it this way: A classic enumeration has no use-case for equal-but-distinct; this thread doesn't disagree with that, because this thread is not about classic enumerations. In the same way, integers don't have use-cases for equal-but-distinct either, but in practice, you can distinguish between exact literals and the results of computation: rosuav@sikorsky:~$ cat unique_numbers.py x = 10 y = 10 z = 9+1 print(x is y, x is z, y is z) rosuav@sikorsky:~$ python3 unique_numbers.py True False False This is still not good code, though. If you really need to distinguish those, your code is majorly fragile. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Fri, Jan 23, 2015 at 10:03 AM, Rustom Mody wrote: > On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: >> On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: >> > Can you tell me what of the following code does not satisfy your >> > requirements? >> > [Needs python 3.4] >> > >> > >> from enum import IntEnum >> class B4(IntEnum): >> > F1 = 0 >> > F2 = 0 >> > F3 = 0 >> > T = 1 >> >> This strikes me as a potential problem: >> >> >>> B4.F1 is B4.F2 is B4.F3 >> True >> >>> list(B4) >> [, ] >> >> Enum members with the same values are just aliases for one another, >> not distinct entities. > > Yeah > > The only workaround I have been able to come up with is: > > class B4(IntEnum): >> F1 = 0 >> F2 = "" >> F3 = None >> T = 1 > > which is not bad; its ridiculous > [Like going around with a broken broom searching for falsey objects :-) ] How about something like this: >>> from enum import Enum >>> class B4(Enum): ... F1 = (False, 1) ... F2 = (False, 2) ... F3 = (False, 3) ... T = (True, 4) ... def __bool__(self): ... return self.value[0] ... >>> B4.F1 is B4.F2 False >>> bool(B4.F1) False >>> bool(B4.T) True -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Fri, Jan 23, 2015 at 10:45 AM, Rustom Mody wrote: > No disagreement with the 'hack' > As for "no use case for equal but distinct tokens" - thats a strange > view given this thread If you want equal but distinct, you can give them distinct values and define an __eq__ method that compares them as equal. Because of this though I do take some issue with the Planet example in the docs: https://docs.python.org/3/library/enum.html#planet If any planets happened to have the same mass and radius (which I realize would be unlikely in this case), the example would fail. Using the value of the enum for both identity and data conflates the two concepts and leads to pitfalls. -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On Sat, Jan 24, 2015 at 5:09 AM, Tony the Tiger wrote: > On Thu, 22 Jan 2015 17:13:12 +, Automn wrote: > >> game > > No interest, at all, nada, zilch. zero, nothing. > > /Grrr Then don't bother responding, just skip the thread and move on. The rest of us, who don't have this unnatural aversion to games, can still help out (although the OP didn't have any specific questions or anything, so this looked like just an announcement). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On 01/22/2015 09:13 AM, Automn wrote: > > I am programming a "Secret of Mana" (Seiken Densetsu) game in kivy, it runs > on a phone with kivy launcher. AWESOME That was a totally fabulous game -- one of the very few I actually played to the end. :) -- ~Ethan~ signature.asc Description: OpenPGP digital signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Loading a module from a subdirectory
On 2014-03-10, Virgil Stokes wrote: > This is a multi-part message in MIME format. > --030903060901020503030004 > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > Content-Transfer-Encoding: 7bit > > I have the following folder-file structure: > > C:/PythonCode/VideoPlayerSimulator/ > +-- __init__.py (empty file) > +-- GlbVars.py (contains the single > class Glb) > > C:/PythonCode/VideoPlayerSimulator/RubberBanding/ > +-- __init__.py > +-- ImportDemo.py > > where, ImportDemo.py contains the following code (a single line): > > from VideoPlayerSimulator.GlbVars import Glb as G > > gives the following error when I execute it: > > *ImportError: No module named VideoPlayerSimulator.GlbVars* > > Note: >1. My sys.path contains: > ['C:\\PythonCode\\VideoPlayerSimulator', ...] >2. Python 2.7.5 on a Window 7 platform >3. The same ImportDemo.py file when executed on my Window Vista platform > with the same folder-file structure, *DOES NOT* give an error and > works > as expected. > > Why does the error occur, and why does it not occur on the Windows Vista > platform? > I don't think you understand what Mr. Otten said, it is not undefined behaviour, maybe you could demangle your import statement. Automn -- https://mail.python.org/mailman/listinfo/python-list
Re: Loading a module from a subdirectory
On Fri, Jan 23, 2015 at 11:23 AM, Automn wrote: > On 2014-03-10, Virgil Stokes wrote: >> [SNIP] > > I don't think you understand what Mr. Otten said, it is not undefined > behaviour, > maybe you could demangle your import statement. The post you're replying to is 10 months old. One way or another, the OP has probably resolved the problem by now. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On Friday, January 23, 2015 at 11:49:05 AM UTC-6, Chris Angelico wrote:
> On Sat, Jan 24, 2015 at 3:00 AM, Chris Warrick wrote:
> > 5. especially old-style %-based string formatting!
>
> Please. There's nothing wrong with %-style formatting.
*BALD-FACED-PARTISAN-LIE*!
If there is *NOTHING* wrong with %formatting then why did we
violate our philosophy of "there should be one way to do
it..." and introduce the string.format() method?
The new string.format() method is not merely *ANOTHER* way
to do the same thing Chris, it's first and foremost a bug-
fix for the limited capabilities of the legacy %formatting.
But string.format() is so much more than a mere bug-fix,
Chris, since it not only offers a richer set of tools, you
can even create your own custom extension of the formatter:
https://docs.python.org/2/library/string.html#string-formatting
...try to do all that with %formatting! And lets not forget
that a *FORMAT-METHOD* aligns itself nicely with the wise
philosophy of OOP! (oh boy, i'm going flac for that one from
the OOP hating religious nutters!)
> It's not deprecated, and never will be;
Chris, what do you call a statement that is based on an
un-provable premise? Oh and, GvR told me to tell you that he
wants his time machine back, and if it has even one dent
you're going to be in some serious trouble!
> and it has the advantage of being cross-language
> compatible. I was speaking with a Python student yesterday
> who didn't understand the {} notation, but grokked "%d +
> %d = %d" % (x, y, x+y) instantly, thanks to experience
> with other languages.
So now you finally admit to us that you base your decisions
on emotion and ignore facts. This was something that i had
suspected for some time and i'm glad that you can finally
admit the truth.
So even though string.format() is highly superior to the
legacy %format crap, you will happily ignore the
advancements and cling to your instinctual emotions like the
religious nutters clinging to a bible.
> Use of % formatting is not a bug.
"not a bug"? Another ridiculous judgment! I believe the
description you're looking for is: "is a foolish
consistency".
--
https://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive sorting of strings (Python newbie)
Peter Otten <[email protected]>: > The standard recommendation is to convert bytes to unicode as early as > possible and only manipulate unicode. Unicode doesn't get you off the hook (as you explain later in your post). Upper/lowercase as well as collation order is ambiguous. Python even with decent locale support can't be expected to do it all for you. Well, if Python can't, then who can? Probably nobody in the world, not generically, anyway. Example: >>> print("re\u0301sume\u0301") résumé >>> print("r\u00e9sum\u00e9") résumé >>> print("re\u0301sume\u0301" == "r\u00e9sum\u00e9") False >>> print("\ufb01nd") find >>> print("find") find >>> print("\ufb01nd" == "find") False If equality can't be determined, words really can't be sorted. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Thursday, January 22, 2015 at 9:22:40 PM UTC-6, Terry Reedy wrote: > On 1/22/2015 8:15 PM, Rick Johnson wrote: > > > Okay, i have found a solution to the type hinting problem > > that will appease both sides. On one side we have those who > > are proposing type hinting annotations within function sigs, > > and on the other side, we have those who oppose the > > implementation of type hinting via this method because of > > the readability concerns. The solution is move the type > > hinting syntax completely out of the source file and into > > another file -- think of it as a "Python Type Hinting Header > > File". > > This idea is so brilliant Well thank you kind sir. O:-) > that it is already an option in mypy and is part of the new > type-hint proposal. An *OPTION*? If it is not mandatory then why bother? If authors have a choice between writing type hints into func sigs or writing them in a "stub file", then the natural human behavior of "slothfulness" will bring about the destruction of Python via syntactic noise. Heck, why don't we just adopt the *REAL* fairness doctrine and make indentation optional? > The separate type-hint files are called 'stub files'. I > don't know what the extension is. These will be used for > the stdlib, which will not have annotations in the .py > files So are saying that stubs are mandatory for stdlib source but optional everywhere else? > > (1) Removes the noisy syntax from the source file. Python > > code will remain as clean tomorrow as it is today. > > This will at least be an option. You are and will be free > to advocate that people always use stub files. Well i don't advocate from a selfish perspective here, i'm trying to save this community! Even though no human cannot escape his inherent emotional being, *some-of-us* do understand the importance of rational judgment when making important decisions! > > (2) Puts the onerous on the author *NOT* on the reader. > > This system utilizes a concept known as "Level Of Detail" > > (or LOD). LOD means that i should not need to see a type > > hint unless i *WANT* to see a type hint. > > One thing not discussed here (but was in the earlier > python-ideas thread some months ago) is that some groups > have standards for using some functions that is stricter > than the function's full duck-typing generality. A stub > file allows a group to specify a restrictive use > annotation for their static checker without putting lies > into the code or doc of the function itself. Yes, there is nothing worse than lies, and comments are already full of them. Yet again another reason to *FORCE* stub file usage! > > (3) If i decide i don't want type hints in my code, all i > > have to do is delete or rename a file, which is much less > > error prone then editing source code. > > If the annotations are in a separate file, deleting will > hardly be necessary since the file will be ignored until > one runs software that uses it. > > > (4) Has the added benefit of aiding when debugging type hints. > > I am not sure what you mean here. It will be easier to > temporarily comment out an incorrect annotation for a > function, pending correction, when in a separate file. To tell you the truth I had not even considered allowing commenting in the stub files, i was primarily focused on *EXPORTING* the hints, so you are correct! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Thursday, January 22, 2015 at 9:24:01 PM UTC-6, Rustom Mody wrote: > > > > Simplistic Example Code utilizing two files: > > > > > > [...snip code example...] > > > 1. Allow in same file > 2. Change syntax slightly to: >type greeting : str -> str While i'll agree that removing the hints from sigs is better than the alternative of injecting noise into sigs, i still feel as though type hints will "dirty" the purity of source no matter how wonderful the declaration might to be. I believe strongly that LOD is the only method we can apply that will allow us to "bolt on" non-destructive type hints in Python. So although your idea is an improvement, i'm sticking with the "stub file solution". (unless something better is offered) > [type is the keyword equivalent to your other typehint file ] > and you have essentially the Haskell solution. > > The catch I expect is that haskell is strongly committed to simultaneous > definitions: > > x = 1 > y = x+2 > > is the same as > y = x+2 > x = 1 > > and so definitions can generally be permuted around > > Python is committed to the opposite extreme: > even def and class are not declarative but imperative I'm sorry, but i was unable to understand how your last point was relevant to type hints? -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On Sat, Jan 24, 2015 at 6:02 AM, Rick Johnson wrote: >> It's not deprecated, and never will be; > > Chris, what do you call a statement that is based on an > un-provable premise? Oh and, GvR told me to tell you that he > wants his time machine back, and if it has even one dent > you're going to be in some serious trouble! Statements from the BDFL committing to maintaining it *at least* until Python 4000, with clear indication that it is most definitely not deprecated. Or, looking at it another way: If you want to disagree with me, find a statement in current, official documentation that says that it's deprecated. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Thursday, January 22, 2015 at 10:04:29 PM UTC-6, Chris Angelico wrote: > It's worth pointing out, too, that the idea isn't > panaceaic - it's just another tool in the box. Any time > you break related things into separate places, especially > separate files, the tendency for them to get out of sync > grows dramatically. I wonder how that "poor python interpreter" keeps all those .pyc and .pyo files in sync with constantly changing source code? It should be tantamount to torture! Will someone *PLEASE* start a charity site titled: "Python's sanity fund"? > Use of stub files for something that's only occasionally > run (the type-checking linter) increases the potential > time delay between the error and the fix. Unless you make > a git/hg hook that runs type checks, chances are you'll > have those issues in your code. > > Stub files are useful, but they aren't going to magically > solve everyone's complaints. We're not trying to solve everyone's complaints, we're trying to formulate a solution that will cause the least amount (or completely avert) violating Python's design philosophy. You act as if the "type hint fan-boys" are the *ONLY* side of this coin, well, i here to inform you that coins are two-sided! Even though type hints may be useful to many programmers, i'm sure equally as many will find no use for them. But emotion and opinions *ALONE* is not a wise basis for ANY decision making. Therefore, the "MANDATORY-STUB-FILE-SOLUTION" is the *ONLY* solution (offered so far) that can maintain Python's philosophical goals whilst appeasing both sides of this two faced coin. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Sat, Jan 24, 2015 at 6:48 AM, Rick Johnson wrote: > On Thursday, January 22, 2015 at 10:04:29 PM UTC-6, Chris Angelico wrote: > >> It's worth pointing out, too, that the idea isn't >> panaceaic - it's just another tool in the box. Any time >> you break related things into separate places, especially >> separate files, the tendency for them to get out of sync >> grows dramatically. > > I wonder how that "poor python interpreter" keeps all those > .pyc and .pyo files in sync with constantly changing source > code? It should be tantamount to torture! Will someone > *PLEASE* start a charity site titled: "Python's sanity fund"? That's where one is directly derived from the other. Edit the .py file, rebuild the .pyc from it. Any dumb machine can do that... as long as timestamps can be relied on, the hard drive is correctly retaining data, etc, etc, etc. And guess what? Python isn't perfect at it. I had a bizarre problem a while ago that came down to an incorrect .pyc file in the stdlib. (I still have no idea how that came to be incorrect. The hard drive doesn't seem to be failing, and the corruption in the file looks more like a software bug than a hardware issue.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive sorting of strings (Python newbie)
On Sat, Jan 24, 2015 at 6:14 AM, Marko Rauhamaa wrote:
> Well, if Python can't, then who can? Probably nobody in the world, not
> generically, anyway.
>
> Example:
>
> >>> print("re\u0301sume\u0301")
> résumé
> >>> print("r\u00e9sum\u00e9")
> résumé
> >>> print("re\u0301sume\u0301" == "r\u00e9sum\u00e9")
> False
> >>> print("\ufb01nd")
> find
> >>> print("find")
> find
> >>> print("\ufb01nd" == "find")
> False
>
> If equality can't be determined, words really can't be sorted.
Ah, that's a bit easier to deal with. Just use Unicode normalization.
>>> print(unicodedata.normalize("NFC","re\u0301sume\u0301") ==
>>> unicodedata.normalize("NFC","r\u00e9sum\u00e9"))
True
It's a bit verbose, but if you're doing a lot of comparisons, you
probably want to make a key-function that folds together everything
that you want to be treated the same way, for instance:
def key(s):
"""Normalize a Unicode string for comparison purposes.
Composes, case-folds, and trims excess spaces.
"""
return unicodedata.normalize("NFC",s).strip().casefold()
Then it's much tidier:
>>> print(key("re\u0301sume\u0301") == key("r\u00e9sum\u00e9"))
True
>>> print(key("\ufb01nd") == key("find"))
True
You may want to go further, too; for search comparisons, you'll want
to use NFKC normalization, and probably translate all strings of
Unicode whitespace into single U+0020s, or completely strip out
zero-width non-breaking spaces (and maybe zero-width breaking spaces,
too), etc, etc. It all depends on what you mean by "equality". But
certainly a basic NFC or NFD normalization is safe for general work.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
Steven D'Aprano writes: > Ben Finney wrote: > > > Freedom of expression entails an obligation on the state to not > > quash anyone's expression. It does not affect anyone who is not the > > state; it imposes no obligation on the PSF. > > By this reasoning, you would be perfectly comfortable with a state of > affairs where a media monopoly […] What in the above makes you think I'd be at all comfortable with a media monopoly? Not so. Rather, my objection to monopolisation of media is rooted in concerns other than freedom of expression. Or, in the terms I used above: It is not freedom of expression which imposes the obligation to avoid monopolisation of media. -- \ “Oh, I realize it's a penny here and a penny there, but look at | `\ me: I've worked myself up from nothing to a state of extreme | _o__) poverty.” —Groucho Marx | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] absolute vs. relative URI
On 23/01/2015 19:46, Chris Angelico wrote: On Sat, Jan 24, 2015 at 6:02 AM, Rick Johnson wrote: It's not deprecated, and never will be; Chris, what do you call a statement that is based on an un-provable premise? Oh and, GvR told me to tell you that he wants his time machine back, and if it has even one dent you're going to be in some serious trouble! Statements from the BDFL committing to maintaining it *at least* until Python 4000, with clear indication that it is most definitely not deprecated. Or, looking at it another way: If you want to disagree with me, find a statement in current, official documentation that says that it's deprecated. ChrisA This http://bugs.python.org/issue14123 seems relevant. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 7:23:34 AM UTC-6, Fetchinson . wrote: > I really like the idea that in python I don't have lots of > choices in many areas, certain things are dictated. The > big advantage is that when I read other people's code I > know what to expect so me being restricted is a small > price to pay that is totally worth it. So I'd come down on > the side of the complainers in this case, "the complainers"??? O:-) Intentional or not, your word choice paints a negative connotation of the "opposition". We are not "complainers", we merely hold a contradictory view to that of the "proposers". Injecting polarity into debates is dangerous, because, then we get off into the emotional weeds and a solution may never be found -- just observe the polarization of American politics if you don't believe me --> *PUKE* Rational people understand that both sides of any argument deserve objective consideration, and when a unanimous solution cannot be found, a compromise must be made on both sides. Even if that means cutting the baby in half. Sorry to pick on you. Everything else you said was very rational and articulate! -- https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
Steven D'Aprano writes: > Ben Finney wrote: > > > Freedom of expression entails an obligation on the state to not > > quash anyone's expression. It does not affect anyone who is not the > > state; it imposes no obligation on the PSF. > > By this reasoning, you would be perfectly comfortable with a state of > affairs where a media monopoly suppressed any and all dissenting > viewpoints, provided that it was a *privately owned* monopoly and not > the government. To answer this more directly: Expression between people – the field relevant to the freedom we're discussing – occurs naturally and with little effort. It is not an activity requiring high startup costs, and the market for it is as large as humanity. A monopoly on media is inherently unstable for this reason, so a https://en.wikipedia.org/wiki/Natural_monopoly> is highly unlikely ever to arise. Competitors will arise frequently to end the monopoly, if no state action is taken to stop them. If you are positing a media monopoly capable of suppressing any and all dissenting viewpoints, it can only persist in this because the state prevents any competitor to that monopoly. So this is still effectively the state acting to quash freedom of expression. -- \ “Now Maggie, I’ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.” —Homer, _The Simpsons_ | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On Friday, January 23, 2015 at 10:10:08 AM UTC-8, Tony the Tiger wrote: > On Thu, 22 Jan 2015 17:13:12 +, Automn wrote: > > > game > > No interest, at all, nada, zilch. zero, nothing. > > /Grrr Why don't you like fun? -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 1:59:38 PM UTC-6, Chris Angelico wrote: > On Sat, Jan 24, 2015 at 6:48 AM, Sir Rick Johnson wrote: > > On Thursday, January 22, 2015 at 10:04:29 PM UTC-6, Chris Angelico wrote: > > > >> It's worth pointing out, too, that the idea isn't > >> panaceaic - it's just another tool in the box. Any time > >> you break related things into separate places, especially > >> separate files, the tendency for them to get out of sync > >> grows dramatically. > > > > I wonder how that "poor python interpreter" keeps all those > > .pyc and .pyo files in sync with constantly changing source > > code? It should be tantamount to torture! Will someone > > *PLEASE* start a charity site titled: "Python's sanity fund"? > > That's where one is directly derived from the other. Edit the .py > file, rebuild the .pyc from it. Any dumb machine can do that... as > long as timestamps can be relied on, the hard drive is correctly > retaining data, etc, etc, etc. Okay, you make a fair point, so let's dig beyond the superficiality and find the truth shall we? I don't care who wins, i just want to find the truth. Your assertion is that since "external hints" are not directly visible when reading source (as they would be in func sigs) that the author will forget to update them??? Heck, do you ever read comments? Many of them are not only out of sync with the code they describe (because an author forgot to update a corresponding comment after changing the code), in some cases, they are not even in sync with *REALITY* (this case being where the author cannot articulately describe what the code is doing and the comments become misleading) Yes, there are programmers out there who can write perfectly functioning code but cannot describe what it is doing with even a modicum of coherency! Do the phrase "word salad" mean anything to you? So after observing the lunacy of comment authors, arguing that by placing hints in source (as opposed to exporting them to stub files) is somehow going to "magically enforce" synchronicity -- you have more faith in others than i do! > And guess what? Python isn't perfect at it. I had a > bizarre problem a while ago that came down to an incorrect > .pyc file in the stdlib. (I still have no idea how that > came to be incorrect. The hard drive doesn't seem to be > failing, and the corruption in the file looks more like a > software bug than a hardware issue.) I too have encountered, when doing some heavy *EDIT-RUN- EDIT* sessions, where Python was still using an old pyc file that did not correctly sync with the modified code in my editor. And in some cases i was able to verify the bug by changing a symbol and noting that the exception reports a reference to the old (now non-existent) symbol. Sadly when this happens i am usually too busy to stop and spend time chasing down the source: is it my editor, or is this a Python issue, or something more subtle??? My quick fix is to run a Python script that deletes all my .pyc files and everything is all peaches and cream again. Mmm, peaches! So yes, anecdotal evidence does support your argument that: "machines can screw up". -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
In article <[email protected]>, [email protected] says... > > On Thursday, January 22, 2015 at 10:04:29 PM UTC-6, Chris Angelico wrote: > > > It's worth pointing out, too, that the idea isn't > > panaceaic - it's just another tool in the box. Any time > > you break related things into separate places, especially > > separate files, the tendency for them to get out of sync > > grows dramatically. > > I wonder how that "poor python interpreter" keeps all those > .pyc and .pyo files in sync with constantly changing source > code? It should be tantamount to torture! Will someone > *PLEASE* start a charity site titled: "Python's sanity fund"? > The process is automatic and based exclusively on timestamps. What you propose is manual labor and therein lies the rub. You have to remember to update your static analysis files when you update your code. And it is not always easy to do it, especially in team development environments. This is also going to complicate user work and the static analysis parser work. Function headers need to be matched with the annotated description in another file. Because of namespaces this will leave room for ambiguity, unless you mirror in the type hinting file the complete function signature, which must include its namespace. That is, you need a syntax that at the very least includes class declarations, but should probably also consider local namespaces and modules. All because you are not matching directly a type annotation with the type declaration in the code. ... In any case, I agree entirely with you that type annotation is one ugly syntax to a programming language that is touted everywhere as being simple and easy to read. I would say that the mistake started 5 years ago, and I am surprised how you guys let that horrible PEP pass. I wasn't around then, so I'm off the hook. Some folks in here argue that complex type annotations will be rare, since functions should be designed as straightforward units of code with simple requirements and respecting certain best practices, like separation of concerns, low cyclomatic complexity, adapt well to simple unit tests, bla bla bla. But the actual practice of coding software is very different. We generally code bad software and generally avoid best practices if they get in the way of our schedules, our knowledge, and even our ability. And there is always the problem of OOP, which is a magnificent source of complex function declarations in terms of the types they receive and output. I think that you are right in that we shouldn't pollute our code with static analysis shit. We shouldn't pollute our code period. But There's better ways of doing it without resorting to external files. I'd say Steven D'Aprano example of Cobra hit my sweet spot. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On 1/23/15, Chris Angelico wrote: > On Sat, Jan 24, 2015 at 12:23 AM, Fetchinson . > wrote: >> In any case, I'm pretty sure it was said before, but I can't really >> find it anywhere, can someone tell me what the rationale is for >> *function signature* type hinting? >> >> I totally get type hinting in general, but why does it have to be in >> the function signature? Any reason for that specifically? > > Is there any particular reason for the number of arguments to be part > of the function signature? I guess this is a rhetorical question :) > I totally get the notion of declaring how > many arguments a function takes, but why does it have to be in the > function signature? Ditto :) > Data types are just as much a part of that signature as argument count > is. I guess this would be true if there weren't about 5 other alternative proposals which solve the exact same problem (type hinting) by other means. Luckily, these will be listed in the PEP soon and the reason for rejecting them will be there as well, and so my question will pretty much be answered there. https://github.com/ambv/typehinting/issues/55 > You could argue that the function's return type isn't part of > that, but that's about it. >> If there is a pep for it, people will use it, so the fact that >> it is optional is irrelevant... > > Function annotations were introduced in 2006 (Python 3.0) with PEP 3107: > > https://www.python.org/dev/peps/pep-3107/ > > They were optional then, they are still optional now. Have you been > overrun with them for the past decade? If not, why do you expect now > to be? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
In article <[email protected]>, [email protected] says... > > Injecting polarity into debates is dangerous, because, then > we get off into the emotional weeds and a solution may never > be found -- just observe the polarization of American > politics if you don't believe me --> *PUKE* I agree entirely. But you have to excuse me... weren't you the one calling Guido lapdog (you used worse names) to anyone who agreed with the PEP? ;) Don't been an hypocrit also, when Rantingrick is good enough. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 3:02:57 PM UTC-6, Mario Figueiredo wrote: > In any case, I agree entirely with you that type > annotation is one ugly syntax to a programming language > that is touted everywhere as being simple and easy to > read. I would say that the mistake started 5 years ago, > and I am surprised how you guys let that horrible PEP > pass. I wasn't around then, so I'm off the hook. > > Some folks in here argue that complex type annotations > will be rare, since functions should be designed as > straightforward units of code with simple requirements and > respecting certain best practices, like separation of > concerns, low cyclomatic complexity, adapt well to simple > unit tests, bla bla bla. But the actual practice of coding > software is very different. We generally code bad software > and generally avoid best practices if they get in the way > of our schedules, our knowledge, and even our ability. And > there is always the problem of OOP, which is a magnificent > source of complex function declarations in terms of the > types they receive and output. > > I think that you are right in that we shouldn't pollute > our code with static analysis shit. We shouldn't pollute > our code period. But There's better ways of doing it > without resorting to external files. > > I'd say Steven D'Aprano example of Cobra hit my sweet > spot. Yes and this is what i meant when i said "cutting the baby in half". Although stub files have many advantages, i'll admit they are onerous for the authors. So the compromise would be to keep the hints in the same file for which they are applied, but to separate them from the func arguments: (Example modified for PEP8 compliance ;-) @typehint(arg1:str, arg2:int, returns:bool) def myfunction(arg1, arg2): return True Of course "@typehint" could be an extension of the decorator syntax, a keyword, a build-in function or whatever, i don't care. That's an acceptable compromise for me. It's not completely satisfactory, but at least i can read parameters without needing to ignore type noise -- gawd that is so annoying! Today's repressed look of disapproval brought to you by: Angry Java Programmers Everywhere! -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
Is there a way to do it without calling external utilities (i.e. a Python module, etc)? I'd rather stay within the realm of Python if possible. Jason On 01/23/2015 10:04 AM, Chris Angelico wrote: On Sat, Jan 24, 2015 at 3:02 AM, Jason Bailey wrote: I'm actually wondering if it might be more beneficial for me to check if the local DHCP port (udp 67) is bound and in use. I had tried to do this some time ago, and couldn't get it working right (it would always test true, even when it shouldn't have). Can anyone steer me in the right direction on port status? You can check with netstat: $ sudo netstat -n4lp|grep ':67 ' udp0 0 0.0.0.0:67 0.0.0.0:* 22466/dhcpd On my system, there's a /proc/net/udp which carries this information. Everything's in hex, so port 67 is shown as 0043: $ grep :0043 /proc/net/udp 5755: :0043 : 07 : 00: 00 8334454 2 880403e60b40 0 You'd have to check your own system to know what's truly reliable and worth using. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 3:13:12 PM UTC-6, Mario Figueiredo wrote: > In article <[email protected]>, > Sir Richard Johnson The First says... > > > > Injecting polarity into debates is dangerous, because, > > then we get off into the emotional weeds and a solution > > may never be found -- just observe the polarization of > > American politics if you don't believe me --> *PUKE* > > I agree entirely. But you have to excuse me... weren't you > the one calling Guido lapdog (you used worse names) to > anyone who agreed with the PEP? ;) I was not calling *ANYONE* who agreed with the PEP "a lapdog", my statement was more specific. I called Chris a "lapdog of" and a "rabbid fanboy" -- Guido was merely the "implied Satan". Of course i'm not suggesting that Guido is a malevolent godlike being, his inclusion in the expression is merely a incidental result of Chris's idol worship of "everything Guido". Although, to be fair, I guess i may have embellished a bit by using the word "rabbid", and for that i apologize. But to respond to your assertion that i'm being hypocritical: nonsense. Stating facts is *NEVER* hypocritical. Just because a fact happens to be an "inconvenient truth" does not invalidate it's truthfulness. Chris (or anybody for that matter) can choose to be a free thinking individual, or a brainwashed disciple, the choice is his. Even intelligent people (like Chris) can fall under the spell of a "implicit cult of personality". -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
On Friday, January 23, 2015 at 2:07:04 PM UTC-8, Jason Bailey wrote: > Is there a way to do it without calling external utilities (i.e. a > Python module, etc)? I'd rather stay within the realm of Python if possible. > > Jason > > > > On 01/23/2015 10:04 AM, Chris Angelico wrote: > > On Sat, Jan 24, 2015 at 3:02 AM, Jason Bailey > > wrote: > >> I'm actually wondering if it might be more beneficial for me to check if > >> the > >> local DHCP port (udp 67) is bound and in use. I had tried to do this some > >> time ago, and couldn't get it working right (it would always test true, > >> even > >> when it shouldn't have). Can anyone steer me in the right direction on port > >> status? > > You can check with netstat: > > > > $ sudo netstat -n4lp|grep ':67 ' > > udp0 0 0.0.0.0:67 0.0.0.0:* > > 22466/dhcpd > > > > On my system, there's a /proc/net/udp which carries this information. > > Everything's in hex, so port 67 is shown as 0043: > > > > $ grep :0043 /proc/net/udp > > 5755: :0043 : 07 : 00: > > 00 8334454 2 880403e60b40 0 > > > > You'd have to check your own system to know what's truly reliable and > > worth using. > > > > ChrisA First off, don't top post. Either use the interleaved or bottom-posting style. https://en.wikipedia.org/wiki/Posting_style#Interleaved_style Secondly, even if you find a module, keep in mind that the module probably won't stay in Python land. It will probably call an external utility itself. If you REALLY wanted to check it without calling an external utility, you could connect to port 67 and see what happens, but that could cause problems. -- https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
On Monday, January 19, 2015 at 4:16:13 PM UTC-8, Luke Tomaneng wrote: > Has anyone noticed these? There have been about three of them recently and > they don't seem to have anything to do with Python at all. Does anyone know > if there is a good reason they are here? My question is, does anyone know what the hell they're ranting about? -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
In article <[email protected]>, [email protected] says... > > (Example modified for PEP8 compliance ;-) > > @typehint(arg1:str, arg2:int, returns:bool) > def myfunction(arg1, arg2): > return True > > Of course "@typehint" could be an extension of the decorator > syntax, a keyword, a build-in function or whatever, i don't > care. I'd rather it'd be a docstring parameter. - Decorators are transformation tools. Which type hints are not. - keywords should be few and used only for language features. Static analysis isn't and should never be a language feature. It's an extension, perhaps. - Same with built-in functions... although a case could be made for a static analysis package, hmmm. So I'd rather see: def myfunction(arg1, arg2): """ Normal docstring. """ "@typehint: (str, int) -> bool" return True This conforms to PEP 258, but not to PEP 8, but you can always use the triple quotes. I would just use the single-quote myself for matters of taste. I removed the arguments names on purpose. They are only necessary on the PEP because type hinting is a part of the function header there. However, when using a documentation like pattern as above (or as in your own example), they can be safely removed, with the added benefit of making the syntax simpler. Alternatively, because dangling strings are always considered documentation and completely ignored by the interpreter (PEP 258), one could also do: "@typehint: (str, int) -> bool" def myfunction(arg1, arg2): """ Normal docstring. """ return True Again the choice of triple quotes or not is something not worth debating. -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
On Sat, Jan 24, 2015 at 9:38 AM, wrote: > Secondly, even if you find a module, keep in mind that the module probably > won't stay in Python land. It will probably call an external utility itself. > > If you REALLY wanted to check it without calling an external utility, you > could connect to port 67 and see what happens, but that could cause problems. We're talking UDP here, so there's no "connect to" concept. You have to send a packet and listen for a reply, and that might have consequences (eg if you send a DHCPDISCOVER just to find out if there's a DHCP server, you potentially cause a temporary IP allocation). Reading from /proc or running an external program would be the best ways to find out. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
In article , [email protected] says... > > > So I'd rather see: > > def myfunction(arg1, arg2): > """ > Normal docstring. > """ > "@typehint: (str, int) -> bool" > return True > Actually that is idiotic. Much better is: def myfunction(arg1, arg2): """ Normal docstring... @typehint: (str, int) -> bool """ return True Why would I need to insert an extra docstring, if I'm already defining a parameter? -- https://mail.python.org/mailman/listinfo/python-list
Re: What killed Smalltalk could kill Python
On Thursday, January 22, 2015 at 9:39:53 PM UTC-8, alex23 wrote: > On 22/01/2015 1:23 PM, Steven D'Aprano wrote: > > Modern games *are* part of "today's complex application systems", and games > > developers may need the same skills used by "serious developers" > > I wish more game developers would understand this. I've lost count of > the number of games that have failed during development because all of > the source code was stolen or destroyed. I've had arguments with game > devs (some who've worked at some of the bigger studios) because they're > convinced that nothing outside of game development has anything to teach > them...when their (for eg) revision control entails zipping up their > daily changes and emailing them to the rest of the team... Could be worse. I seem to recall an interview with someone from Blizzard Entertainment mentioning that the first Warcraft game (Released in 1994) was developed by passing around floppy disks with new code among the developers. Though I imagine that was actually probably pretty common back then. But yeah...if you have more than 1 developer, version control of some sort just isn't optional. Having to manually merge changes is extremely tedious. If you're a solo developer, its still a good idea. Even if you don't take advantage of branching and undoing commits, it's good to at least have a backup of your code somewhere. -- https://mail.python.org/mailman/listinfo/python-list
Re: What killed Smalltalk could kill Python
On 01/21/2015 05:55 PM, Chris Angelico wrote: > On Thu, Jan 22, 2015 at 10:37 AM, Tim Daneliuk wrote: >> I find these kinds of discussions sort of silly. Once there is a critical >> mass of installed base, no language EVER dies. > > Not sure about that. Back in the 1990s, I wrote most of my code in > REXX, either command-line or using a GUI toolkit like VX-REXX. Where's > REXX today? Well, let's see. It's still the native-ish language of > OS/2. Where's OS/2 today? Left behind. REXX has no Unicode support (it > does, however, support DBCS - useful, no?), no inbuilt networking > support (there are third-party TCP/IP socket libraries for OS/2 REXX, > but I don't know that other REXX implementations have socket services; > and that's just basic BSD sockets, no higher-level protocol handling > at all), etc, etc. Sure, it's not technically dead... but is anyone > developing the language further? I don't think so. Is new REXX code > being written? Not a lot. Yet when OS/2 was more popular, REXX > definitely had its installed base. It was the one obvious scripting > language for any OS/2 program. Languages can definitely die, or at > least be so left behind that they may as well be dead. > > ChrisA > Rexx is still well used on mainframes. -- Tim Daneliuk [email protected] PGP Key: http://www.tundraware.com/PGP/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 2:46:01 PM UTC-8, Mario Figueiredo wrote: > In article , [email protected] > says... > > > > > > So I'd rather see: > > > > def myfunction(arg1, arg2): > > """ > > Normal docstring. > > """ > > "@typehint: (str, int) -> bool" > > return True > > > > Actually that is idiotic. Much better is: > > def myfunction(arg1, arg2): > """ > Normal docstring... > @typehint: (str, int) -> bool > """ > return True > > Why would I need to insert an extra docstring, if I'm already defining a > parameter? I really like that implementation. Its unobtrusive and doesn't clutter the function definition, and putting in the docstring makes it get colored like a comment (At least, with my IDE setup it does) so it is easily ignored by my eyes as I'm scrolling through. -- https://mail.python.org/mailman/listinfo/python-list
Re: What killed Smalltalk could kill Python
On Sat, Jan 24, 2015 at 9:51 AM, Tim Daneliuk wrote: > On 01/21/2015 05:55 PM, Chris Angelico wrote: >> On Thu, Jan 22, 2015 at 10:37 AM, Tim Daneliuk wrote: >>> I find these kinds of discussions sort of silly. Once there is a critical >>> mass of installed base, no language EVER dies. >> >> Not sure about that. Back in the 1990s, I wrote most of my code in >> REXX, either command-line or using a GUI toolkit like VX-REXX. Where's >> REXX today? Well, let's see. It's still the native-ish language of >> OS/2. Where's OS/2 today? Left behind. REXX has no Unicode support (it >> does, however, support DBCS - useful, no?), no inbuilt networking >> support (there are third-party TCP/IP socket libraries for OS/2 REXX, >> but I don't know that other REXX implementations have socket services; >> and that's just basic BSD sockets, no higher-level protocol handling >> at all), etc, etc. Sure, it's not technically dead... but is anyone >> developing the language further? I don't think so. Is new REXX code >> being written? Not a lot. Yet when OS/2 was more popular, REXX >> definitely had its installed base. It was the one obvious scripting >> language for any OS/2 program. Languages can definitely die, or at >> least be so left behind that they may as well be dead. >> >> ChrisA >> > > Rexx is still well used on mainframes. Oh, is it? Cool! Maybe some day I'll be interviewing for a job, and they'll ask if I know REXX.. and I'll actually be able to say yes. :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: What killed Smalltalk could kill Python
On 1/23/2015 2:48 PM, [email protected] wrote: On Thursday, January 22, 2015 at 9:39:53 PM UTC-8, alex23 wrote: I seem to recall an interview with someone from Blizzard Entertainment mentioning that the first Warcraft game (Released in 1994) was developed by passing around floppy disks with new code among the developers. Though I imagine that was actually probably pretty common back then. It even had a formal name -- sneakernet Emile -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
In article , [email protected] says... > > > def myfunction(arg1, arg2): > > """ > > Normal docstring... > > @typehint: (str, int) -> bool > > """ > > return True > > > > I really like that implementation. > > Its unobtrusive and doesn't clutter the function definition, and > putting in the docstring makes it get colored like a comment (At > least, with my IDE setup it does) so it is easily ignored by my eyes > as I'm scrolling through. It has the side effect of being included in __doc__. A purist may have an issue with that, since type hinting, for the purposes of static analysis, should have no place in that attribute. But you could always fall back to the previous version: def myfunction(arg1, arg2): """ Normal docstring... """ "@typehint: (str, int) -> bool" return True And __doc__ would be free of it. It would be up to the user to choose. For something completely different, I like @hint: better than @typehint: -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
On Friday, January 23, 2015 at 2:50:12 PM UTC-8, Chris Angelico wrote: > On Sat, Jan 24, 2015 at 9:38 AM, wrote: > > Secondly, even if you find a module, keep in mind that the module probably > > won't stay in Python land. It will probably call an external utility > > itself. > > > > If you REALLY wanted to check it without calling an external utility, you > > could connect to port 67 and see what happens, but that could cause > > problems. > > We're talking UDP here, so there's no "connect to" concept. You have > to send a packet and listen for a reply, and that might have > consequences (eg if you send a DHCPDISCOVER just to find out if > there's a DHCP server, you potentially cause a temporary IP > allocation). > > Reading from /proc or running an external program would be the best > ways to find out. > > ChrisA I forgot that DHCP uses UDP. My mistake. -- https://mail.python.org/mailman/listinfo/python-list
Re: Check for running DHCP daemon?
On Sat, Jan 24, 2015 at 10:21 AM, wrote: > On Friday, January 23, 2015 at 2:50:12 PM UTC-8, Chris Angelico wrote: >> On Sat, Jan 24, 2015 at 9:38 AM, wrote: >> > Secondly, even if you find a module, keep in mind that the module probably >> > won't stay in Python land. It will probably call an external utility >> > itself. >> > >> > If you REALLY wanted to check it without calling an external utility, you >> > could connect to port 67 and see what happens, but that could cause >> > problems. >> >> We're talking UDP here, so there's no "connect to" concept. You have >> to send a packet and listen for a reply, and that might have >> consequences (eg if you send a DHCPDISCOVER just to find out if >> there's a DHCP server, you potentially cause a temporary IP >> allocation). >> >> Reading from /proc or running an external program would be the best >> ways to find out. >> >> ChrisA > > I forgot that DHCP uses UDP. My mistake. Yeah, it's usually easier to probe a TCP service. You can either connect to it, or - often - simply try to bind to the same port, as you'll usually get an error. Not always, though, so connecting is the reliable test. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Friday, January 23, 2015 at 4:42:51 PM UTC-6, Mario Figueiredo wrote: > I'd rather it'd be a docstring parameter. > > - Decorators are transformation tools. Which type hints > are not. Valid point. > - keywords should be few and used only for language > features. Static analysis isn't and should never be a > language feature. It's an extension, perhaps. Indeed. I've always been fond of Python's relatively small set of keywords, and avoiding additions is a noble goal. It seems like we've entered an era of increasing feature creep. > - Same with built-in functions... although a case could be > made for a static analysis package, hmmm. > > So I'd rather see: > > def myfunction(arg1, arg2): > """ > Normal docstring. > """ > "@typehint: (str, int) -> bool" > return True > I think extending the doc-string syntax is good idea since there is nothing going on in there anyway. It's sort of like a treasure just waiting to be plundered. Plus, I find i can easily ignore doc-strings, whereas, adding a new syntax is going to be a syntactical distraction no matter how "clean" it may be. Heck, even after years of reading Python source, function decorators still jump out at me like lions from behind a bush! And although i think one could make a good argument that decorators *ought-to-be* obvious because of the resulting unavoidable implications of them, i don't believe the same argument applies to a feature which simply serves as an "optional hook" for static analysis tools -- for which the implications are entirely dependent on purposeful actions by a programmer -- any other time it's just dead code. > Alternatively, because dangling strings are always > considered documentation and completely ignored by the > interpreter (PEP 258), one could also do: > > "@typehint: (str, int) -> bool" > def myfunction(arg1, arg2): > """ > Normal docstring. > """ > return True > Ha, well one of the more wonderful aspects of being an "opposer" (as opposed to a "proposer") is that you can omit yourself from the headaches of the implementation details O:-). I say: they wanted type hints, fine, let them suffer the headaches of hacking the interpreter. My only goal (at this point) is ensuring that their little intellectual "problem child" does not walk on my wonderfully lush and finely manicured lawn. KEEP OFF MY GRASS!!! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
Mario Figueiredo : > Much better is: > > def myfunction(arg1, arg2): > """ > Normal docstring... > @typehint: (str, int) -> bool > """ > return True I seem to remember an idea floated on the Scheme mailing list of using assertions for such a purpose: def myfunction(arg1, arg2): assert isinstance(arg1, str) and isinstance(arg2, int) return True The advantage is that the assertions can be as complex as you'd like: def weekday(day): assert isinstance(day, int) and 0 <= day <= 6 ... def str_product(x, y): assert isinstance(x, int) and isinstance(y, str) or \ isinstance(x, str) and isinstance(y, int) ... Also, they have always been present in the language and assertion semantics is fully compatible with static analysis. Only I'd hate if that style became standard boilerplate... Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On 23/01/15 04:53, Steven D'Aprano wrote: If your manager is so bad, why isn't he insisting that you program in PHP or Java or Algol 68 [insert name of some language you dislike] instead of Python? Is your bad manager forcing you to write Java-style code in Python, or insisting on Hungarian Notation? Nobody is forcing me to do anything. But without a thriving community, Python has no value to me. If we add type hinting, then that community will go away, because other languages are better options. Who will win? Julia? Ruby? They are all waiting in line for Python to fail. Then Python will be like Smalltalk. Sturla -- https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
On 1/23/2015 5:40 PM, [email protected] wrote: On Monday, January 19, 2015 at 4:16:13 PM UTC-8, Luke Tomaneng wrote: Has anyone noticed these? There have been about three of them recently and they don't seem to have anything to do with Python at all. Does anyone know if there is a good reason they are here? They are spam that made it past the spam filter. Ignore them. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On Sat, Jan 24, 2015 at 12:00 PM, Sturla Molden wrote: > But without a thriving community, Python has no value to me. > > If we add type hinting, then that community will go away, because other > languages are better options. > > Who will win? Julia? Ruby? They are all waiting in line for Python to fail. > Then Python will be like Smalltalk. The Python community that was already killed by Python 3.0? Funny, it seems to be a bit more resilient than the naysayers would have us believe. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
On Thursday, January 22, 2015 at 10:23:48 PM UTC-6, Steven D'Aprano wrote: > Rick Johnson wrote: > > > The solution is move the type hinting syntax completely > > out of the source file and into another file -- think of > > it as a "Python Type Hinting Header File". > > The 1970s called, they want their bad ideas back. [...] > Things that go together should appear together. Imagine a > language where you declared the function name in one file, > the function parameters in a second file, any default > values in a third file, and the function body in a fourth > file. Ridiculous. Ideally, all these things should be > found together, preferably close enough for the reader to > take it all in at a glance (although some function bodies > may be too large). Anyone else care for a pipping hot cup of Reductio ad absurdum? > There may be times where splitting related things are > unavoidable, but they should be a last resort, only to be > used when any other solution is unacceptable. Duh! Do you think i just pulled stub files out my arse without giving all the other alternatives due consideration? But you had your fun so that's all that matters. ;-) PS: Man, you need to invest in some formatting tools. I format all my posts with a max width of 60, but then when you quote them back i see strange line breaks. Does your editor think that 60 chars is too wide? What's going on? -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 11:35:49 PM UTC+5:30, Ian wrote: > On Fri, Jan 23, 2015 at 10:03 AM, Rustom Mody wrote: > > On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: > >> On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: > >> > Can you tell me what of the following code does not satisfy your > >> > requirements? > >> > [Needs python 3.4] > >> > > >> > > >> from enum import IntEnum > >> class B4(IntEnum): > >> > F1 = 0 > >> > F2 = 0 > >> > F3 = 0 > >> > T = 1 > >> > >> This strikes me as a potential problem: > >> > >> >>> B4.F1 is B4.F2 is B4.F3 > >> True > >> >>> list(B4) > >> [, ] > >> > >> Enum members with the same values are just aliases for one another, > >> not distinct entities. > > > > Yeah > > > > The only workaround I have been able to come up with is: > > > > class B4(IntEnum): > >> F1 = 0 > >> F2 = "" > >> F3 = None > >> T = 1 > > > > which is not bad; its ridiculous > > [Like going around with a broken broom searching for falsey objects :-) ] > > How about something like this: > > >>> from enum import Enum > >>> class B4(Enum): > ... F1 = (False, 1) > ... F2 = (False, 2) > ... F3 = (False, 3) > ... T = (True, 4) > ... def __bool__(self): > ... return self.value[0] > ... > >>> B4.F1 is B4.F2 > False > >>> bool(B4.F1) > False > >>> bool(B4.T) > True ‼Perfect‼ For the OP you may like to read the following: [And if you dont short version is use __bool__ in python3 __nonzero__ in python2 ] http://stackoverflow.com/questions/8909932/how-to-overload-pythons-bool-method http://stackoverflow.com/questions/2233786/overriding-bool-for-custom-class https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Friday, January 23, 2015 at 11:35:49 PM UTC+5:30, Ian wrote: > On Fri, Jan 23, 2015 at 10:03 AM, Rustom Mody wrote: > > On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: > >> On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: > >> > Can you tell me what of the following code does not satisfy your > >> > requirements? > >> > [Needs python 3.4] > >> > > >> > > >> from enum import IntEnum > >> class B4(IntEnum): > >> > F1 = 0 > >> > F2 = 0 > >> > F3 = 0 > >> > T = 1 > >> > >> This strikes me as a potential problem: > >> > >> >>> B4.F1 is B4.F2 is B4.F3 > >> True > >> >>> list(B4) > >> [, ] > >> > >> Enum members with the same values are just aliases for one another, > >> not distinct entities. > > > > Yeah > > > > The only workaround I have been able to come up with is: > > > > class B4(IntEnum): > >> F1 = 0 > >> F2 = "" > >> F3 = None > >> T = 1 > > > > which is not bad; its ridiculous > > [Like going around with a broken broom searching for falsey objects :-) ] > > How about something like this: > > >>> from enum import Enum > >>> class B4(Enum): > ... F1 = (False, 1) > ... F2 = (False, 2) > ... F3 = (False, 3) > ... T = (True, 4) > ... def __bool__(self): > ... return self.value[0] > ... > >>> B4.F1 is B4.F2 > False > >>> bool(B4.F1) > False > >>> bool(B4.T) > True Simpler (though less general) class B4(Enum): F1 = 1 F2 = 2 F3 = 3 T = 4 def __bool__(self): return self.value == 4 -- https://mail.python.org/mailman/listinfo/python-list
Re: Random ALL CAPS posts on this group
On Friday, January 23, 2015 at 6:05:02 AM UTC-6, Chris Angelico wrote: > It's definitely not "state vs non-state". Freedom of > expression should allow me to say anything I like in my > own home I also hereby declare that man should be free to ponder thoughts in his own mind, and sing in his own shower, and watch his own TV, and even yank his own wank! Now hurry along Chris. MAKE HASTE! We must liberate the people of this world with knowledge of these newly found rights!!! -- https://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing.Queue & vim python interpreter
On 18Jan2015 16:20, [email protected] wrote: I am experimenting on a fork of vim-plug for managing vim plugins. I wanted to add parallel update support for python since ruby isn't nearly as common. I've come across a weird bug that only seems to happen when I'm inside vim, I'm wondering if someone could tell me why. This problem can be reproduced by sourcing a vim file with the following snippet. Then execute the command PyCrash. command! -nargs=0 PyCrash call s:py_crash() function! s:py_crash() python << EOF import multiprocessing as multi queue = multi.Queue() queue.put('a') queue.close() EOF endfunction This prints to messages the following: Traceback (most recent call last): File "/usr/lib/python2.7/multiprocessing/queues.py", line 266, in _feed send(obj) IOError: [Errno 32] Broken pipe Please include the entire traceback in errors. I would guess this is because you have made a Queue but have not got subprocess to read from it. So when you .put onto it, you get a broken pipe. Cheers, Cameron Simpson Nothing is impossible for the man who doesn't have to do it. -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On Thursday, January 22, 2015 at 10:43:30 PM UTC+5:30, Automn wrote: > Hello, > > I am programming a "Secret of Mana" (Seiken Densetsu) game in kivy, it runs > on a phone with kivy launcher. > > Features for now are : movement by swiping, polygon collision and image state > changes with resource handling. > > The codebase can be found at : > https://sourceforge.net/projects/kivypriestsoflore2 > > The graphics have been licensed for this. > > Automn > -- > my blog : http://thediaryofelvishhealer.blogspot.com/ > Time heals. Is this runnable on a computer? [I mean the old fashioned ones that sit on desks] I tried installing it and am getting rusi@Gpa:~$ python3 kk.py [INFO ] Kivy v1.8.0 [INFO ] [Logger ] Record log in /home/rusi/.kivy/logs/kivy_15-01-24_3.txt [INFO ] [Factory ] 157 symbols loaded [DEBUG ] [Cache ] register with limit=None, timeout=Nones [DEBUG ] [Cache ] register with limit=None, timeout=60s [DEBUG ] [Cache ] register with limit=None, timeout=Nones [INFO ] [Image ] Providers: img_tex, img_dds, img_gif (img_pygame, img_pil ignored) [DEBUG ] [Cache ] register with limit=1000, timeout=60s [DEBUG ] [Cache ] register with limit=1000, timeout=3600s [DEBUG ] [App ] Loading kv <./pong.kv> [DEBUG ] [App ] kv <./pong.kv> not found [DEBUG ] [Window ] Ignored (import error) [DEBUG ] [Window ] Ignored (import error) [WARNING] [WinPygame ] SDL wrapper failed to import! [DEBUG ] [Window ] Ignored (import error) [DEBUG ] [Window ] Ignored (import error) [CRITICAL] [Window ] Unable to find any valuable Window provider at all! [CRITICAL] [App ] Unable to get a Window, abort. -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On Saturday, January 24, 2015 at 9:36:56 AM UTC+5:30, Rustom Mody wrote: > On Thursday, January 22, 2015 at 10:43:30 PM UTC+5:30, Automn wrote: > > Hello, > > > > I am programming a "Secret of Mana" (Seiken Densetsu) game in kivy, it runs > > on a phone with kivy launcher. > > > > Features for now are : movement by swiping, polygon collision and image > > state > > changes with resource handling. > > > > The codebase can be found at : > > https://sourceforge.net/projects/kivypriestsoflore2 > > > > The graphics have been licensed for this. > > > > Automn > > -- > > my blog : http://thediaryofelvishhealer.blogspot.com/ > > Time heals. > > Is this runnable on a computer? > [I mean the old fashioned ones that sit on desks] > > I tried installing it and am getting > > rusi@Gpa:~$ python3 kk.py > [INFO ] Kivy v1.8.0 > [INFO ] [Logger ] Record log in > /home/rusi/.kivy/logs/kivy_15-01-24_3.txt > [INFO ] [Factory ] 157 symbols loaded > [DEBUG ] [Cache ] register with limit=None, timeout=Nones > [DEBUG ] [Cache ] register with limit=None, timeout=60s > [DEBUG ] [Cache ] register with limit=None, timeout=Nones > [INFO ] [Image ] Providers: img_tex, img_dds, img_gif (img_pygame, > img_pil ignored) > [DEBUG ] [Cache ] register with limit=1000, timeout=60s > [DEBUG ] [Cache ] register with limit=1000, timeout=3600s > [DEBUG ] [App ] Loading kv <./pong.kv> > [DEBUG ] [App ] kv <./pong.kv> not found > [DEBUG ] [Window ] Ignored (import error) > [DEBUG ] [Window ] Ignored (import error) > [WARNING] [WinPygame ] SDL wrapper failed to import! > [DEBUG ] [Window ] Ignored (import error) > [DEBUG ] [Window ] Ignored (import error) > [CRITICAL] [Window ] Unable to find any valuable Window provider at all! > [CRITICAL] [App ] Unable to get a Window, abort. Ok After installing pygame I get the black window of the first pong example However Ive to run it as root else I get PermissionError: [Errno 13] Permission denied: '/dev/input/event4' self._fd = os.open(filename, os.O_NONBLOCK | os.O_RDONLY) PermissionError: [Errno 13] Permission denied: '/dev/input/event9 -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
[email protected] wrote: > On Friday, January 23, 2015 at 10:10:08 AM UTC-8, Tony the Tiger wrote: >> On Thu, 22 Jan 2015 17:13:12 +, Automn wrote: >> >> > game >> >> No interest, at all, nada, zilch. zero, nothing. >> >> /Grrr > > Why don't you like fun? I had fun once. It was horrible. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy secret of mana game
On Sat, Jan 24, 2015 at 3:53 PM, Steven D'Aprano wrote: > I had fun once. It was horrible. You probably had it boiled. The proper way to have fun is fried in garlic butter, with a bit of salt. Try having some real home-cooked fresh fun, I think you'll like it. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
Rustom Mody wrote: > On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote: >> On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote: >> > Can you tell me what of the following code does not satisfy your >> > requirements? >> > [Needs python 3.4] >> > >> > >> from enum import IntEnum >> class B4(IntEnum): >> > F1 = 0 >> > F2 = 0 >> > F3 = 0 >> > T = 1 >> >> This strikes me as a potential problem: >> >> >>> B4.F1 is B4.F2 is B4.F3 >> True >> >>> list(B4) >> [, ] >> >> Enum members with the same values are just aliases for one another, >> not distinct entities. > > Yeah > > The only workaround I have been able to come up with is: > > class B4(IntEnum): >> F1 = 0 >> F2 = "" >> F3 = None >> T = 1 > > which is not bad; its ridiculous > [Like going around with a broken broom searching for falsey objects :-) ] It certainly is. But fortunately it is not necessary. # Untested class B4(IntEnum): F1 = 0 F2 = 1 F3 = 2 T = 3 def __bool__(self): return self is B4.T def __str__(self): if self is B4.F1: return "Certainly False" if self is B4.F2: return "Maybe False" if self is B4.F3: return "Maybe True" if self is B4.T: return "Certainly True" -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
Marko Rauhamaa wrote:
> I seem to remember an idea floated on the Scheme mailing list of using
> assertions for such a purpose:
>
>def myfunction(arg1, arg2):
>assert isinstance(arg1, str) and isinstance(arg2, int)
>return True
>
> The advantage is that the assertions can be as complex as you'd like:
>
>def weekday(day):
>assert isinstance(day, int) and 0 <= day <= 6
>...
>
>def str_product(x, y):
>assert isinstance(x, int) and isinstance(y, str) or \
>isinstance(x, str) and isinstance(y, int)
>...
>
> Also, they have always been present in the language and assertion
> semantics is fully compatible with static analysis.
Not really. Well, I suppose technically they could be, if the type-checker
included a full Python interpreter.
Requiring the type-checker to parse and understand arbitrarily complex
assertions would require the type-checker to be as complex as Python
itself:
def f(something):
assert (__import__("somemodule") is
some_function(spam, eggs, *ham, **cheese).attr.x[y](z) or
any(some_expression and another_expression
for a, b, c, d in my_module.map(something, fe, fi, fo, fum)
if some_condition(a) or b == c[d]) and
are_you_confused_yet() if foo else bar or eval(expr, ns) < 23
or open('config').read(100)[23:27] == 'okay')
Fortunately, type systems are generally not fully Turing complete and are
usually significantly more restricted. PEP 484 doesn't mandate an upper
limit to how clever the type-checker must be, it only sets a common syntax
which type-checkers are expected to support. That is significant less
complex than a full Python parser, and should be lightweight enough that
IDEs and editors can use type-hints for providing text completion and
hints.
(This means that type-checkers are permitted to parse assertions, but they
aren't required to.)
Assertions also have the problem that they execute arbitrarily complex code
at runtime. Type annotations also execute code at runtime, but they're not
expected to be arbitrarily complex: mostly name lookups.
Lastly, this use of assertions clashes with "best practice" for assertions.
Since assertions may be disabled, you should not use them for testing
user-supplied arguments. So that means you have to write:
def func(arg):
assert isinstance(arg, int) # satisfy the type checker
if isinstance(arg, int): # support times when assert is disabled
...
which is not only ugly, but every call requires *two* isinstance checks. It
also means that when asserts are enabled you get a different exception for
bad data than when they are disabled.
This doesn't apply to annotations:
def func(arg:int):
# since this is a public function, not private, we cannot assume the
# caller will run the type-checker
if isinstance(arg, int):
...
In this case, the overhead from the "arg:int" annotation is trivial: a
single name lookup and binding when the function is created, not when it is
called.
Sufficiently clever type-checkers may use assertions to infer types, but
requiring this is a non-starter.
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
On Sat, Jan 24, 2015 at 4:29 PM, Steven D'Aprano
wrote:
> Sufficiently clever type-checkers may use assertions to infer types, but
> requiring this is a non-starter.
Or they could use the isinstance checks themselves to infer types.
def func(arg):
if not isinstance(arg, int): raise ValueError("Expected an integer")
It's fairly straight-forward to do an AST parse on a module, iterate
over it for functions, and then look for a specific pattern like the
above:
If(test=UnaryOp(op=Not(), operand=Call(func=Name(id='isinstance',
ctx=Load()), args=[Name(id='arg', ctx=Load()), Name(id='int',
ctx=Load())], keywords=[], starargs=None, kwargs=None)),
body=[Raise(exc=Call(func=Name(id='ValueError', ctx=Load()),
args=[Str(s='Expected an integer')], keywords=[], starargs=None,
kwargs=None), cause=None)], orelse=[])
... okay, that's not exactly pretty, but it's still a straight-forward
structure. But having just watched a PyCon talk about PyPy and RPython
and type inference, it's pretty clear that static analysis can do a
*lot* more than this; so really, looking for isinstance checks is both
too hard and too simplistic to be really worth doing. Type hinting is
a different beast.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and sorting of a numeric class....
On Sat, Jan 24, 2015 at 4:01 PM, Steven D'Aprano wrote: > # Untested > class B4(IntEnum): > F1 = 0 > F2 = 1 > F3 = 2 > T = 3 > def __bool__(self): > return self is B4.T > def __str__(self): > if self is B4.F1: return "Certainly False" > if self is B4.F2: return "Maybe False" > if self is B4.F3: return "Maybe True" > if self is B4.T: return "Certainly True" I keep expecting to hear Bluebottle asking about why we didn't figure this out B4... anyway. class B4(IntEnum): CertainlyFalse = 0 MaybeFalse = 1 MaybeTrue = 2 CertainlyTrue = 3 def __bool__(self): return self is B4.CertainlyTrue Now you don't need a __str__ function. :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python is DOOMED! Again!
Sturla Molden wrote: > On 23/01/15 04:53, Steven D'Aprano wrote: > >> If your manager is so bad, why isn't he insisting that you program in PHP >> or Java or Algol 68 [insert name of some language you dislike] instead of >> Python? Is your bad manager forcing you to write Java-style code in >> Python, or insisting on Hungarian Notation? > > Nobody is forcing me to do anything. > > But without a thriving community, Python has no value to me. > > If we add type hinting, then that community will go away, because other > languages are better options. > > Who will win? Julia? Ruby? They are all waiting in line for Python to > fail. Then Python will be like Smalltalk. How ironic. Julia *already uses* a type system much like the proposed Python one: http://julia.readthedocs.org/en/latest/manual/types/ and Ruby has an experimental one: http://blog.codeclimate.com/blog/2014/05/06/gradual-type-checking-for-ruby/ Javascript has one available too: https://code.facebook.com/posts/1505962329687926/flow-a-new-static-type-checker-for-javascript/ So does Groovy: http://groovy.codehaus.org/Runtime+vs+Compile+time,+Static+vs+Dynamic And Erlang, Clojure, Racket and many more. Python is falling behind, not racing ahead. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Sanity Proposal: Type Hinting Solution
Fetchinson . wrote:
> On 1/23/15, Steven D'Aprano wrote:
[...]
>> Cobra is especially close to Python-like syntax, and supports unit tests
>> as well:
>>
>>
>> def sqroot(i as int) as float
>> require
>>i > 0
>> ensure
>>result > 0
>> tests
>>assert sqroot(25) == 5.0
>> body
>> ...
>>
>> It would be nice to be able to include at least *some* tests right there
>> in the code rather than in a separate file.
>
> I completely agree. A cobra-style type hinting implementation would
> satisfy everyone who doesn't want to make function signatures noisy
> (including me) and would also satisfy those who advocate for the
> actual feature (type hinting) without worrying much about the
> implementation detail. These two groups are overlapping by the way :)
I don't understand this. Cobra's type-hints are right there in the function
signature, just like Python annotations.
# Cobra
def sqroot(i as int) as float
# Python
def sqroot(i:int)->float:
Cobra's use of "as" clashes with Python. In Python, "as" is used for
name-binding:
import module as name
with open('file') as f
except Exception as e
but apart from that minor difference, they're virtually identical.
> In any case, I'm pretty sure it was said before, but I can't really
> find it anywhere, can someone tell me what the rationale is for
> *function signature* type hinting?
The basic principle is that things which are related should be found
together. The further away they are, the worse.
Bad:
- the parameter name and the type are in different files
Better:
- the parameter name and the type are only a few lines apart
Best:
- the parameter name and type are right next to each other
The closer they are, the easier it is to keep them in sync, and the easier
it is to see the relevant information at a glance. Putting them together
also means that you don't have to repeat the argument name:
int n
def spam(n): ...
versus
def spam(n:int): ...
Those reasons are why decorators have the syntax which they do:
@decorator
def spam(n):
do_this()
do_that()
do_something_else()
is better than the old way of using decorators:
def spam(n):
do_this()
do_that()
do_something_else()
spam = decorator(spam)
The decorator is only a single line away from the signature, and you don't
have to repeat the name.
We can see this at work in Pascal. Pascal functions have type declarations
in the signature, and variable declarations between the signature and the
body:
function sqroot(arg: Integer): Real;
var
x: Integer;
y: Real;
z: Something_Else;
begin
do_this(1, 2);
do_that(3, 4);
do_something_else(5, 6);
x := some expression; { what's the type of x again? }
end;
The declarations in the signature work very well and are easy to use, but
the "var" section, not so much. Especially in large functions, the place
where you declare the variable and its type, and the place where you first
use it, can be separated by many lines. This makes maintenance and reading
of the code more difficult.
Newer languages like Java let you declare the variable the first time you
use it:
int x = some expression;
and you don't have to search very far to find out what sort of thing x is,
it is right there.
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
Alternative to multi-line lambdas: Assign-anywhere def statements
In some random and rambling discussion about Python, the notion came
up that multi-line lambda functions are often sought as a means of
populating dictionaries and other such structures. Conceptually, "def
foo(...): ..." is broadly equivalent to "foo = FunctionType(...)"; but
the only type of assignment that can be done is to a simple name.
(It's affected by global statements, so it might be global or local,
but still just a simple name.)
The theory was mooted that it would be nice to be able to assign to anything:
cmd = {} # Command dispatch table
def cmd["foo"](*args):
print("You asked to foo.")
def cmd["bar"](*args):
print("There's no wine in the bar.")
def cmd["asdf"](*args):
print("Asdf! Asdf!")
Obviously this doesn't (currently) work syntactically; but in theory,
a decorator ought to be able to do the same job. The question is, can
it be done generically? For the specific case of the dispatch table,
it would be easy enough to make a function that stuffs its argument
into that one specific dictionary:
cmd = {}
def command(func):
cmd[func.__name__] = func
return func
@command
def foo(*args):
print("You asked to foo.")
but this is hardly generic. There's no convenient way to give an
argument to a decorator that says "please assign this here", short of
using some stupid eval hack... is there?
(Incidentally, for a non-generic dispatch table, a callable dict
subclass could be pretty clean:
class DispatchTable(dict):
"""Self-populating dictionary - use this as a function decorator
to stuff functions into it."""
def __call__(self, func):
self[func.__name__] = func
return func
cmd = DispatchTable()
@cmd
def foo(*args):
print("You asked to foo.")
It's still specific to one exact purpose, though.)
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
