« first day (3146 days earlier)      last day (2027 days later) » 
00:00 - 15:0015:00 - 00:00

15:00
For regular non-reversed dunders, the docs say "If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented." (docs.python.org/3/reference/datamodel.html#object.__or__)
One might expect that this also applies to reversed dunders
@Sam How many items would you typically be summing? What actually happens when you add two class instances? sum might get very inefficient when summing a large list, which is why sum won't let you pass it a list of strings to concatenate.
Ah, the type hierarchy confirms this higher up in the page. "Numeric methods and rich comparison methods should return [NotImplemented] if they do not implement the operation for the operands provided"
__radd__ is a numeric method, QED
class Thing:
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return Thing(self.x + other.x)
    def __radd__(self, other):
        if isinstance(other, int) and other == 0:
            return Thing(self.x)
        else:
            return NotImplemented

seq = [Thing("Hello, "), Thing("World"), Thing("!")]
print(sum(seq).x)
#result:
#Hello, World!
Now 10% more standards-compliant
@Kevin
class Thing(collections.UserString):
    def __radd__(self, other):
        if isinstance(other, int) and other == 0:
            return self

seq = [Thing("Hello, "), Thing("World"), Thing("!")]
print(sum(seq))
15:05
If you haven't seen it before, you should read Joel Spolsky's classic article about Shlemiel the painter’s algorithm.
Yes, yes, multiple string concatenation is catastrophically slow and we should all use .join. Unclear whether Sam's actual class has anything to do with strings at all.
All I cared about is being able to use sum without having to specify the start
ok, turn puzzle upside down. What could you pass to start that would enable you to sum almost arbitrary classes
@Kevin True, which is why I asked what adding 2 of his instances actually does, just in case there's a way to avoid O(n^2) behaviour.
@piRSquared A class X where X()+a always returns a
>>> sum([1, "foo", 2j, -0.5, {1:2}, {3}, [4]], type("SelfishSummer", (object,), {"__add__": lambda self, other: self})())
<__main__.SelfishSummer object at 0x03085AB0>
sum('Hello World'.split(), type('Thing', tuple(), {'__add__': lambda a, b: b})())
15:12
Of course, then a has to define sensible addition behaviour.
my bad, class is arbitrary but consistent within the sequence
Actually, why wouldn't this be a more sensible default start?
type('Thing', tuple(), {'__add__': lambda a, b: b})()
It works for anything [citation needed] and provides all the same default behavior.
Perhaps they want sum([]) to return 0 and don't want to special-case it
except for failing of course
ok ^^
Looks like Sam's solved his problem, and isn't too concerned about possible optimizations. I guess that's his prerogative.
As is my custom I will now construct a cardboard diorama representing Sam's problem and place it in my Closet of Unsolved Mysteries
15:18
Go|f: an empty tuple.
(*[],)
@piRSquared huh?
I was trying to golf the creation of an empty tuple. I said it, then came up with what I thought was the shortest thing I could.
Just () creates an empty tuple :)
yeah, I confused myself there
15:23
ZOMG! How did I not know that /facepalm
you're too busy splatting everything for no reason
Relatedly, I wonder if there's a way to make a tuple using exactly three non-whitespace characters.
I thought (,) was legal but it seems not
an empty tuple?
15:24
Maybe that's a parameter list only thing
or any?
[],
Let's say empty.
@Kevin technically (), would be a tuple - but not empty :)
True
if only tuple implemented unary plus...
Loophole closure: zero points for suggesting (); or ()#
Cheater... ()#
15:28
Got em
dang it!
@Kevin do meet the original rules though :p
mmm, what is this? ,,*
syntax error
It was a typo while I was messing around, but my IPython console outputs ',*', a string
It's invalid in a regular python interpreter for the same python version
15:34
I'm just going to run all 16 million three letter combos through eval and see if any of them become empty tuples.
Not sure whether it's taking a long time or hanging or erasing my hard drive or what
@roganjosh it's a syntax error in my ipython
perhaps you have some magic set differently, like when you can omit parentheses
It's probably easier to chalk it up to being Spyder
I see you also like to live dangerously
Weighing up the fact that it's useless anyway, and cannot be repeated in your ipython, I think I'll drop it
It's done. The only solutions that don't use regular whitespace or comments are ['\x0c()', '(\x0c)', '()\x0c']
I assume \x0c is some kind of fancy whitespace.
There you go.
----> 1 unicodedata.name('\x0c')

