Re: replacing `else` with `then` in `for` and `try`
I haven't read over every message in the thread, so sorry if this has been suggested before, but how about "if not break:" and "if not except:" as synonyms for the current 'else' clause? They're already keywords, and this sequence of keywords has no current meaning. -- https://mail.python.org/mailman/listinfo/python-list
Re: why won't slicing lists raise IndexError?
On Mon, Dec 4, 2017, at 13:54, Jason Maldonis wrote: > Is there any background on why that doesn't raise an IndexError? Knowing > that might help me design my extended list class better. For my specific > use case, it would simplify my code (and prevent `if isinstance(item, > slice)` checks) if the slicing raised an IndexError in the example I > gave. Slicing (of strings, lists, tuples, anyway) never raises an IndexError. If the start is out of range it will return an empty list. I don't know. As for "why", it's just how the operation was designed. Perhaps it was considered that an exception isn't needed because there's no ambiguity (i.e. there's no other reason a slice operation can return a list shorter than the length implied by the slice parameters). Why would this simplify your code? What are you doing that would benefit from an IndexError here? -- https://mail.python.org/mailman/listinfo/python-list
Re: Politeness (was: we want python software)
On Wed, Dec 6, 2017, at 11:18, Steve D'Aprano wrote: > You suggested that if he wasn't familiar with free software, his > request that people send him a copy of Python wouldn't look so odd. > Okay, if Python weren't free software, it would be non-free software, > and you are saying that it wouldn't look so odd for somebody to join a > mailing list and request a bunch of strangers to gift him a copy of > non-free software. The third possibility is that he believes that this list is official in some corporate sense, that if he asks for the software and it is not free he will receive a price quote. -- https://mail.python.org/mailman/listinfo/python-list
Re: why won't slicing lists raise IndexError?
On Mon, Dec 4, 2017, at 13:54, Jason Maldonis wrote: > Is there any background on why that doesn't raise an IndexError? Knowing > that might help me design my extended list class better. For my specific > use case, it would simplify my code (and prevent `if isinstance(item, > slice)` checks) if the slicing raised an IndexError in the example I > gave. Slicing (of strings, lists, tuples, anyway) never raises an IndexError. If the start is out of range it will return an empty list. I don't know. As for "why", it's just how the operation was designed. Perhaps it was considered that an exception isn't needed because there's no ambiguity (i.e. there's no other reason a slice operation can return a list shorter than the length implied by the slice parameters). Why would this simplify your code? What are you doing that would benefit from an IndexError here? -- https://mail.python.org/mailman/listinfo/python-list
Re: What is wrong with this regex for matching emails?
On Sun, Dec 17, 2017, at 10:46, Chris Angelico wrote: > But if you're trying to *validate* an email address - for instance, if > you receive a form submission and want to know if there was an email > address included - then my recommendation is simply DON'T. You can't > get all the edge cases right; it is actually impossible for a regex to > perfectly match every valid email address and no invalid addresses. That's not actually true (the thing that notoriously can't be matched in a regex, RFC822 "address", is basically most of the syntax of the To: header - the part that is *the address* as we speak of it normally is "addr-spec" and is in fact a regular language, though a regex to match it goes on for a few hundred characters. The formal syntax also has some surprising corners that might not reflect real-world implementations: for example, a local-part may not begin or end with a dot or contain two dots in a row (unless quoted - the suggestion someone else made that a local-part may contain an @ sign also requires quoting). It's also unfortunate that a domain-part may not end with the dot, since this would provide a way to specify TLD- only addresses without allowing the error of mistakenly leaving the TLD off of an address. > And that's only counting *syntactically* valid - it doesn't take into > account the fact that "[email protected]" is not going to get > anywhere. So if you're trying to do validation, basically just don't. The recommendation still stands, of course - this script is probably not the place to explore these obscure corners. If the email address is important, you can send a link to it and wait for them to click it to confirm the email. If it's not, don't bother at all. -- https://mail.python.org/mailman/listinfo/python-list
Re: __contains__ classmethod?
On Mon, Dec 18, 2017, at 16:25, Tim Chase wrote: > My understanding was that "in" makes use of an available __contains__ > but something seems to preventing Python from finding that. > > What's going on here? Most __ methods have to be an actual method on the class object, which means you have to use a metaclass. "one" in X() works, but to get "one" in X to work, you need: class M(type): def __contains__(cls, v): return v in cls._ALL class X(object, metaclass=M): ONE = "one" TWO = "two" _ALL = frozenset(v for k,v in locals().items() if k.isupper()) If you want *both* "one" in X and "one" in X() to work, I think you pretty much have to define it in both places. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is wrong with this regex for matching emails?
On Mon, Dec 18, 2017, at 02:01, Chris Angelico wrote: > Hmm, is that true? I was under the impression that the quoting rules > were impossible to match with a regex. Or maybe it's just that they're > impossible to match with a *standard* regex, but the extended > implementations (including Python's, possibly) are able to match them? What's impossible to match with a regex are the comments permitted by RFC822 (which are delimited by balanced parentheses - AIUI perl can do it, python can't.) Which are, according to my argument, not part of the address. > Anyhow, it is FAR from simple; and also, for the purpose of "detect > email addresses in text documents", not desirable. Same as with URL > detection - it's better to have a handful of weird cases that don't > autolink correctly than to mis-detect any address that's at the end of > a sentence, for instance. For that purpose, it's better to ignore the > RFC and just craft a regex that matches *common* email address > formats. Email addresses don't, according to the formal spec, allow a dot at the end of the domain part. I was half-seriously proposing that as an extension (since DNS names *do*). -- https://mail.python.org/mailman/listinfo/python-list
Re: How to exec a string which has an embedded '\n'?
On Sat, Dec 30, 2017, at 23:57, [email protected] wrote: > I have a multiline string, something like '''...\nf.write('\n')\n...''' > when pass to exec(), I got > SyntaxError: EOL while scanning string literal > > How to get rid of it? Use \\n for this case, since you want the \n to be interpreted by the exec parser rather than the newline being part of the string. -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode direction control characters
On Tue, Jan 2, 2018, at 10:36, Robin Becker wrote: > >> u'\u200e28\u200e/\u200e09\u200e/\u200e1962' > > I guess I'm really wondering whether the BIDI control characters have any > semantic meaning. Most numbers seem to be LTR. > > If I saw u'\u200f12' it seems to imply that the characters should be > displayed > '21', but I don't know whether the number is 12 or 21. No, 200F acts as a single R-L character (like an invisible letter), not an override for adjacent characters (as 202E would). LRM/RLM basically act like an invisible letter of the relevant directionality. European numerals have "weak" LTR directionality (to allow them to be used as part of e.g. a list of numbers in a sentence written in an RTL language), and don't affect some punctuation marks the same way as letters. I believe the purpose here is to ensure that it displays as 28/09/1962 instead of 1962/09/28 when the surrounding context is right-to-left. For the slash in particular, this was apparently a bug that was fixed in some recent version of unicode (this is mentioned briefly in UTR9, look for "solidus"), so earlier implementations or non-unicode implementations may not have supported it correctly. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: has sourceforge exposed the dirty little secret ?
On Sun, Jan 7, 2018, at 17:27, Gene Heskett wrote: > > > > đ đ» > > > But here its broken and I am looking at two pairs of vertical boxes > because it is not properly mime'd. If you use chars or gliphs from a > non-default charset, it needs to demarcated with a mime-boundary marker > followed by the new type definition. Your email/news agent did not do > that. UTF-8 is the default character set, and anyway his message does have a content-type of 'text/plain; charset="utf-8"; Format="flowed"'. Your environment not having font support and/or support for non-BMP characters is not a deficiency in the message. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: has sourceforge exposed the dirty little secret ?
On Sun, Jan 7, 2018, at 17:47, Richard Damon wrote: > But it also says: > > Content-Transfer-Encoding: 7bit > > Which is incorrect, as the message is actually 8bit encoded (since the > Emoji aren't in the first 127 characters, so their UTF-8 encoding isn't > 7-bit. Some software might have messed up the message in transit due to > that error. Well, the fact that the emoji survived the round-trip and showed up properly in his reply (and yours) led me to rule out the possibility that anything like that had happened. Plus, if that had happened, the result wouldn't be boxes, but a series of ASCII characters (some of which are control characters, and some of which are printable). -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: has sourceforge exposed the dirty little secret ?
On Sun, Jan 7, 2018, at 18:50, Gene Heskett wrote: > That, now that you mention it, could also effect this as I see it, my > default kmail message body font is hack 14 in deference to the age of my > eyes. > > My system default font is I believe utf-8. That is not a kmail settable > option. But if I uncheck the "use custom fonts", it is still two pair of > character outlines. So to what family of fonts do these characters > belong? If it supports truetype fonts (and picking fonts based on what fonts have a character available, rather than one font for the whole message), you might try the https://www.google.com/get/noto/ family - it has a black-and-white Emoji font available (color fonts require special application support, but the black and white one is just plain truetype) - of course, that won't help if it's limited to 16 bits (the fact that they are *pairs* of boxes unfortunately suggests this, but maybe it'll work properly if a font is available). -- https://mail.python.org/mailman/listinfo/python-list
Re: Can utf-8 encoded character contain a byte of TAB?
On Mon, Jan 15, 2018, at 09:35, Peter Otten wrote: > Peng Yu wrote: > > > Can utf-8 encoded character contain a byte of TAB? > > Yes; ascii is a subset of utf8. > > If you want to allow fields containing TABs in a file where TAB is also the > field separator you need a convention to escape the TABs occuring in the > values. Nothing I see in your post can cope with that, but the csv module > can, by quoting field containing the delimiter: Just to be clear, TAB *only* appears in utf-8 as the encoding for the actual TAB character, not as a part of any other character's encoding. The only bytes that can appear in the utf-8 encoding of non-ascii characters are starting with 0xC2 through 0xF4, followed by one or more of 0x80 through 0xBF. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help: 64bit python call c and got OSError: exception: access violation writing 0xFFFFFFFF99222A60
On Mon, Jan 22, 2018, at 16:00, Jason Qian via Python-list wrote:
> Hello!
>
> I am using ctypes on Windows to interface with a dll and it works fine
> on Linux and windows 32-bit python. But, when using 64-bit python, we got
> error "exception: access violation writing 0x99222A60".
You are treating the obj type (myPythonAPI *) as c_int, which is only 32 bits.
You should be using a pointer type instead (ideally you should be using void *
and c_void_p, so Python doesn't need the class definition.) Don't forget to set
lib.loadInstance.restype as well.
> __declspec(dllexport) myPythonAPI* loadInstance(){ return new
> myPythonAPI(); }
> __declspec(dllexport) int createService(myPythonAPI* obj, const char*
> serviceName) { eturn obj->createService(serviceName);
> lib = cdll.LoadLibrary('xxx.dll')
>
> lib.createService.argtypes=[c_int,ctypes.c_char_p]
> lib.createService.restype=ctypes.c_int
>
> class myDriver(object):
> def init(self):
> self.obj = lib.loadInstance()
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why does datetime.timedelta only have the attributes 'days' and 'seconds'?
On Tue, Apr 19, 2022, at 07:11, Loris Bennett wrote:
> I now realise that timedelta is not really what I need. I am interested
> solely in pure periods, i.e. numbers of seconds, that I can convert back
> and forth from a format such as
A timedelta *is* a pure period. A timedelta of one day is 86400 seconds.
The thing you *think* timedelta does [making a day act as 23 or 25 hours across
daylight saving boundaries etc], that you *don't* want it to do, is something
it *does not actually do*. I don't know how this can be made more clear to you.
timedelta is what you need. if you think it's not, it's because you're using
datetime incorrectly.
The real problem is that naive datetime objects [without using either a fixed
timezone offset like the built-in utc, or a library like pytz] are not fit for
any purpose.
If you use pytz correctly [which is unfortunately awkward due to leaky
abstractions and mismatches between the datetime model works and how most
people expect datetimes with timezones to work], you will indeed get 24 hours
from timedelta(days=1)
>>> et = pytz.timezone('America/New_York')
>>> et.normalize(et.localize(datetime.datetime(2022,3,12,12,0,0)) +
>>> datetime.timedelta(days=1))
datetime.datetime(2022, 3, 13, 13, 0, tzinfo=)
you can see here that 2022-03-12T12:00-0500 + timedelta(days=1) correctly
becomes 2022-03-13T13:00-0400, 24 hours later.
As far as I know, Python doesn't even have a way to represent "1 day" [or 1
month, 1 year] as a context-dependent-length interval (the thing you think
timedelta does), at least not within the standard library and the datetime
model.
> 11-22::44:55
>
> (These are the lengths of time a job has run on an HPC system - leap
> seconds and time zones are of no relevance).
>
> It is obviously fairly easy to rustle up something to do this, but I am
> surprised that this is not baked into Python (such a class also seems to
> be missing from R). I would have thought that periods crop up all over
> the place and therefore formatting as strings and parsing of string
> would be supported natively by most modern languages. Apparently not.
>
> Cheers,
>
> Loris
>
> --
> This signature is currently under construction.
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: Pre-Pre-PEP: The datetime.timedeltacal class
On Sat, Apr 16, 2022, at 13:35, Peter J. Holzer wrote: > When adding a timedeltacal object to a datetime, the fields are added > from most to least significant: First a new date is computed by > advancing the number of months specified [TODO: Research how other > systems handle overflow (e.g. 2022-01-31 + 1 month: 2022-02-31 doesn't > exist)], then advance the number of days. Finally add the number of > seconds and microseconds, taking into accout daylight savings time > switches if the datetime is time zone aware. > > Subtracting a timedeltacal object from a datetime is the same, just in > the opposite direction. > > Note that t + d - d is in general not equal to t. I'm not sure there's a guarantee that t + n day + m second may not be equal to t + m second + n day, either. This is possibly also something that we can look at what existing implementations do, though I'm concerned that the choice of "fold" rather than "isdst" may come back to bite us here [C actually uses a three-state isdst input for mktime which performs these operations] Also, what about hours? "12 calendar hours" may be 13 or 11 hours depending on if a DST transition is included in the given time. -- https://mail.python.org/mailman/listinfo/python-list
Re: Exploring terminfo
On Fri, Jan 15, 2021, at 13:36, Alan Gauld via Python-list wrote: > That could make a big difference, the putp() function specifically > states that it writes to stdout. I think there is a reasonable argument that this is a deficiency of the curses module. I think that the curses module should A) expose a version of tputs that accepts a python callback to process each output byte B) expose a version of putp that uses python's stdout[.buffer].write rather than C's putchar. -- https://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 cannot detect the version of compiled sqlite version at some point in runtime.
On Wed, Jan 20, 2021, at 14:54, panfei wrote: > 3. Compile Python 3.9.1 > C_INCLUDE_PATH=/home/felix/.local/sqlite/sqlite-3.34.0/include/ > CPLUS_INCLUDE_PATH=/home/felix/.local/sqlite/sqlite-3.34.0/include/ > LD_RUN_PATH=/home/felix/.local/sqlite/default/lib ./configure > --prefix=/home/felix/.local/python/python-3.9.1 --enable-optimizations > make && make install How *exactly* did you compile python? i.e. what specific commands, to make it pick up those include paths? Because from the symptoms you are reporting, it sounds like it was not compiled against the correct version of sqlite. -- https://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 cannot detect the version of compiled sqlite version at some point in runtime.
On Wed, Jan 20, 2021, at 16:45, Random832 wrote: > On Wed, Jan 20, 2021, at 14:54, panfei wrote: > > 3. Compile Python 3.9.1 > > C_INCLUDE_PATH=/home/felix/.local/sqlite/sqlite-3.34.0/include/ > > CPLUS_INCLUDE_PATH=/home/felix/.local/sqlite/sqlite-3.34.0/include/ > > LD_RUN_PATH=/home/felix/.local/sqlite/default/lib ./configure > > --prefix=/home/felix/.local/python/python-3.9.1 --enable-optimizations > > make && make install > > How *exactly* did you compile python? i.e. what specific commands, to > make it pick up those include paths? Because from the symptoms you are > reporting, it sounds like it was not compiled against the correct > version of sqlite. Oh, sorry, I missed "./configure" on that line. So, it looks like you had the environment variables set when you ran configure, but not make. I don't think this is a common way to set include paths, by the way. The usual way is with pkg-config, but I'm not sure how to add your .local sqlite directory to it. Does your sqlite installation include a file called "sqlite3.pc"? If so, try adding the directory containing it to PKG_CONFIG_PATH when running configure. If not... well, export the environment variables or add them when running make and hope for the best -- https://mail.python.org/mailman/listinfo/python-list
Re: Response for PING in ircbot.
On Sat, Jan 30, 2021, at 11:50, Bischoop wrote:
>
> Got problem with responding for Ping, tried so many ways to response
> and always end up with time out or other error. This time:
1. It looks like you're forgetting to send \n\r
2. i'm not sure if the server ping is guaranteed to have : character
3. if it does have : character you need to send everything after it even if it
includes spaces
4. what happens if the data in recv includes more than one line of data, or
partial line at the end? this isn't a proper way to handle irc protocol in
general, let alone the ping command
> ERROR :(Ping timeout: 264 seconds)
> Traceback (most recent call last):
> s.send(bytes('PONG ' + data.split()[1], 'UTF-8'))
> BrokenPipeError: [Errno 32] Broken pipe
>
> while True:
> time.sleep(2)
> data=s.recv(2040).decode('utf8')
> data = data.strip("\n\r")
> print(data)
> if data.find ("PING :"):
> s.send(bytes('PONG ' + data.split()[1], 'UTF-8'))
--
https://mail.python.org/mailman/listinfo/python-list
Re: use set notation for repr of dict_keys?
On Sat, Feb 20, 2021, at 15:00, dn via Python-list wrote: > So, the output is not a set (as you say) but nor (as > apparently-indicated by the square-brackets) is it actually a list! To be clear, it is an instance of collections.abc.Set, and supports most binary operators that sets support. I was surprised, though, to find that you can't remove items directly from the key set, or in general update it in place with &= or -= (these operators work, but give a new set object). AIUI the keys, values, and items collections have always had the ordering guarantee that iterating over them while not modifying the underlying dictionary will give the same order each time [with respect to each other, and possibly also with respect to iterating over the original dictionary to obtain the keys] -- https://mail.python.org/mailman/listinfo/python-list
Re: use set notation for repr of dict_keys?
On Wed, Feb 24, 2021, at 02:59, Marco Sulla wrote: > On Wed, 24 Feb 2021 at 06:29, Random832 wrote: > > I was surprised, though, to find that you can't remove items directly from > > the key set, or in general update it in place with &= or -= (these > > operators work, but give a new set object). > > This is because they are a view. Changing the key object means you > will change the underlying dict. Probably not that you want or expect. Why wouldn't it be what I want or expect? Java allows exactly this [and it's the only way provided to, for example, remove all keys matching a predicate in a single pass... an operation that Python sets don't support either] > You can just "cast" them into a "real" set object. > > There was a discussion to implement the whole Set interface for dicts. > Currently, only `|` is supported. -- https://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to minimize the need of run time checks?
On Tue, Aug 9, 2016, at 16:51, Juan Pablo Romero Méndez wrote: > So as the writer of the function you expect the user to read the function > body to determine what is safe to pass or not? How about expecting them to read the docstring? -- https://mail.python.org/mailman/listinfo/python-list
Re: cmd prompt does not recognizes python command on Windows 7
On Wed, Aug 10, 2016, at 06:34, eryk sun wrote: > On Wed, Aug 10, 2016 at 4:46 AM, wrote: > > > > i have installed python 3.5 , but the python command is not recognized > > > > C:\Users\sharmaaj>python > > 'python' is not recognized as an internal or external command, > > operable program or batch file. > > > > what should i do to run python commands. > > Modify your setup. Open "Programs and Features" from the control > panel. Right-click the entry for Python 3.5 (not "Python Launcher") > and select Uninstall/Change. In the dialog, click on "Modify". Click > "Next" and select "Add Python to environment variables". Click > "Install". When it's done, open a new command prompt and enter > "python". Or he could just use "py", which is the python launcher you just mentioned, and works fine. If he has other versions of python installed he may need "py -3". -- https://mail.python.org/mailman/listinfo/python-list
Re: Python slang
On Wed, Aug 10, 2016, at 07:59, Dennis Lee Bieber wrote: > The use of = also has a long history... FORTRAN (where the comparison > was .EQ.), BASIC (granted, K&K required assignment to start with the > keyword LET, so the use of = was mainly a delimiter between target and > expression being assigned). Visual Basic actually uses = for both assignment and comparison *without* the Let keyword, it gets by on the fact that assignment is not an expression. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python slang
On Wed, Aug 10, 2016, at 19:57, Michael Torrie wrote: > But the grammar must still be a bit complex as sometimes the LHS of the > = is an expression, as well as the RHS. The only place that an *arbitrary* expression (including e.g. = as equality) can appear in the LHS is inside parentheses, otherwise you're limited to dot and call/index (which are both parentheses, which isn't a problem for the parser since no object can do both and it's the same kind of expression) just like in Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: I am new to python. I have a few questions coming from an armature!
On Wed, Aug 17, 2016, at 14:27, Terry Reedy wrote: > That particular syntax was not really considered. At least 10 versions > using 'if', 'then', 'else', and other tokens were. > > They all had the problem of requiring a new keyword such as 'then' or > some other innovation. Why not just if(cond, trueval, falseval), a la Visual Basic? It's too late to change now, but I'm curious as to whether it was considered or not. -- https://mail.python.org/mailman/listinfo/python-list
Re: saving octet-stream png file
On Fri, Aug 19, 2016, at 16:51, Lawrence DâOliveiro wrote: > On Saturday, August 20, 2016 at 6:03:53 AM UTC+12, Terry Reedy wrote: > > > > An 'octet' is a byte of 8 bits. > > Is there any other size of byte? Not very often anymore. Used to be some systems had 9-bit bytes, and of course a lot of communication protocols only supported 7-bit data bytes. "Byte" is a technical term in the C and C++ standards meaning the smallest addressable unit even if that is a larger word. -- https://mail.python.org/mailman/listinfo/python-list
Re: saving octet-stream png file
On Fri, Aug 19, 2016, at 21:09, Steve D'Aprano wrote: > Depends what you mean by "byte", but the short answer is "Yes". > > In the C/C++ standard, bytes must be at least eight bytes. As the below > FAQ > explains, that means that on machines like the PDP-10 a C++ compiler will > define bytes to be 32 bits. I assume you mean 36, but I think this is mixing up two separate parts of the FAQ along with some theory discussion. AFAIK all historical C implementations for the PDP-10 and other 18- or 36-bit word systems have used the "9-bit bytes, and an extra offset member in char and void pointers if necessary" solution rather than the "word-sized byte" solution. In principle, I think a close reading of the standard would allow for an implementation can have 'skipped bits' as discussed there so long as there is no significance to the 'missing' bits in *any* type - so you could legally have 8-bit bytes on a PDP-10 so long as you also had 16-bit shorts, 32-bit long/pointer/float, and in general *never ever* broke the illusion that only the bits addressable via char pointers exist. Modern implementations aren't expected to expose ECC bits, after all. Such an implementation would probably be best done by ignoring the high bits of each word, which are easily masked off and often have no real use anyway in pointers (How many of these systems supported 2^36 words = 288 modern gigabytes of memory?), rather than by ignoring a single bit "between" each byte. AIUI many PDP-10 applications only used 18 bits for word pointers. -- https://mail.python.org/mailman/listinfo/python-list
Re: saving octet-stream png file
On Sat, Aug 20, 2016, at 03:50, Marko Rauhamaa wrote: > 2'scomplement arithmetics is quite often taken advantage of in C > programming. Unfortunately, with the castration of signed integers with > the most recent C standards, 2's-complement has been dangerously broken. No part of any version of the C standard has ever allowed signed integer overflow to work as defined behavior the way a generation of programmers assumed it did. What changed was advances in compiler optimization technology, not a standards change. -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP suggestion: Uniform way to indicate Python language version
On Mon, Aug 22, 2016, at 01:35, Steven D'Aprano wrote: > Could somebody (the OP?) please explain what is the purpose of this > proposal, what it does, how it works, and when would people use it? I think what he wants is a way for a module which uses features (syntactic or otherwise, but I suppose especially syntactic features since this can't as easily be done with a runtime check using existing mechanisms) from a particular python version and which makes no provision to run under earlier versions to fail with a message like "This script requires Python 3.4 or later" rather than a mysterious syntax error or worse a runtime error after the program has been running for some time. -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP suggestion: Uniform way to indicate Python language version
On Mon, Aug 22, 2016, at 02:03, Stefan Behnel wrote: > Steven D'Aprano schrieb am 22.08.2016 um 07:35: > > if sys.version < '3': > > import mymodule2 as mymodule > > else: > > import mymodule3 as mymodule > > This condition is going to fail when Python 30.0 comes out. Er, won't it rather stop behaving as desired when Python 10.0 comes out, and resume when 30.0 does? -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP suggestion: Uniform way to indicate Python language version
On Mon, Aug 22, 2016, at 08:44, Chris Angelico wrote: > However, I don't think it's particularly necessary. Explicit version > number checks should be very rare, and shouldn't be encouraged. > Instead, encourage feature checks, as Steve gave some examples of. The problem is when you want to write a large body of code that just *uses* lots of features (including syntactic features), *without* checking for them. Steve's examples were of how to support earlier versions, not how *not* to. At some point you want to just write Python 3 code and say to hell with Python 2, or the same for any particular version of Python 3. -- https://mail.python.org/mailman/listinfo/python-list
Re: Does This Scare You?
On Mon, Aug 22, 2016, at 08:39, Chris Angelico wrote: > Nope. On Windows, you would try/except it. No, you can't, because the failure mode often isn't "file refuses to open" but "data is written to a serial port". There are myriad other ways > something could fail, and the only correct action is to attempt it. > Most of the reserved names will simply give an error; the only way > you'd actually get incorrect behaviour is if the file name, including > extension, is exactly a device name. I think the reason you believe this can be traced back to the "C:\con\con" trick, which crashed the system by trying to use the name as a directory. > (Caveat: My knowledge of Windows > is rusty and my testing just now was cursory. I could be wrong.) Eryk Sun already posted an example using "NUL .txt". -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP suggestion: Uniform way to indicate Python language version
On Mon, Aug 22, 2016, at 09:21, Steve D'Aprano wrote: > Rather, you just use the features you rely on, document the minimum > supported version, and if somebody is silly enough to try running your > code > under Python 1.4, they'll get a SyntaxError or an exception when you try > to > do something that is not supported. Receiving a SyntaxError or whatever other exception, which provides no suggestion about how to actually fix the issue (install a later version of python / run with "python3" instead of "python"), is a bad user experience. It will continue to be a bad user experience when people are using features that only work on python 5.0 and later and other people are trying to run their scripts under python 4.0, so it not having existed all along is not a sufficient justification to not consider adding it,. -- https://mail.python.org/mailman/listinfo/python-list
Re: The dangerous, exquisite art of safely handing user-uploaded files: Tom Eastman (was: Does This Scare You?)
On Mon, Aug 22, 2016, at 10:21, Ben Finney wrote:
> So yes, filenames from arbitrary sources should be *completely*
> untrusted, and never used to access any file on the system. Throw the
> entire filename away and make a filename locally, without using any part
> of the original name.
To be fair, this particular case is unique in presenting a possibility
to cause problems even for a filename that consists only of whitelisted
characters (for a reasonable-sounding whitelist such as "ASCII letters
and numbers and underscore only; all other characters to be scrubbed and
replaced with {underscore, hex escape, nothing}"). I don't think there's
any other precedent.
--
https://mail.python.org/mailman/listinfo/python-list
Re: The dangerous, exquisite art of safely handing user-uploaded files: Tom Eastman (was: Does This Scare You?)
On Mon, Aug 22, 2016, at 11:40, Chris Angelico wrote: > Windows has some other issues, including that arbitrary files can > become executable very easily (eg if %PATHEXT% includes its file > extension), and since the current directory is always at the beginning > of your path, this can easily turn into a remote code execution > exploit. I didn't include dot in my example whitelist, and there's no mechanism for an attacker to add random extensions to your PATHEXT. > And any GUI that automatically calculates thumbnails from > image files (this includes Windows, Mac OS, and more than one Linux > window manager) could potentially be attacked via a malformed file, > simply by having it appear on the file system. This has nothing to do with the filename, unless you additionally assume that this will only happen if the file is called .jpg -- https://mail.python.org/mailman/listinfo/python-list
Re: Dynamically import specific names from a module vs importing full module
On Mon, Aug 22, 2016, at 16:21, Malcolm Greene wrote: > Python 3.5: Is there a way to dynamically import specific names from a > module vs importing the full module? > > By dynamic I mean via some form of importlib machinery, eg. I'm looking > for the dynamic "from import " equivalent of "import > "'s importlib.import_module. You do know that "from import " still loads the whole module into sys.modules, right? And you're free to assign the result from importlib.import_module to a local variable and delete it once you've gotten the names you want out of it. -- https://mail.python.org/mailman/listinfo/python-list
Re: degrees and radians.
On Wed, Aug 24, 2016, at 00:26, Gary Herron wrote: > Perhaps I'm not understanding what you mean by "clunky", but this seems > pretty clean and simple to me. The original post is from 2002, I don't know why it got a reply just now. -- https://mail.python.org/mailman/listinfo/python-list
Re: The order of iterable de-referencing in assignment?
On Wed, Aug 24, 2016, at 07:17, Chris Angelico wrote: > Objects/listobject.c:795 > > /* Special cases: >1) lists and tuples which can use PySequence_Fast ops >2) extending self to self requires making a copy first > */ And, of course, it is a special case - a.extend(iter(a)) is enough to break it. Frankly I'm not sure why bother to implement it when anyone who legitimately wants to do it can simply do a *= 2. -- https://mail.python.org/mailman/listinfo/python-list
Re: integer's methods
On Sat, Aug 27, 2016, at 13:24, Grant Edwards wrote: > Becuase the parser thinks you've entered a floating point number with > a fractional part of "bit_length". 123.+456 doesn't think that the fractional part is "+456". (Of course, the real reason is "because it would be even more annoying to get random errors only with attributes that start with "e" or "j") -- https://mail.python.org/mailman/listinfo/python-list
Magic UTF-8/Windows-1252 encodings
Directing this to python-list because it's really not on the topic of the idea being discussed. On Mon, Aug 29, 2016, at 05:37, Chris Angelico wrote: > Suppose I come to python-ideas and say "Hey, the MUD community would > really benefit from a magic decoder that would use UTF-8 where > possible, ISO-8859-1 as fall-back, and Windows-1252 for characters not > in 8859-1". Apart from responding that 8859-1 is a complete subset of > 1252, ISO-8859-1, with a dash in between "ISO" and "8859" is not a complete subset of 1252. In fact, ISO-8859-1-with-a-dash incorporates ISO 6429 for 0x80-0x9F, and thereby has no bytes that do not map to characters. The magic encoding that people often ask for or use is to use UTF-8 first, Windows-1252 as a fallback, and ISO 6429 as the final fallback (and may or may not involve a "side trip" through Windows-1252 for UTF-8 encodings purportedly of code points between U+0080 and U+009F). Incidentally, many Windows encodings, including 1252, as they are actually used do use ISO 6429 for bytes that do not map to characters, even when best fit mappings are not accepted. It is unclear why they published tables that define these bytes as undefined, which have been picked up by independent implementations of these encodings such as the ones in Python. The only reason I can think of is to reserve the ability to add new mappings later, as they did for 0x80 to U+20AC. > there's not really a lot that you could discuss about that > proposal, unless I were to show you some of my code. I can tell you > about the number of MUDs that I play, the number of MUD clients that > I've written, and some stats from my MUD server, and say "The MUD > community needs this support", but it's of little value compared to > actual code. > > (For the record, a two-step decode of "UTF-8, fall back on 1252" is > exactly what I do... in half a dozen lines of code. So this does NOT > need to be implemented.) And what level is the fallback done at? Per line? Per character? Per read result? Does encountering an invalid-for-UTF-8 byte put it permanently in Windows-1252 mode? Does it "retroactively" affect earlier bytes? Can it be used as a stream encoding, or does it require you to use bytes-based I/O and a separate .decode step? I assume a MUD server isn't blocking on each client socket waiting for a newline character, so how does such a decoding step mesh with whatever such a server does to handle I/O asynchronously? Are there any frameworks that you could be using that you can't if it's not an encoding? What happens if it's being used as an incremental decoder, encounters a valid UTF-8 lead byte on a buffer boundary, and then must "reject" (i.e. decode as the fallback encoding) it afterwards because an invalid trail byte follows it in the next buffer? What happens if a buffer consists only of a valid partial UTF-8 character? I can probably implement the fallback as an error handler in half a dozen lines, but it's not obvious and I suspect it's not what a lot of people do. It would probably take a bit more than half a dozen lines to implement it as an encoding. -- https://mail.python.org/mailman/listinfo/python-list
Re: Magic UTF-8/Windows-1252 encodings
On Mon, Aug 29, 2016, at 11:14, Chris Angelico wrote: > Please don't. :) This is something that belongs in the application; > it's somewhat hacky, and I don't see any benefit to it going into the > language. For one thing, I could well imagine making the fallback > encoding configurable (it isn't currently, but it could easily be), > and that doesn't really fit into the Python notion of error handler. Well, yeah, if anything implementing it as an error handler is a hack, I just meant it's just the least hacky way I can think that fits in the size "half a dozen lines". > For another, this is a fairly rare concept - I don't see dozens of > programs out there using the exact same strange logic, and even if > there were, there'd be small differences That is actually an argument in favor of putting it in the stdlib, assuming few of those small differences are truly considered and intentional. The main thrust of my post was that this is one of the things that's harder than it sounds to get right due to edge cases, just like the clip/clamp function being discussed last month. > (eg whether or not the > fallback is applied line-by-line). This was intended as an example of > something that does NOT belong in the core language, and while I > appreciate the offer of help, it's not something I'd support polluting > the language with :) > > (Plus, my server's not written in Python. Nor is the client that this > started in, although I have considered writing a version of it in > Python, which would in theory benefit from this.) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python slang
On Wed, Aug 10, 2016, at 12:19, Random832 wrote: > On Wed, Aug 10, 2016, at 07:59, Dennis Lee Bieber wrote: > > The use of = also has a long history... FORTRAN (where the > > comparison was .EQ.), BASIC (granted, K&K required assignment to > > start with the keyword LET, so the use of = was mainly a > > delimiter between target and expression being assigned). > > Visual Basic actually uses = for both assignment and comparison > *without* the Let keyword, it gets by on the fact that assignment is > not an expression. I just discovered something interesting. It turns out, Python 0.9.1 did the same thing (i.e. = for both assignment and comparison), with the ambiguity resolved by not allowing comparison operators generally in some expression contexts. >>> a, b = 1, 2 a < b Parsing error: file , line 1: a < b ^ Unhandled exception: run-time error: syntax error >>> # wait, what? I was doing this, originally, to test that comparisons >>> # still worked after a change to cmp_outcome to silence a compiler >>> # warning. I thought I'd somehow broken the parser. >>> (a < b) 1 >>> (a = b) 0 >>> if a = b: 1 # It doesn't always need parentheses ... else: 0 ... 0 >>> a, b (1, 2) >>> (a == b) # Turns out the modern operator doesn't even exist Parsing error: file , line 1: (a == b) ^ Unhandled exception: run-time error: syntax error >>> (a != b) # And now something for Barry Warsaw Parsing error: file , line 1: (a != b) ^ Unhandled exception: run-time error: syntax error >>> (a <> b) 1 It's gone in Python 1.0 - all of the modern behavior we're familiar with, except of course the boolean type, is fully present, with the continued existence [for a while] of the <> operator the only trace of days gone by. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour with numbers in exponential notation
On Fri, Sep 2, 2016, at 11:51, Marco Sulla wrote: > >>> 10**26 - 1 > 99 > >>> 1e26 - 1 > 1e+26 > > > Why? Exponential notation creates floating point numbers, which have a limited amount of precision in binary. Specifically (on my system which, as most modern computers do, use IEEE double precision numbers for the python float type), 0x52b7d2dcc80cd4 is the value of 1e26, whereas. 0x52b7d2dcc80cd2e400 is the valoe of 10**26. Trying to add 1 gets it rounded off again, and the value is simply printed as 1e+26 by default because this is the shortest representation that gives the same number, even if "14764729344.0" would be more accurate. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour with numbers in exponential notation
On Fri, Sep 2, 2016, at 13:02, Marco Sulla wrote:
> On Fri, Sep 2, 2016 at 6:17 PM, Random832 wrote:
> > Trying to add 1 gets it rounded off again, and the value is simply
> > printed as 1e+26 by default because this is the shortest representation
> > that gives the same number, even if "14764729344.0"
> > would be more accurate.
>
> It seems it's not simply a representation. It seems the numbers are just
> equal:
Yes. The number 1e+16 is represented as a floating point number
equal to 14764729344. Then when you add 1 to it, the
1 gets rounded off and you get a floating point number that is still
equal to 14764729344:
>>> a = float(10**16)
>>> int(a)
14764729344
>>> b = a + 1
>>> int(b)
14764729344
You switched examples. 10**22 is the largest power of 10 that can be
represented exactly, but 10**15+1 is te largest "power of 10 plus
one" that can be represented exactly.
Float can only represent numbers whose binary representation
contains 53 bits or less from the first to the last "1".
>>> '{:b}'.format(10**15)
'1110001101011010100100110001101000'
# 35 bits before the run of zeros
>>> '{:b}'.format(10**16)
'1000111110001001101101'
# 38 bits, works fine in float
>>> '{:b}'.format(10**15+1)
'1110001101011010100100110001101001'
# 50 bits, barely fits in a float
>>> '{:b}'.format(10**16+1)
'10001111100010011011010001'
# 54 bits, too many.
Anything else gets rounded off. It's the same as if you tried to add
a tiny number to 1.
>>> 1+1e-15 == 1
False
>>> 1+1e-16 == 1
True
> This is really weird. I tried to do it just in C:
You should be using double instead of long double; double is the
C equivalent of the Python float type.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour with numbers in exponential notation
On Fri, Sep 2, 2016, at 15:12, Christian Gollwitzer wrote: > Tradition? All languages I know of treat a number with an exponent as > floating point. Scheme does allow you to give integers (and rationals) in decimal and/or exponential notation with the "#e" prefix. -- https://mail.python.org/mailman/listinfo/python-list
Re: What you can do about legalese nonsense on email (was: How to split value where is comma ?)
On Thu, Sep 8, 2016, at 18:13, Grant Edwards wrote: > After all, that boilerplate just makes the corporation look stupid and > incompetent. Any email that leaves the corporate network must be > assumed to be visible to world+dog. Anybody who thinks differently is > deluded and should not be allowed access to information that is > "confidential and subject to privledge". If every lawyer in the world benefits from the interpretation that this sort of notice is legally effective (since tomorrow it may be they who accidentaly send privileged information), who will argue in court that it's not? The reality is more complex, and it appears that it may only apply if the accidental recipient is a lawyer. I really can't say for sure, since _I'm_ not a lawyer, but posted without further comment: http://apps.americanbar.org/litigation/committees/technology/articles/winter2013-0213-do-email-disclaimers-really-work.html -- https://mail.python.org/mailman/listinfo/python-list
Re: How to extend a tuple of tuples?
On Mon, Sep 12, 2016, at 17:29, Chris Angelico wrote:
> old_id = id(a)
> a += something
> if id(a) == old_id:
> print("We may have an optimization, folks!")
>
> But that can have false positives. If two objects do not concurrently
> exist, they're allowed to have the same ID number.
But the two objects do concurrently exist, from the time __iadd__ is
evaluated until the time when a is assigned, in the formal semantics of
this code. Allowing them to not concurrently exist is, effectively,
precisely the optimization being discussed.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Oh gods can we get any more off-topic *wink* [was Re: [Python-ideas] Inconsistencies]
On Wed, Sep 14, 2016, at 23:12, Steve D'Aprano wrote: > Yes it does. Even an infinitely large flat plane has a horizon almost > identical to the actual horizon. Your link actually doesn't support the latter claim, it goes into some detail on why it wouldn't if it were infinitely large due to gravitational effects on light. Of course, the fact that the horizon is a short [in comparison to the size of the known world] distance away *is* evidence for a round Earth. It might "look the same", but it would contain features all the way up to potentially the edge (anything not obstructed by subjectively taller objects in front of it), it certainly wouldn't make sense not to see the opposing landmass across an ocean. > http://www.askamathematician.com/2012/08/q-if-earth-was-flat-would-there-be-the-horizon-if-so-what-would-it-look-like-if-the-earth-was-flat-and-had-infinite-area-would-that-change-the-answer/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Oh gods can we get any more off-topic *wink* [was Re: [Python-ideas] Inconsistencies]
On Thu, Sep 15, 2016, at 15:06, Steve D'Aprano wrote: > No, the horizon would still be horizontal. It merely wouldn't *look* > horizontal, an optical illusion. I guess that depends on your definition of what a horizon is - and what a straight line is, if not the path followed by a beam of light. -- https://mail.python.org/mailman/listinfo/python-list
Re: Oh gods can we get any more off-topic *wink* [was Re: [Python-ideas] Inconsistencies]
On Thu, Sep 15, 2016, at 15:31, Steve D'Aprano wrote: > Light follows geodesics, not straight lines. What is a straight line on a curved space if not a geodesic? That was actually what I was getting at. -- https://mail.python.org/mailman/listinfo/python-list
Re: What does this zip() code mean?
On Tue, Sep 20, 2016, at 09:19, [email protected] wrote: > >>> x = [1, 2, 3] > >>> y = [4, 5, 6] > >>> zipped = zip(x, y) > >>> list(zipped) > [(1, 4), (2, 5), (3, 6)] > >>> x2, y2 = zip(*zip(x, y)) > >>> x == list(x2) and y == list(y2) > True > > My problem is >>> x2, y2 = zip(*zip(x, y)). > zip return an iterator but x2 and y2 are different? > I really need detail explanation about this line. Well, as you've seen, zip(x, y) is (1, 4), (2, 5), (3, 6) This means that zip(*...) is zip((1, 4), (2, 5), (3, 6)). It takes the first element of each argument (1, 2, and 3), and then the next element of each argument (4, 5, and 6). -- https://mail.python.org/mailman/listinfo/python-list
Re: Linear Time Tree Traversal Generator
On Tue, Sep 20, 2016, at 22:34, Steve D'Aprano wrote: > I'm afraid I don't understand this. This is a standard binary tree > inorder traversal. Each node is visited once, and there are N nodes, > so I make that out to be O(N) not O(N log N). I'm afraid I can't parse > your final clause: > > "since values from the leaves of the tree have to be yielded > multiple times to the top of the tree" > > Each leaf is yielded once, and I don't understand what you mean by > yielding to the top of the tree. His point is that in order for the top-level iterator to return a given node there's a yield call in the top level's iterator , that calls the next level's iterator's yield, that calls the next one, so on, in a call stack log(n) levels deep. -- https://mail.python.org/mailman/listinfo/python-list
Re: Linear Time Tree Traversal Generator
On Tue, Sep 20, 2016, at 23:34, Steve D'Aprano wrote:
> One of us is badly missing something.
The problem is the number of times next is called. Here, it'll be more
clear if we wrap the iterator in the original example to print each time
next is called.
class WrappedIterator():
def __init__(self, orig, reference):
self.orig = orig
self.ref = reference
def __iter__(self):
return self
def __next__(self):
desc = "next for " + self.ref
try:
result = next(self.orig)
print(desc, '=', result)
return result
except StopIteration:
print(desc, "StopIteration")
raise
class Node:
def __init__(self, value, left=None, right=None):
self._value = value
self._left = left
self._right = right
def _iter(node):
if node._left:
for x in iter(node._left):
yield x
yield node._value
if node._right:
for x in iter(node._right):
yield x
def __iter__(self):
return WrappedIterator(self._iter(), 'Node %r' % self._value)
node1 = Node(1)
node3 = Node(3)
node2 = Node(2, node1, node3)
node5 = Node(5)
node7 = Node(7)
node6 = Node(6, node5, node7)
node4 = Node(4, node2, node6)
for value in node4:
print("Got value %r" % (value,))
---output---
next for Node 1 = 1
next for Node 2 = 1
next for Node 4 = 1
Got value 1
next for Node 1 StopIteration
next for Node 2 = 2
next for Node 4 = 2
Got value 2
next for Node 3 = 3
next for Node 2 = 3
next for Node 4 = 3
Got value 3
next for Node 3 StopIteration
next for Node 2 StopIteration
next for Node 4 = 4
Got value 4
next for Node 5 = 5
next for Node 6 = 5
next for Node 4 = 5
Got value 5
next for Node 5 StopIteration
next for Node 6 = 6
next for Node 4 = 6
Got value 6
next for Node 7 = 7
next for Node 6 = 7
next for Node 4 = 7
Got value 7
next for Node 7 StopIteration
next for Node 6 StopIteration
next for Node 4 StopIteration
--
You can see that next is called three times (log N) for each value
returned.
It's not about the stack space, it's about going up and down the stack
over and over.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Linear Time Tree Traversal Generator
On Wed, Sep 21, 2016, at 10:39, ROGER GRAYDON CHRISTMAN wrote: > Which only highlights my disappointment that my tree > traversal itself was O(n log n), unless I gave up on yield. Or you can give up on recursion. Recursive tree traversal is generally associated with passing in a callback in rather than implementing an iterable-like interface that can be used with a caller's for-loop anyway. def __iter__(node): stack = [] while stack or node: if node: stack.append(node) node = node._left else: node = stack.pop() yield node._value node = node._right -- https://mail.python.org/mailman/listinfo/python-list
Re: Pasting code into the cmdline interpreter
On Thu, Sep 22, 2016, at 09:45, eryk sun wrote: > On Thu, Sep 22, 2016 at 12:40 PM, Gregory Ewing > wrote: > > eryk sun wrote: > >> > >> Actually in a Unix terminal the cursor can also be at > >> the end of a line, but a bug in Python requires pressing Ctrl+D twice > >> in that case. > > > > I wouldn't call that a bug, rather it's a consequence of > > what Ctrl-D does. It doesn't really mean EOF, it means to > > send whatever the terminal driver has in its input buffer. > > If the buffer is empty at the time, the process gets a > > zero-length read which is taken as EOF. But if the buffer > > is not empty, it just gets whatever is in the buffer. > > > > There's nothing Python can do about that, because it > > never sees the Ctrl-D -- that's handled entirely by the > > terminal driver. > > Yes, FileIO.readall continues making read() system calls until it sees > an empty read. But if we know we're reading from a terminal, we should > be able to assume that a read either consumes an entire line up to a > newline character or the entire buffer, no? In other words, if we see > a read that returns less than the buffer size but doesn't end on a > newline, then for a terminal, and only a terminal, I think we can > infer Ctrl+D was typed and handle it as EOF. I don't see where you're getting that users should even expect ctrl-d at the end of a line to be treated as EOF. It doesn't behave that way in any other program - try it in cat, dash, etc. There are also other circumstances that can cause a partial read. For example, if the user types the dsusp character (^Y by default) on systems that support it, the program will be suspended and will receive a partial read when resumed. I wouldn't bet on a guarantee that you can't get a partial read if input is too long to fit in the driver's edit buffer (which may be smaller than the program's read buffer) on some platforms (though when I've tried it it simply stops accepting input until I hit ctrl-D or enter)... and savvy users may deliberately type ctrl-D for this purpose. And, of course, in readline, the terminal is really in cbreak mode and Python receives an actual Ctrl+D rather than having to infer anything. But here, too, other programs ignore it just like Python: try it in bash, zsh, etc. The only "bug" is in some users' simplistic understanding that "ctrl-D means EOF". -- https://mail.python.org/mailman/listinfo/python-list
Re: Can this be easily done in Python?
On Tue, Sep 27, 2016, at 15:58, TUA wrote:
> Is the following possible in Python?
>
> Given how the line below works
>
> TransactionTerms = 'TransactionTerms'
>
>
> have something like
>
> TransactionTerms =
>
> that sets the variable TransactionTerms to its own name as string
> representation without having to specify it explicitly as in the line
> above
What are you trying to do?
If you're trying to avoid saying it twice:
exec('%s=%r'%['TransactionTerms']*2)
If you're trying to avoid having it as a string:
def TransactionTerms(): pass
TransactionTerms = TransactionTerms.__name__
--
https://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to change the closure of a python function?
On Wed, Sep 28, 2016, at 11:41, Paul Moore wrote: > What "allows side effects" in languages like Haskell is the fact that the > runtime behaviour of the language is not defined as "calculating the > value of the main function" but rather as "making the process that the > main functon defines as an abstract monad actually happen". Well, from another point of view, the output (that is, the set of changes to files, among other things, that is defined by the monad-thingy) is *part of* the value of the main function. And the state of the universe prior to running it is part of the input is part of the arguments. -- https://mail.python.org/mailman/listinfo/python-list
Re: Expression can be simplified on list
On Thu, Sep 29, 2016, at 02:47, Rustom Mody wrote: > Your example is exactly what I am saying; if a type has a behavior in > which all values are always True (true-ish) its a rather strange kind > of bool-nature. For a given type T, if all objects of type T are true (true-ish, truthy, whatever), it does make using an expression of type T in an if-statement an incoherent thing to do, but it makes using an expression of type Union[T, NoneType] reasonable. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a mechanism equivalent to "trace variable w ..." in Tcl for Python?
On Fri, Sep 30, 2016, at 14:42, Ned Batchelder wrote:
> On Friday, September 30, 2016 at 2:16:10 PM UTC-4, Les Cargill wrote:
> > What is an equivalent mechanism in Python?
>
> There's no way* to hook into "x = 2", but you could hook into "x.a = 2"
> if you wanted do, by defining __setattr__ on x's class.
That or set cls.a to be a descriptor (using either @property or a
custom-made descriptor class)
class motor:
@property
def RPM(self): return self._RPM
@RPM.setter
def RPM(self, value):
print("RPM changed from", self._RPM, "to", value)
self._RPM = value
If you really wanted to get crazy, you could use self.__dict__['RPM']
instead of self._RPM, which would allow you to inject the descriptor
separately after the class has already been defined and used. Making it
work right if the definition of motor already has an RPM descriptor [for
example, if it uses __slots__] is an exercise for the reader.
> *OK, there might be some crazy hack involving your own class as the
> globals for a module or something, but it sounds ill-advised.
You can make your own class to be *the module itself* to support
external code's "mod.x = 2", but AIUI that won't apply to plain
assignment, which bypasses most of the relevant machinery.
--
https://mail.python.org/mailman/listinfo/python-list
Re: unintuitive for-loop behavior
On Fri, Sep 30, 2016, at 20:46, Gregory Ewing wrote: > What *is* necessary and sufficient is to make each iteration > of the for-loop create a new binding of the loop variable > (and not any other variable!). I don't think that's true. I think this is logic that is excessively tied to the toy examples that are used to illustrate the problem. You don't think it's common [at least, as far as defining a lambda inside a loop at all is common] to do something like this? for a in collection: b = some_calculation_of(a) do_something_with(lambda: ... b ...) There's a reason that C++'s solution to this problem is an explicit list of what names are captured as references vs values inside the lambda. I think what we really need is an explicit expression/block that gives a list of names and says that all uses of that name in any function defined inside the expression/block refer to the value that that expression had when the expression/block was entered. Suppose: [final exponent: lambda base: (base ** exponent) for exponent in range(9)] for exponent in range: 9 final exponent: def pwr(base): return base ** exponent result.append(pwr) for a in collection: b = some_calculation_of(a) final b: do_something_with(lambda: ... b ...) Maybe do stuff like "for final var in ..." for both loops and comprehensions, or "final var = expr:", depending on if we can make the intuitive-looking syntax well-defined. "final" is a placeholder for whatever new keyword is chosen, though I will note that even though IIRC Guido doesn't like this sort of thing, it would only appear next to identifiers in the proposed syntax and two identifiers not joined by an operator is meaningless. An alternative would be, considering that the problem only applies to nested functions, to expand the "keyword argument" hack into a less-"hacky" and less verbose solution, e.g. "lambda base, $exponent: base ** exponent" - creating, in effect, a keyword argument with the name 'exponent' that can't actually be passed in to the function. -- https://mail.python.org/mailman/listinfo/python-list
Re: segfault using shutil.make_archive
On Thu, Oct 6, 2016, at 12:46, Tim wrote: > I need to zip up a directory that's about 400mb. > I'm using shutil.make_archive and I'm getting this response: > > Segmentation fault: 11 (core dumped) > > The code is straightforward (and works on other, smaller dirs): Are you able to make a test case that reproduces it reliably without any specifics about what data you are using (e.g. can you generate a directory full of blank [or /dev/urandom if the compressed size is a factor] files that causes this)? Is it a large number of files or a large total size of files? -- https://mail.python.org/mailman/listinfo/python-list
Re: segfault using shutil.make_archive
On Thu, Oct 6, 2016, at 13:45, Random832 wrote: > On Thu, Oct 6, 2016, at 12:46, Tim wrote: > > I need to zip up a directory that's about 400mb. > > I'm using shutil.make_archive and I'm getting this response: > > > > Segmentation fault: 11 (core dumped) > > > > The code is straightforward (and works on other, smaller dirs): > > Are you able to make a test case that reproduces it reliably without any > specifics about what data you are using (e.g. can you generate a > directory full of blank [or /dev/urandom if the compressed size is a > factor] files that causes this)? Is it a large number of files or a > large total size of files? Also consider passing a logging object to make_archive and see if it prints out anything interesting before the segfault. import shutil import logging import sys logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stderr)) shutil.make_archive(..., logger=logger) -- https://mail.python.org/mailman/listinfo/python-list
Re: A newbie doubt on methods/functions calling
On Thu, Oct 6, 2016, at 19:27, Loren Wilton wrote: > So I don't want to WRITE a Python interpreter for the actual mainframe > environment. I want to use an interpreter for an existing environment > (Windows) where there are already a lot of existing libraries. But > since a lot of the data to be analyzed is on the mainframe > environment, and the results would be wanted there too, I need to > extend the Python data access to the mainframe environment. Honestly, the best implementation strategy I can think of is to first implement a Python interpreter for the actual mainframe environment. Then invent an RPC layer that can semi-transparently bridge the two for when you want to call a module that only exists in the Windows environment (or call _from_ such a module back to an object/module that only exists in the mainframe environment), whether it's because it requires a Windows library or because you want the Windows python interpreter to do the heavy lifting because it's faster. Do you have C in the mainframe environment? -- https://mail.python.org/mailman/listinfo/python-list
Re: how to refactor nested for loop into smaller for loop assume each of them independent?
On Sat, Oct 8, 2016, at 06:12, BartC wrote: > The OP's code however is a good demonstration of how crazy Python's > original for-range loop was: you need to construct a list of N elements > just to be able to count to N. How many years was it until xrange was > introduced? Python 1.4 had it, and that's the earliest version of the documentation that exists on the website. Python 1.0.1 does include rangeobject, with a timestamp on rangeobject.h of 1994-01-01. Python 0.9.1 does not. So it was added some time between the original alt.sources posting (February 1991) and version 1.0 (January 1994). And one could argue that 1.0 was the first "real" release of the language. And of course, you were always free to write: i = 0 while i < 99: i = i + 1 -- https://mail.python.org/mailman/listinfo/python-list
Re: how to refactor nested for loop into smaller for loop assume each of them independent?
On Sat, Oct 8, 2016, at 07:29, Steve D'Aprano wrote:
> The oldest version I have access to is the *extremely* primitive 0.9. Not
> surprisingly, it doesn't have xrange -- but it lacks a lot of things,
> including globals(), map(), named exceptions, "" strings ('' is okay),
> exponentiation, and more.
Really? I'm not sure exactly what you mean by "named exceptions", but
0.9.1 has RuntimeError, EOFError, TypeError, MemoryError, NameError,
SystemError, and KeyboardInterrupt... but exceptions aren't objects,
they're strings.
They're caught by identity, though - "except 'type error'" fails to
catch TypeError, and vice versa.
The most interesting thing that I remember noticing about python 0.9.1
is that == and != don't exist - the equality comparison operators were
<> and a context-sensitive =.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Making IDLE3 ignore non-BMP characters instead of throwing an exception?
On Mon, Oct 17, 2016, at 14:20, eryk sun wrote: > You can patch print() to transcode non-BMP characters as surrogate > pairs. For example: > > On Windows this should allow printing non-BMP characters such as > emojis (e.g. U+0001F44C). I thought there was some reason this wouldn't work with tk, or else tkinter would do it already? -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't Python include non-blocking keyboard input function?
On Tue, Oct 25, 2016, at 02:39, Steven D'Aprano wrote: > Not really. I think that lots of people think they need it, but > once they write a little utility, they often realise that it's not > that useful. That's just my opinion, and I'm one of those guys who > wrote one: > > http://code.activestate.com/recipes/577977-get-single-keypress/?in=user-4172944 Non-blocking (which your example here doesn't even do) isn't the same thing as character-at-a-time. It doesn't even imply it, technically - you could want to do other stuff and occasionally check if the user has entered a line, though *that* is even *more* involved on Windows because it means you can't do it with msvcrt.kbhit. -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, Oct 31, 2016, at 10:55, Wildman via Python-list wrote: > I have code using that approach but I am trying to save myself > from having to parse the entire shadow file. Grep will do it > for me if I can get code right. Python already has built-in functions to parse the shadow file. https://docs.python.org/3/library/spwd.html#module-spwd But you can't use sudo this way if you use that. But why do you want to use sudo from within the python script instead of just running the python script with sudo? -- https://mail.python.org/mailman/listinfo/python-list
Re: Immutability of Floats, Ints and Strings in Python
On Fri, Nov 25, 2016, at 06:33, Ned Batchelder wrote: > A Python implementation can choose when to reuse immutable objects and > when not to. Reusing a value has a cost, because the values have to > be kept, and then found again. So the cost is only paid when there's > a reasonable chance that the values will actually be needed again. > And that cost has to be weighed against the opposite cost of simply > making a new object instead. Of course, there are more complicated costs to consider. For an implementation where objects do not have a naturally persistent object identity (such as an immovable address in memory as in cpython) they may consider it easier to have an "object identity" that consists of the whole value for immutable types rather than pay whatever costs are associated with having a unique and unchanging "id" value. It's also not hard to imagine an implementation that has "references" consisting of a tagged union and incorporating the value in the "reference" itself (and therefore the id) for floats and small integer/string values, though I can't name any implementation (of Python, anyway - it's not uncommon for Lisp) that does so. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Mon, Dec 5, 2016, at 14:48, Michael Torrie wrote: > Wow. Does that actually work? And work consistently? How would it > handle globs like this: The rules are simpler than you're probably thinking of. There's actually no relationship between globs on the left and on the right. Globs on the left simply select the files to rename as normal, the glob pattern doesn't inform the renaming operation. A question mark on the right takes the character from *that character position* in the original filename. That is, if you have "abc", "rename ab? ?de" renames it to "ade", not "cde". A star on the right takes all remaining characters. If you include a dot, the "name" (everything before the last dot) and "extension" of the file are considered separate components [so in adddition to rename *.c *.d, renaming a.* b.* where you have a.py, a.pyc, a.pyo will work]. But if you don't include a dot, for example "rename abcde.fgh xyz*", it will rename to xyzde.fgh . -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Mon, Dec 5, 2016, at 21:21, Dennis Lee Bieber wrote: > They are languages in their own right, with their own rules. > > The Windows command prompt being one of the weakest -- it doesn't > support arithmetic and local variables, nor (to my knowledge) looping > constructs. BAT files are limited to something like 9 parameters (which > may > be the only argument for not expanding wildcards at the command line > level). There are only nine that you can name explicitly, but there's no obstacle to handling more with shift or %*. Also, there is a 'for' loop, though the syntax is somewhat arcane (and you can always loop with if/goto) It can do arithmetic with 'set /a', and there is a 'setlocal' command for local variable scopes. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Tue, Dec 6, 2016, at 02:01, Larry Hudson via Python-list wrote: > On 12/05/2016 06:51 PM, Nathan Ernst wrote: > > IIRC, command.com was a relic of Win9x running on top of DOS and was a > > 16-bit executable, so inherently crippled (and probably never support by > > the NT kernel). Whereby cmd.exe coexisted but ran in a 32-bit context. > > I know my 79-year-old memory is definitely subject to "senior moments" > and not too reliable, but > IIRC it was Windows prior to 9x (Win 3 and earlier) that were 16 bit and > ran on top of DOS. > Win95 was the first 32 bit version and was independent from DOS. Yes but there was no* 32-bit windows command interpreter - it ran DOS in a virtual machine inside it. Windows 3 did the same, actually - the real architecture of Windows/386 was a 32-bit protected mode host kernel called VMM32.VXD that ran all of Windows in one virtual machine and each DOS window in another one, leading to the odd consequence of there being cooperative multitasking between Windows apps but pre-emptive multitasking between DOS apps [and between them and Windows]. The fact that Windows was launched at boot by running "win.com" (either in autoexec.bat or manually at the command line) created a *perception* that windows ran "on top of DOS", but running it really *replaced* DOS in memory, putting the CPU into protected mode and everything. The ability to boot into (or exit to) DOS was because people still did real work (and games) in DOS and the virtual environment of DOS-on-Windows didn't perform well enough to be sufficient. *Well, I vaguely remember a version of cmd.exe that would run on Windows 98 floating around back in the day, but it certainly didn't come with the OS. It might have been a pirated Windows NT component. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Thu, Dec 8, 2016, at 01:20, Gregory Ewing wrote: > BartC wrote: > > And globbing doesn't take care of all of it: a Linux program still has > > to iterate over a loop of filenames. The same as on Windows, except the > > latter will need to call a function to deliver the next filename. > > Actually, most of them will require *two* loops, one to > iterate over a sequence of filespecs, and another for > the files matching each filespec. Speaking of which, I think I've advocated before for fileinput to perform these loops, and for some mechanism for argparse to do it, etc... seems like it's about that time again. There are other issues, like needing a way to do Windows' version of wildcard parsing with all its quirks, or at least some of its quirks - "*.*" for all files and "*." for files not containing any dot being the most commonly used in the real world. > Whereas the unix program only requires one loop. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Wed, Dec 7, 2016, at 00:15, Steven D'Aprano wrote:
> and the shell expands the metacharacters ? {...} * [...] regardless of
> how much
> smarts the command itself has.
>
> There are thousands of programs I might use, and they may implement who
> knows
> how many different globbing rules:
>
> - some might support * and ? but not {...}
Just to point out, brace expansion isn't globbing. The most important
difference is that brace expansion doesn't care what files exist. {a,b}c
becomes "ac bc" regardless of if the files exist. {a,b}* becomes a* b*,
and if no files match one or both of these, it does whatever the shell
does in such cases.
This is why you can do commands like "mv
fix_a_ty{op,po}_in_this_filename"
--
https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Wed, Dec 7, 2016, at 03:50, Peter Otten wrote: > Is there an equivalent to > > # touch -- -r > > on Windows? Doesn't need one - options conventionally start with /, and filenames can't contain /. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Wed, Dec 7, 2016, at 15:29, Lew Pitcher wrote: > But, point of fact is that the feature to disable globbing is not often > needed. Most Unix programs that accept filenames are happy to accept a > list of filenames. There is not much call for a program to perform it's own > globbing, like is required in Windows. > > In fact, I can only think of three Unix "commandline" programs that need > shell globbing disabled: > find - which performs it's own filename matching > grep - which uses regular expressions to search the contents of files, > and > sed - which uses regular expressions to edit the contents of files. > (I'm sure that there are a few more examples, though). tar can do its own filename matching in some contexts, to match files inside the archive for example. 7z does its own filename matching to allow distinguishing "extract from multiple archives" [x \*.zip] from "extract a list of filenames from a single archive" [x a.zip b.zip] - a BartC-compliant command line paradigm if I ever saw one. I suspect it also allows you to match files inside the archives in the list part. scp lets you pass glob patterns to be matched on the remote server. also, quoting for scp is somewhat unpleasant, since metacharacters in general, not just globs but also $variables, quotes,`commands` etc, are interpreted by both the local shell and the remote shell. sftp is a little more sane, but still has remote globs for fetching, and quotes to escape those globs. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Wed, Dec 7, 2016, at 22:41, Steven D'Aprano wrote: > Python's fnmatch lib is a good example. It has, or at least had, no > support for escaping metacharacters. Anyone relying on Python's fnmatch and > glob > modules alone for globbing will be unable to handle legitimate file names. That's not true. You can "escape" metacharacters by enclosing them in square brackets, forming a character class of a single character. I've done the same in SQL, so it occurred to me immediately. But of course you have to know you have to do this, and it's not immediately obvious that it will work for the square bracket characters themselves. Other implementations of globbing (including native windows) don't do this and don't even *have* square brackets as metacharacters. -- https://mail.python.org/mailman/listinfo/python-list
Re: python 2.7.12 on Linux behaving differently than on Windows
On Thu, Dec 8, 2016, at 20:38, Dennis Lee Bieber wrote: > On Thu, 08 Dec 2016 10:37:27 -0500, Random832 > declaimed the following: > >There are other issues, like needing a way to do Windows' version of > >wildcard parsing with all its quirks, or at least some of its quirks - > >"*.*" for all files and "*." for files not containing any dot being the > >most commonly used in the real world. > > > In the original 8.3 scheme -- no files "contained" a dot Yes, but they do now, and the compatibility quirks persist. At some point in the process *?. are translated to other reserved characters <>" in order to allow the same native functions to perform both the 'quirks mode' and more rigorous logic. -- https://mail.python.org/mailman/listinfo/python-list
Re: Splitting text into lines
On Tue, Dec 13, 2016, at 12:25, George Trojan - NOAA Federal wrote:
> >
> > Are repeated newlines/carriage returns significant at all? What about
> > just using re and just replacing any repeated instances of '\r' or '\n'
> > with '\n'? I.e. something like
> > >>> # the_string is your file all read in
> > >>> import re
> > >>> re.sub("[\r\n]+", "\n", the_string)
> > and then continuing as before (i.e. splitting by newlines, etc.)
> > Does that work?
> > Cheers,
> > Thomas
>
>
> The '\r\r\n' string is a line separator, though not used consistently in
> US
> meteorological bulletins. I do not want to eliminate "real" empty lines.
I'd do re.sub("\r*\n", "\n", the_string). Any "real" empty lines are
almost certainly going to have two \n characters, regardless of any \r
characters. It looks like what *happens* is that the file, or some part
of the file, had \r\n line endings originally and was "converted" to
turn the \n into \r\n.
> I was hoping there is a way to prevent read() from making hidden changes
> to the file content.
Pass newline='' into open.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Running python from pty without prompt
On Tue, Dec 13, 2016, at 11:01, Michael Torrie wrote: > On 12/13/2016 05:39 AM, Samuel Williams wrote: > > Michael, yes. > > > > FYI, I found out why this works. Pressing Ctrl-D flushes the input > > buffer. If you do this on an empty line, it causes read(...) to return > > 0 which Ruby considers end of input for the script, but the pipe is > > not closed. > > Currently Python does not appear to support this behavior. Possibly it > could be patched to support something similar, though. The problem is there's currently no way to differentiate "interactive mode" from "script run on a tty". You can get similar behavior with python -c "import sys;exec(sys.stdin.read())" -- https://mail.python.org/mailman/listinfo/python-list
Re: Running python from pty without prompt
On Tue, Dec 13, 2016, at 17:09, Michael Torrie wrote: > On 12/13/2016 10:48 AM, Random832 wrote: > > The problem is there's currently no way to differentiate "interactive > > mode" from "script run on a tty". > > > > You can get similar behavior with python -c "import > > sys;exec(sys.stdin.read())" > > Are you sure? I can pipe scripts into Python and they run fine and > Python is not in interactive mode. Yes, a pipe and a tty are two different things. > python < script.py > > The behavior the OP is looking for of course is a way of demarcating the > end of the script and the beginning of data to feed the script. It's more than just that - with a tty you can call sys.stdin.read() multiple times, and each time end it with ctrl-d. -- https://mail.python.org/mailman/listinfo/python-list
Re: Running python from pty without prompt
On Tue, Dec 13, 2016, at 19:10, Steve D'Aprano wrote: > Can you show a simple demonstration of what you are doing? > > I'm having difficulty following this thread because I don't know > what "script run on a tty" means. The question is literally about the input/script being the tty and not redirected from any other file, which causes an interactive prompt in CPython, but does not do so in some other languages. I don't understand what part of this you're not getting. > I thought that with the exception of scripts run from cron, any time you > run a script *or* in interactive mode, there is an associated tty. Am I > wrong? -- https://mail.python.org/mailman/listinfo/python-list
Re: Running python from pty without prompt
On Tue, Dec 13, 2016, at 19:20, Steve D'Aprano wrote: > sys.flags.interactive will tell you whether or not your script was > launched > with the -i flag. > > hasattr(sys, 'ps1') or hasattr(sys, 'ps2') will tell you if you are > running > in the REPL (interactive interpreter). The ps1 and ps2 variables aren't > defined in non-interactive mode. There's no way to *tell python to* run in non-interactive mode without using a file other than the tty as the script. It's not a matter of finding out from within python whether it's in interactive note, it's a matter of python finding out whether the user *wants* it to run in interactive mode. -- https://mail.python.org/mailman/listinfo/python-list
Re: Best attack order for groups of numbers trying to destroy each other, given a victory chance for number to number attack.
On Thu, Dec 15, 2016, at 08:31, Dennis Lee Bieber wrote: > As for my posts disappearing: I run with "X-NoArchive" set. I have from > before Google absorbed DejaNews. Back then, most news-servers expired > posts > on some periodic basis (my ISP tended to hold text groups for 30 days or > so, binaries groups cycled in less than 36 hours). When DejaNews arrived, > many objected to the non-expiration facet: > https://en.wikipedia.org/wiki/Google_Groups#Deja_News As I recall, what most people *actually* said they objected to was the fact that they profited from showing ads. X-No-Archive was just a convenient blunt weapon to hit them with. -- https://mail.python.org/mailman/listinfo/python-list
Re: OT - "Soft" ESC key on the new MacBook Pro
On Sun, Dec 18, 2016, at 17:03, Gregory Ewing wrote: > mm0fmf wrote: > > +1 for knowing where CTRL should be. > > Bonus +1 for having used an ASR33. > > And it's quite remarkable that the designers of the ASR33 > knew exactly where it would need to be for Emacs users > years later! I think Richard Stallman must have a time > machine as well. Except for the fact that the actual keyboard that Emacs was originally developed for [the Knight Keyboard, and the later Symbolics "Space Cadet" Keyboards] had the control key more or less where it is on modern PC keyboards [slightly further to the right, so easier to reach with the thumb of the same-side hand], and the Meta key to its left. To the left of A was "rub out". I assume the original Emacs users used proper touch-typing style: modifier keys with the opposite hand from the letter they were using it with, rather than trying to contort the same-side hand into hitting both keys at once. Meanwhile, users of Unix systems were stuck with terminals like the ADM-3A and VT-100, which, inherited from the ASR-33 but one must assume the real reason was to save money, only had one control key and no true meta key (one escape key). I suspect there would have only been one shift key if they could have got away with it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Simulating int arithmetic with wrap-around
On Fri, Dec 30, 2016, at 09:47, Steve D'Aprano wrote: > Again, assume both operands are in range for an N-bit signed integer. > What's > a good way to efficiently, or at least not too inefficiently, do the > calculations in Python? I'd do something like: bit_mask = (1 << bits) - 1 # 0x sign_bit = 1 << (bits - 1) # 0x8000 sign_ext = ~bit_mask # ...F def signed(value): if value & sign_bit: return value | sign_ext else: return value & bit_mask def unsigned(value): return value & bit_mask And also avoid doing it on intermediate steps where it can be shown to not affect the result or allow the value to grow too large. -- https://mail.python.org/mailman/listinfo/python-list
Re: Simulating int arithmetic with wrap-around
On Fri, Dec 30, 2016, at 09:47, Steve D'Aprano wrote: > Again, assume both operands are in range for an N-bit signed integer. > What's > a good way to efficiently, or at least not too inefficiently, do the > calculations in Python? I'd do something like: bit_mask = (1 << bits) - 1 # 0x sign_bit = 1 << (bits - 1) # 0x8000 sign_ext = ~bit_mask # ...F def signed(value): if value & sign_bit: return value | sign_ext else: return value & bit_mask def unsigned(value): return value & bit_mask And also avoid doing it on intermediate steps where it can be shown to not affect the result or allow the value to grow too large. -- https://mail.python.org/mailman/listinfo/python-list
Re: Extended ASCII
On Fri, Jan 13, 2017, at 17:24, D'Arcy Cain wrote: > I thought I was done with this crap once I moved to 3.x but some > Winblows machines are still sending what some circles call "Extended > ASCII". I have a file that I am trying to read and it is barfing on > some characters. For example: > >due to the Qu\xe9bec government > > Obviously should be "due to the Québec government". I can't figure out > what that encoding is or if it is anything that can even be understood > outside of M$. I have tried ascii, cp437, cp858, cp1140, cp1250, > latin-1, utf8 and others. None of them recognize that character. Can > someone tell me what encoding includes that character please. It's latin-1 (or possibly cp1252 or something else depending on other characters), your problem is elsewhere. > Here is the failing code: > > with open(sys.argv[1], encoding="latin-1") as fp: >for ln in fp: > print(ln) > > Traceback (most recent call last): >File "./load_iff", line 11, in > print(ln) > UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in > position 132: ordinal not in range(128) Note that this is an encode error - it's converting *from* unicode *to* bytes, for the print statement. > I don't understand why the error says "ascii" when I told it to use > "latin-1". You set the encoding for the file, not the output. The problem is in your print statement, and the fact that you probably have your locale set to "C" or not set up at all instead of e.g. "en_CA.UTF-8". -- https://mail.python.org/mailman/listinfo/python-list
Re: Open (txt) editor and get its content
On Thu, Apr 19, 2018, at 03:39, [email protected] wrote: > Is there any other option for getting interactive multi line input from user. If you don't need a full-featured text editor, you could build a simple input popup with the Textbox widget in tkinter. -- https://mail.python.org/mailman/listinfo/python-list
Can't drop files on python scripts in a fresh installation of Windows 10 and Python 3.7
Python itself runs fine, but when I try to drop a file on a script it just doesn't work. If I try to regsvr32 the shell extension, it says: The module "c:\windows\pyshellext.amd64.dll" failed to load. There was no indication of any problem until this. Apparently it is linked against "VCRUNTIME140.dll", not (or in addition to? peview shows both) the universal CRT. Installing the Visual C++ 2015 redistributable resolved it, but there was no instruction for this. -- https://mail.python.org/mailman/listinfo/python-list
Can't drop files on python scripts in a fresh installation of Windows
Python itself runs fine, but when I try to drop a file on a script it just doesn't work. If I try to regsvr32 the shell extension, it says: The module "c:\windows\pyshellext.amd64.dll" failed to load. There was no indication of any problem until this. Apparently it is linked against "VCRUNTIME140.dll", not (or in addition to? peview shows both) the universal CRT. Installing the Visual C++ 2015 redistributable resolved it, but there was no instruction for this. -- https://mail.python.org/mailman/listinfo/python-list
Re: List of Functions
On Mon, Mar 28, 2016, at 19:40, Steven D'Aprano wrote: > Not to mention "Monad". I don't think *anyone* knows what a Monad is ;-) A monad is just a monoid in the category of endofunctors; what's the problem? Well, someone had to say it. -- https://mail.python.org/mailman/listinfo/python-list
Re: [stdlib-sig] Can imaplib be improved?
I'd posted this to [email protected] without realizing that that list is mostly dead. On Thu, Mar 24, 2016, at 22:33, Random832 wrote: > I assume that everyone who has ever used imaplib is familiar with how > painful its output format is to deal with. I am wondering if anyone else > has any ideas on ways it can be extended in a backward-compatible way to > provide options for better parsing, handling unilateral data from the > server, processing data as it comes in, etc. Anyone have any thoughts? -- https://mail.python.org/mailman/listinfo/python-list
Re: [stdlib-sig] Can imaplib be improved?
On Tue, Mar 29, 2016, at 14:45, Grant Edwards wrote: > I think giving up on backwards compatiblity and starting from scratch > is the best idea. > > I like imaplib2 > > https://pypi.python.org/pypi/imaplib2 > https://github.com/bcoe/imaplib2 > https://sourceforge.net/projects/imaplib2/ > > imapclient is pretty nice to work with: > > https://pypi.python.org/pypi/IMAPClient > https://bitbucket.org/mjs0/imapclient > http://freshfoo.com/presentations/imapclient-intro/#/ > > Perhaps it (or something like it) could be added to the std library > alongside the current imaplib. I couldn't get imapclient to install; I got some kind of error (I can't remember, and can't reproduce now because it "thinks" it was successful) from pip installing some crypto dependency, and a runtime error not finding a SSLContext class. I haven't tried imaplib2 yet; by the time I discovered it my scripts were already mature enough that I just finished with what I had. -- https://mail.python.org/mailman/listinfo/python-list
Re: Threading is foobared?
On Tue, Mar 29, 2016, at 19:54, Rob Gaddi wrote: > Just read on Usenet instead of through the mailing list. That way > you can accept broken threading as a given rather than wonder why it's > happening in a particular case. It's a given everywhere. Any thread that contains a sufficient number of replies from both users using usenet and users using the mailing list (gmane counts as the mailing list, since it _doesn't_ do the broken stuff) is going to be broken for everyone everywhere, though it will be broken in different places. For users reading by the mailing list, Usenet users' replies to Mailing List users will be broken (but their replies to each other will be fine). For users reading by Usenet, Mailing List users' replies to each other will be broken (though all replies made via Usenet or to Usenet users will be fine). -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion: make sequence and map interfaces more similar
On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote: > The map contract is this: > > x = StrangeDict() > x[123] = 456 > ... > assert x[123] == 456 > > Your mapping does violate the map contract. So, you can put *anything* in that "..."? x = dict() x[123] = 456 x[123] = 789 assert x[123] == 456 dict violates the map contract. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion: make sequence and map interfaces more similar
On Wed, Mar 30, 2016, at 01:43, Steven D'Aprano wrote: > This is not an argument about dicts being mutable, because clearly they > aren't. This is an argument about key:value pairs being stable. "Stable" > doesn't mean "immutable". If you change the value associated with a key > directly, then it will change. That's the whole point. But if you change > *one* key, the relationship between *other* keys and their values > shouldn't > change. This doesn't mean that an object violates the contract by having a method that changes the relationships between multiple keys and values. I had considered including an example of replacing the _whole dictionary_ with a new object in the ellipsis. Absolutely nothing is stable under a *completely unrestricted* set of operations. > Specifically, insertions and deletions to the mapping never affect the > existing keys. You can't say that, because there is no insert and delete method in the mapping interface. > If somebody wants to insist that this is a kind of mapping, I can't > disagree, but it isn't useful as a mapping type. Javascript seems to manage it just fine. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion: make sequence and map interfaces more similar
This discussion is getting a bit distracted from the original request. Let's look at it from a higher level. What is being requested, regardless of if you call it a "map interface" or whatever, is a single way, for sequences and maps... broadly, anything with a __getitem__, to iterate over all values which one might pass to __getitem__, so that one might (among other things) call __setitem__ to mutate the collection. Like, these are common patterns: for i, x in enumerate(l): # do some stuff, sometimes assign l[i] for k, v in d.items(): # do some stuff, sometimes assign d[k] A way to apply that pattern generically to an object which may be either a sequence or a mapping might be nice. Or some other way of doing this operation - maybe a writable iterator like C++ or Java. -- https://mail.python.org/mailman/listinfo/python-list