ValueError: no such name
sad
unicodedata.name isn't very good at characters in the ordinal range 128-256, in my experience
Oops, but "\x0c" isn't in that range, is it. Well, whatever.
15:44
@Andras maybe you want: unicodedata.category('\x0c') ?
never heard of it, but could be
'Cc' as in control character, I guess
for '\xac' I get samarium
"\x0c" is ^L, or formfeed, in ASCII.
Closely related to Esc-c, which is a standard clear & reset control sequence in VT100 terminals.
I'm a little surprised that formfeed and other horizontal control characters like "\n" don't cause eval to crash.
16:02
It's just whitespace. FWIW, I often use ^L to clear the terminal when its full of distracting rubbish. It mightn't do much on Windows though.
And back in the days of paper teletype terminals, ^L was the standard way to scroll to the top of the next page.
16:28
I wonder if shuttles are designed with lightning protection features or if lightning just naturally passes harmlessly along the hull without going through the interior, or what
Relatedly, today's pet peeve is people spelling it "lightening"
That's one of those mistakes that spellcheck can't save you from
I haven't watched the video, but I assume the shuttle is a Faraday cage, approximately.
"Lightening" is also one of my peeves, but it doesn't annoy me as much as the use of "loose" when "lose" is what they meant.
It's a relatively short video, if you're unsure of whether you can fit it into your schedule :^)
@PM2Ring that's a bit shaky assumption since it's not grounded and there's high-frequency charge oscillations
it might work, but I'd be cautious
@AndrasDeak True. That's why I said "approximately". :)
:)
although there's a spark above and below so it might have been close enough to grounded thanks to the ionized channels
16:35
@Kevin Ok, I'll take a look. I have to ration my YouTube usage. I only get 18 gig a month.
You poor soul. I'll mail you some AOL discs.
@PM2Ring high on the list, but surely it can't top "scrap" instead of "scrape"?
At least "loose" and "lose" can be the same part of speech, so sometimes one can substitute for the other.
"We can't get into the house as long as those watchdogs are in the garden", said burglar Alice to burglar Bob. "Open the gates so we can (lose|loose) those hounds"
@roganjosh That's a close call, but I think "lose"/"loose" wins because it's everywhere, but "scrape"/"scrap" has a very restricted domain.
I suppose lightening can be a noun too, so the same trick can be applied there. "The cargo bay doors opened and the heavy boxes fell out into the roiling storm clouds. Pilot Carol was thrown-off balance by the sudden light(e?)ning, but quickly regained control of the plane"
wim
wim
17:16
@roganjosh that ipython autocall garbage
>>> ,print hello
hello
>>> ,,print hello
(',print', 'hello')
I guess, neither lose nor loose fits into the second sentence.
@wim thanks for highlighting autocall
wim
wim
it's horrible syntax
basically: ,f x y # becomes f("x","y")
with semicolon also ;f x y # becomes f("x y")
IIRC the default function is repr which would explain the weird result for ,,*
@roganjosh that's what I was trying to get at chat.stackoverflow.com/transcript/message/46340532#46340532
it's just so useless I don't even know its name or exact behaviour
The uselessness was key in me dropping my investigation, but it's at least nice to know roughly what was happening there :)
17:30
Hi there
Hello :)
looking for some python programmer than can give me one hint
wim
wim
I can't believe it still works I thought they had deprecated this years ago
I'm building a toy JPEG programmer
*compressor sorry :)
I'm using Scipy's DCT scipy.fftpack.dct
and it works
Andras said he couldn't replicate so perhaps it is. Spyder reports IPython 6.1.0
17:33
however, I'd like to programatically generate the basic cblocksw
*blocks
Every couple of months I try to learn how fourier transforms work and every time I retain about 5% of it. I should have a complete understanding by 2022.
It's easy, you just take an infinite number of sine waves whose amplitude/wavelength/x_offset are determined via [mumble] and then you add them together to get the curve you want.
@Jose this topic is well out of my area of expertise, but you haven't asked a question so I think it will be hard for others to help you.
wim
wim
huh, TIL new ipython feature
>>> *f*?
BufferError
ConnectionRefusedError
OverflowError
ReferenceError
defaultdict
filter
float
format
frozenset
print_function
@Jose Also note that you can edit your posts for up to 2 minutes. Hover over the left side of your post and you'll see a down arrow. Click that and you'll get a menu with "edit" in it.
You can then use the coefficients of those waves to do... Discrete things.
This is very good because some things can only be done discretely, and undescretize(f(discretize(x)) can sometimes be used in place of f(x) where f is a pain in the butt to implement on continuous data
17:54
@wim doesn't work for me, in principle vanilla ipython
@Kevin Fourier in action (sort of) imgur.com/gallery/LktfqxG
I'm using 7.2.0
I think its not working for me is a good sign
Amazing that they could embed a scipy environment in that tachometer
wim
wim
18:10
yeah the ,,* thing stops "working" 7.0.0
I've actually seen one of those during lab practice in undergrad, it metered frequencies around 50 Hz and it was used to monitor the mains power frequency
wim
wim
however that should still work:
>>> , ,*
',*'
ah, indeed
so that's why you pointed me to the parser
wim
wim
because they never actually removed the feature. just rewrote the implementation.
you probably didn't notice, but the syntax error from ,,* in python is a different syntax error from the same thing in IPython
Is FFT one of those things that you could theoretically do with a slide rule or three vacuum tubes, and it's only because of Modern Enterprise Design that we need to download a hundred meg library to get it working on the desktop?
wim
wim
18:15
(the former fails to parse, in the latter it parses but then fails later on, in a way that also happens to be a SyntaxError)
@Kevin Sure. You only need multiplication & addition to do FFT. And you can do Fourier transforms with analog components, like optical systems.
The tachometer I linked might be such an example. The metal bars in the device all resonate at a distinct base frequency, and only the ones in resonance with the engine will vibrate.
I suppose if you want to do a discrete Fourier transform by hand, you should also know how complex exponentials work.
@AndrasDeak s/bar/rod/, probably
It's a good exercise to do a DFT on paper, just to get a feel for how it works. There's a worked example on Wikipedia of a simple DFT of 4 points: en.m.wikipedia.org/wiki/Discrete_Fourier_transform#Example Unfortunately, they don't do the inverse transform to recover the original points from the spectrum, but the working is almost identical.
@AndrasDeak Similar to what happens in our ears, except its different sections of the cochlea that resonate, and the "hairs" (attached to nerves) in a resonating section vibrate more than the hairs in a non-resonating section.
18:35
What's up dudes, so i got this code right here:

with open('brute.txt', 'r') as f:
lookup_dic = {word.strip(): None for word in f.readlines()}
with open('SaveFile.txt', 'r') as f:
lines = (line.strip().split(' = ') for line in f.readlines())
for lookup, val in lines:
if lookup in lookup_dic:
print(f"{lookup} matched and its value is {val}")
lookup_dic[lookup] = val

Here is a quick explanation, I'm making a Python program that "reverse engineer" a Batch game save file and which is "SaveFile.txt", so here is a quick look at the file:
Obligatory disclaimer: dynamically setting a bunch of variables is almost always a bad idea, and you can almost always do nearly the same thing by storing your values in a dictionary. With that out of the way: try updating the dictionary returned by globals() or locals().
>>> s = "main_health"
>>> globals()[s] = 999
>>> main_health
999
Writing to locals() is definitely not recommended. And IIRC, it doesn't work, unless locals() happens to be an alias of globals()
The principal danger of dynamic variable names is that you might override a variable name that's already referring to something useful. Suppose your batch game defines a Strength variable, named str. If you update the globals dict with that, suddenly you can't use str() to convert things to strings.
A secondary problem is if you set a name that isn't actually a legal name. Suppose you set the key "class" to be "fighter". You're not going to be able to access that value directly, because class is a reserved word.
>>> globals()["class"] = "fighter"
>>> class
  File "<stdin>", line 1
    class
        ^
SyntaxError: invalid syntax
You can still access the value by retrieving it from the globals dict, e.g. print(globals()["class"]), but this defeats the ostensibly most attractive feature of using dynamic variables in the first place: so you can access variables without using dict indexing syntax.
18:50
I'd argue that the greater concern over mucking with globals is the difficulty in finding errors. I'd go as far as to say that almost all best practices are geared towards making code maintainable and more long lived.
wim
wim
Yes I was just about to say the same. The main problem is really that it makes the code ugly
Even if you're certain that you'll never overwrite built-in functions or keywords, you might end up discovering that dynamic variables don't win you much clarity over using a regular dict. Especially if you need to do anything remotely fancy, like "given a variable whose name is stored in the string s, find its value" or "determine whether a variable whose name is stored in the string s exists at all". Neither of these can be done without using dict methods on the global dict.
wim
wim
if you're implementing a REPL or something you might need to do just that, otherwise it just muck the boundary between "data" and "code" in a confusing way
If sheep1coder's ultimate use-case is "I want to extract these values from the file and dump them into a REPL with known-good names so I can experiment with them in a freeform manner", then that's about as close as you can get to an actually good justification of dynamic vars
I'm going to get my diorama supplies
19:35
This isn't a list comprehension. Nor is it unpacking, exactly. When I'm describing what I'm doing, what do I call this? {*range(5)}
I do think it qualifies as regular iterable unpacking, as described by docs.python.org/3/reference/expressions.html#expression-lists
The section confirms that unpacking can be performed in tuple, list, or set literals
Oh, ok, then when I called it literal unpacking I wasn't too far off. stackoverflow.com/questions/56348725/…
Yeah I think that's a fine description in that context
still bummed that unpaccking in comprehensions wasn't accepted
Also, in what circumstance is {1, 2, 3} - [1] not perfectly unambiguous? Meaning, what wasn't set.__sub__ written to handle that.
19:44
Or, hmm, maybe "The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking" does not explicitly mean that iterable unpacking is legal within each of those literals. But it's easy enough to confirm that it's legal in lists and sets by observing the starred_list element in docs.python.org/3/reference/expressions.html#list-displays and docs.python.org/3/reference/expressions.html#set-displays
wim
wim
especially since {1, 2, 3}.difference([1]) is ducked correctly
I'm not sure where "tuple displays" are defined in the syntax, since they don't have their own section like list and sets and dicts do. I think it's a subset of Expression Lists
^^ Yeah!
wim
wim
one problem with using syntax tricks like {*var} instead of just set(var) is that it makes the code harder to google
characters like * tends to confuse search engines
so, don't go splatting everywhere just to be cool
PiR will have none of this square talk
19:49
If I never see a post on SO asking "what does * do?" again, it will be too soon
I 100% understand why the asker couldn't find the answer, but I'm just. So tired.
lol... I definitely splat gratuitously. But I can't claim its for the purpose of increasing my cool factor.
I only do literal unpacking as a party trick.
wim
wim
interestingly enough, the keys views which are supposed to be "set-like" will duck type the list for set difference
>>> dict.fromkeys({1, 2, 3}).keys() - [1]
{2, 3}
I'll start including links to symbolhound
@Kevin Or dict union?
19:55
When I combine dictionaries, I like to do it the long way so I can be explicit about the behavior of overlapping keys
Perfectly clear to me {**dict(zip('abcd', range(4))), **dict(zip('cdef', range(4)))}
Yeah, dict unpacking I consider very pythonic
wim
wim
gray brain - crazy dict union with splat unpacking
glowing brain - just writes a for-loop
galaxy brain - `from collections import ChainMap`
well, I guess there's ChainMap too
20:16
@piRSquared Pity that enumerate doesn't take a keyword arg to swap the order of the index and the value from the iterable.
So you could do dict(enumerate("abcd", swap=True)). Or something like that.
no no no, make it mode="swap"
map, reverse to the rescue...
dict(map(reversed, enumerate('abcd')))
I keep forgetting that json.load exists, so I can do json.load(f) instead of json.loads(f.read())
I feel like that's an unloved feature
wim
wim
mode="swap" sounds like it will take 10 times longer and make your hard disk groan
hard disk?
hard drive, do you mean?
20:20
hard disk drive
well, yes, I guess, I've just never seen it abbreviated to hard disk
if your soft disk groans you have a hernia
wim
wim
hard disk as opposed to floppy disk
if my soft disk groans I think i'll be in the hospital
huh, that's weird: hard drive versus floppy disk
hard disk vs. floppy drive: the ole' switcheroo
because it's the actual disk that's floppy, until of course the 1.44 MB floppies that no longer flop
20:23
I guess my joke was a flop then
;)
wim
wim
@tripleee eliza?
@piRSquared I've contemplated doing that, but the readability sucks. And I'd rather avoid the overheads of calling reversed on every index, value pair.
@AndrasDeak The disk inside the case is still floppy, though.
wim
wim
and disc-shaped
Quite.
@PM2Ring I'll answer channeling my inner @Aran-Fey {k: v for v, k in enumerate('abcd')}
wim
wim
20:32
generator comprehensions are readable, so map can just go in the trash (functools)
also they should rename functools to funktools to make it more clear that it's a stinky dumping ground
@piRSquared I approve of this code
@piRSquared That's what I generally do these days. I didn't have that option in 2.6, since it doesn't have dict comps.
@PM2Ring what matters is on the inside, etc. Too abstract for me ;)
Ooh! Here's another "good" option dict(zip(*[*zip(*enumerate('abcd'))][::-1]))
I probably shouldn't admit to having tried that option. :)
wim
wim
20:44
my eyes, ze goggles do nuthink
I wouldn't have used it in real code. I was just testing that it worked as expected.
Stupid referencing tricks in various languages, starting here: forums.xkcd.com/viewtopic.php?p=4458230#p4458094
21:07
1 message moved from The advanced python group
What's going on here?
covert advertisement for a competing python room?
Seems like it.
Hello, is it possible to have a custom library to use the spark context of a notebook ?
@Aran-Fey "covert". Indeed :P
21:16
I have a name a that is pointing to an iterable iter(range(10)). I use up 3 of them with [next(a) for _ in range(3)]; Now I want to prepend another iterable.
def prepend(this, that):
    yield from this
    yield from that

[*prepend('abc', a)]

# ['a', 'b', 'c', 3, 4, 5, 6, 7, 8, 9]
@Anonymous do not do that please
is there better syntax for that sort of thing? I know about itertools.chain. I guess that is just
def prepend(*args):
    for arg in args:
        yield from arg
Not sure why you don't just use itertools.chain
piR hates using adequate tools :P
@PM2Ring reminds me of CRTP I read just yesterday about
yeah, neither do I. For a second I anticipated I'd keep having to prepend. It seemed to me having some weird nested chain(iter10, chain(iter9, chain(iter8, ... ))) was bad. But probably not
21:27
chain(*list_of_iters)
you know, like a chain...
Or chain.from_iterable.
oh, right
Yes but no. like 1) it = iter(stuff) 2) use some it 3) prepend some more stuff 4) use some more stuff 5) prepend some more stuff ... all in a dynamic way such that I couldn't have chain(*list_o_iters) in the first place
Is that not a very weird situation to be in? Any chance it's an XY problem?
That sounds like a use case for a stack or deque.
21:31
@AndrasDeak Ok. I don't know C++, but I kinda get it.
Absolutely not... it's worse. It's an X... problem. Because I'm just thinking about it and I don't have an actual problem to solve.
Either way chain solves it so...
Doing that with chain is going to progressively slow down as the pile of chains gets bigger, until eventually you blow your stack space and either RecursionError or segfault. Not sure which.
ok, theoretically, is there a way to set it up such that you can do indefinitely?
21:34
The stack of iterators pattern: garethrees.org/2016/09/28/pattern
chain.from_iterable is better than chain(*list_o_iters), since it expands the list lazily, so it won't die if list_o_iters is actually an infinite iterable.
I'd probably manage prepended elements with a list used as a stack. append to the list for a logical prepend, pop to consume prepended elements. Depending on whether it makes sense to materialize stuff (or if stuff is already a list or something), I might throw the contents of stuff on the stack too.
stack = stuff[::-1]
while stack:
    item = stack.pop()
    ...
    if whatever:
        stack.append(new_thing)
Something like that.
There's some cute stuff related to this in heapq.merge
wim
wim
yah i was just going to say it sounds like a priority queue
yam! too much reading and I have to start driving. Thx for the reading material and rbrb
rbrb
21:49
@user2357112 I don't think it's good practice to reverse a list just for easier modification
why not just use list.insert(0, new_thing)?
@connectyourcharger: Because list.insert(0, new_thing) is crazy slow.
Or even new_thing + list?
This kind of thing can be the difference between your program finishing in a minute or a day.
Seems a bit better and arguable more readable because the reverse slice can be confusing for the rest of the block
@connectyourcharger you're wrong
21:51
Is the + operator not fast?
see also
Faster than .append?
Nov 9 '18 at 0:11, by PM 2Ring
@PaulMcG Building a list by cumulative concatenation of lists in a loop isn't so good. It's pretty much like building a string by concatenation in a loop. Joel Spolsky calls it the Shlemiel the Painter algorithm.
read the linked post
interesting
Now I'm intrigued to let timeit decide this argument
It's not the exact same thing but if you create new lists in a loop you can lose a lot. And prepending to a list will have to move the entire contents each time I think.
21:54
What about combined with the .pop() call?
pop(0)?
I guess arguably that would be faster because of not wasting the item lookup time
but that's trivial if I know my list operations
Yes pop(0) and insert(0) have to move the entire underlying storage
Which should eat up time
Better to use a deque and popleft()
21:56
rather quickly, too
deque would most likely be the best solution
@connectyourcharger That's slow because it has to shift all the subsequent items up to make room for the new item at the front. It does that at C speed, but best to avoid if you can, and definitely don't do it in a loop. [a] + lst is ok, since it can copy everything to a new list (assuming you have the RAM to spare for the copied list), but once again, you don't want to do it in a loop.
Interesting points. I'm now mildly convinced to timeit.
deque is good for queues & stacks. It's actually faster than list for a stack.
I don't see any reason to consider [a] + lst more okay than lst.insert(0, a). Either option involves going over all of lst, whether to copy the items or to shift them.
rbrb for today, all
22:02
rbrb
@user2357112 Well, it's only marginally faster, at the expense of using double the RAM. And the overhead of creating & deallocating the extra list.
I guess there's not really a good solution at all.
yeah, we need to switch to Go
Copying the list is slightly faster than shifting the list item pointers in-place.
22:06
@user2357112 You also have to go over the whole list if you reverse it. But you only need to do that once.
clearly you need to convert it to a numpy array so that reversing it is just a view
Numpy would be even faster, good point
wim
wim
list is fine for a stack. if deque is somehow faster I'll bet there's only some nanoseconds in it... they're both O(1)
@connectyourcharger: No, NumPy doesn't support efficiently adding new elements to an array at either end (or removing elements, either). I'm pretty sure Andras was joking.
Well, I think it would be trivially faster regardless - you would just have to pick the best solution optimized for NumPy.
22:14
I clearly wasn't :PPP
Probably the reversed-pop-append thing
could be optimized
but this is my completely unprofessional opinion :P
actually, let the record state that my opinion is completely professional
@wim The speed difference isn't huge, but it's noticeable, IIRC. But probably not big enough to worry about changing old stack code to use deque instead of list.
 
1 hour later…
23:44
cbg
00:00 - 15:0015:00 - 00:00

« first day (3146 days earlier)      last day (2027 days later) »