« first day (2774 days earlier)      last day (2399 days later) » 
00:00 - 22:0022:00 - 00:00

00:17
cbg
@OneRaynyDay, it's Monday here already though.
01:02
@SeanFrancisN.Ballais oh. Sorry for your loss
It's a weird Monday though
how so
01:46
cbg
02:07
@OneRaynyDay, I like Mondays.
02:32
@SeanFrancisN.Ballais then I'm not sure if Monday is the weird one
:D
Sorry, I feel tired rn.
I might have weird responses.
03:05
Hi all
Is there anyone here who knows JS?
Evg
Evg
Hi guys. I need to send post request to the server. I receive 406 status code "Not acceptable". I'm very newbie in web.
requests.post(URL, headers={"user-token": USER_TOKEN},
data={"ws_job[ws_method_id]": 29, "ws_job[input]":json.dumps(request_json_dict)})
URL and request_json_dict are set
There's an error on the console when I try to npm install clockwork
Evg
Evg
I'm making it for this api
http://ws-dss.com/cms/en/restful-api-example
03:33
@DiViHart, you prolly want ask in a JS chat room.
@Evg, what's your traceback?
@SeanFrancisN.Ballais OK, I am.
Evg
Evg
@SeanFrancisN.Ballais How to get this traceback? I have an object of response
@Evg, check the terminal. If there's a message of an error, it'll show up there.
Evg
Evg
@SeanFrancisN.Ballais By terminal you mean console?
Evg
Evg
03:39
@SeanFrancisN.Ballais This API is not mine. I only send request and receive 406. So there is nothing in my console
Can you show us your code?
Maybe put it up in GitHub Gist.
Evg
Evg
@SeanFrancisN.Ballais Just 3 last lines. In the beginning there is data
03:59
Tried your code
I don't get any errors
Okay, I get it now.
Have you read the API docs?
I can't read Russian so I couldn't help.
Sorry.
 
2 hours later…
05:36
hello from cupertino!
@smci Need my dupehammer?
I think he needs inputs first, and probably a good canonical answer / question
@AndyK too broad is probably a better cv reason there
@coldspeed sounds good
never easy to find the 'spot on' reason when asking for closure
@IljaEverilä o/
06:13
@coldspeed sure, but shouldn't we have a good canonical before we start mass closings? I have not seen any good canonical answers, and as mentioned a good answer would be way too long to be easily readable. Most users don't care about security holes from user input to shell, some do. But if they learn the wrong way, that's dangerous for the future.
@shad0w_wa1k3r Yes exactly. Post your thoughts in the meta question folks...
 
1 hour later…
07:57
What do I do about this question? It has been unclear for 7 years. Can/should we delete that?
Don't see why it should be deleted, though it's not that great either.
Just got done writing the latest pandas canonical. A little niche though
@IljaEverilä Close as unclear, then?
In hindsight given the accepted answer they were after the set-like solution.
Can anyone look this over and let me know if it needs anything more before I can submit it to sopython's pandas canon list?
user7986928
08:13
@PM2Ring thanks. Thought that it is inappropriate question to put here.
When a 33k rep user answers a "find non-unique words in a sentence" question and tells you filter(lambda x: words.count(x) > 1, words) isn't a repost...
And "if you want efficiency, you should program in assembly instead of python". I wish I was joking.
@coldspeed a) str.translate will be fast until it runs out of memory. You might want to note that and show how you'd do chunking b) You replace all punctuation with '', even [,\.:] that could be undesirable in concatenating words ("first-past-the-post" becomes "firstpastthepost"). Might want to allow configurability to replacing some of those with space. c) It's not really Unicode-friendly; someone recently posted the opposite translation, a regex with a pattern which...
... negated everything which wasn't alphabetical, numerical or string.punctuation and replaced it (includes all types of whitespace).
@smci excellent points. I'll address these in the morning best I can.
@Aran-Fey Delete, I suppose. It's not even clear until OP specifies Do you want us to drop values which occur more than once, or just exclude multiple occurrences of them? Do you care about preserving the original order of the list?
08:28
regarding Unicodes though, that might be out of the problem scope since I did explicitly define punctuation to be the ASCII stuff. Extending to Unicode would only need you to modify the punctuation string as appropriate.
Either way, we're gonna need some close votes on that question
...or the regex pattern
@coldspeed You might like to compare performance to Strip special characters and punctuation from a unicode string. Also @MartijnPieters mentions "\p{P} does not include < and >; those are not classified as punctuation"
And you might like to throw in 2.x numbers.
09:23
Sup guys! Question for any PyCharm users: is there any way to use the console without opening the entire application?

If not (for anyone else), are there any IDE's that would support this?

Thank you!
09:58
What is the canonical for closing this? Why do changes to a nested dict inside dict2 affect dict1? There isn't any in sopython.com/canon
I gave up on trying to find one
Unfortunately you can't close a question as duplicate of "How do I do trivial thing X" and "How do I use my brain"; sometimes there's no choice but to explain something for the trillionth time
9 upvotes 😱
10:14
I've noticed that people are quick to downvote trivial problems, but also quick to upvote trivial problems with a slight spin on them. It's like they're incapable of understanding that it's the same thing they've already seen a hundred times
10:46
@Aran-Fey Shockingly I searched and cannot find any half-decent canonical on "Why did modifying nested list/dict 2 change the contents of list / dict 1?" Not under 'mutability' or 'shallow copy'. Can't find a good one under 'aliasing'
That happens a lot. Not finding any decent dupes, I mean.
@Aran-Fey But I don't see hardly anyone else trying to edit titles for maximal generality and clarity... why bother...
The problem with editing titles is that it can actually harm discoverability. If you have 10 duplicates with garbage titles, it's still more discoverable than 10 duplicates with the exact same title, no matter how accurate it is. That's why I tend to leave titles alone
11:01
@Aran-Fey I try to be very mindful of that. But titles like "Why isn't this working?" or "This gives an error" or "What's wrong with this code?" convey almost zero information.
Thoughts about reopening this? The dupe isn't wrong, but the problem isn't exactly the same and thus there are some more efficient solutions than sorting
And some more details and some more still
I'm Being Nice by not speaking my mind in a comment
I know, but I think English might be a problematic language for OP, just guessing.
Doesn't make the question more clear though :-p
That's not what it looks like to me
The question title is completely sound
oh yeah, forgot about that. Also, OP has 500+ rep, so they should be better at this by now.
improved question a bit, and OP already accepted the answer, so I'm more inclined to let it be.
11:45
Hello.
May someone double check the title of this old question? I'm not sure about the intended usage of a "phthon" namespace: https://stackoverflow.com/questions/28671531/importing-module-and-associated-definitions-functions-objects-into-phthon-namesp
(forgive me, link corrected)
12:01
@Cœur yes, it should be python. H & Y keys are near on standard keyboards
12:24
cbg
 
1 hour later…
13:40
eh
the more I fight with sphinx syntax the more I think that documentation syntax should be part of the language
and not compile if you get the format wrong
and "build" should always build the code and the docs
right now most languages treat is as a somewhat optional component
14:15
Cbg
Would a question like "Why do need different data types?" a fit for SO?
The answer I could think of is so that we could represent different types of data.
That'd probably be heavily downvoted
morning cabbage
@Code-Apprentice Morning, it's evening here though already.
@Aran-Fey, as I have suspected.
I have to ask, what would your answers be to "Why do we need different data types?"
I'm reviewing for my exam tomorrow in Programming Languages and that question might come up.
It's kind of like asking "Why do we need different kinds of tools? Why can't we use a hammer for everything?"
Good point.
Would "So that we could represent different types of data efficiently" be an okay answer?
14:21
most questions asked in an exam are not a good fit on SO unless they are very technical
It's a bit... well... low on useful information :P
I fully agree with Aran
"try implementing A-star with just ints"
@Aran-Fey, haha. In what way could I improve it?
the "different kinds of tools" is a very good analogy, I have no idea how to answer that question other than relatably.com/m/img/disgusted-look-memes/…
I asked my 5 year old "Suppose we have 6 dogs who each have four legs. How many legs do I have?" He says "2".
6
14:23
@piRSquared I can't think of another answer :P
give him a cookie
Honestly I can't think of a good answer to that question. I suppose you could go into detail about why different data types need different methods; for example an append method would be nonsensical on a float
Ah I see. I guess I should also include a reason as to why it is impossible or at least impractical to only one data type?
You know, like a god data type that will fit all uses and is efficient at the same time.
are you taking or designing the exam?
I am taking it.
your teacher sucks
14:25
^
but then yeah, try to explain how different problems call for different solutions
I can't even. Then again I'm a layman when it comes to CS, but I suspect this one's not my fault.
Haha. That question might not appear in the exam though so I'm just trying to fill in any gaps on my knowledge of the fundamentals.
The last time I had an exam for the same course I got the sick the night before, so I'm trying to make up with this exam.
When will they start teaching the important things, like googling and reading documentation and debugging and commenting and writing readable code?
5
hopefully that's just a decoy question that never actually gets asked live
I hope so. In the course, we get to implement our own language so that reduces the amount of coursework we have for that subject.
14:36
Implement your language using a single data type just to spite your teacher
heh
just implement a Turing machine
Ha!
We should have created an esolang instead.
If I recall correctly, the other groups were using regex to parse some of their code.
There was a post that says that you shouldn't do that.
Depends. If your programming language has a complex syntax, then regex isn't the right tool for the job. If your programming language should be fast, then regex isn't the right tool for the job. If your programming language is a toy project for school, then regex may actually be the right tool for the job.
14:43
cbg
Why must edits be at least six characters? If a person asking a question forgets to use backticks to highlight, then a worthwhile edit would only be adding the backticks and not more than two characters.
To prevent low-rep people from filling the review queue with inconsequential edits, I guess. People who submit a suggested edit just to capitalize a few words actually exist.
Sam
Sam
Anyone know if it's possible to write custom snippets for Jupyter Notebook? What I mean by snippets is, in R, I can write a block of code within some named wrapper which gets executed when I type in the name through the console.. Is there something similar for Python?
I get it, just always want to specify code blocks when they are left out
@Sam ... that sounds like a function
Sam
Sam
mm yeh the way I have described it does lol.. I think they are defined in R as a 'text macro'
14:59
So what is the difference then
Sam
Sam
The execution would be optional
so rather than a runtime thing, this is a code-writing-time thing, an IDE feature
Sam
Sam
Yeh, apologies
In R, I've been using the snippets to generate consistent header comment blocks and importing some company libs
I'd try seeing if what you want can be done with custom magics ipython.readthedocs.io/en/stable/config/custommagics.html
that's ipython but hopefully jupyter is similar
Sam
Sam
Thanks I'll have a read through now.
jpp
jpp
15:48
cbg all
 
1 hour later…
16:54
Does this question better fit as two separate questions since he's asking how to find a certain word in the source code of a web page and asking how to load websites from a text file?
My senses tell me that it should be two separate questions.
wim
wim
17:24
should comments complaining about downvotes be flagged for removal?
If anyone has a close vote to spare, the unclear question from earlier is sitting at 4/5 close votes now. Wouldn't want those to expire.
closed now
@wim eventually yes, but if it's not whiny I'd give it a day so that the downvoter may reply
wim
wim
17:43
yeah, it is whiny/sarcastic
okay, SO servers are fast for me...but JetBrains is molasses
@wim "Why the downvote?"
well, I wouldn't. If the downvoter is a nice chap, they'll respond. Otherwise, have it cleaned up tomorrow.
If I downvote without a comment, I move on and don't see any questions anyway.
18:24
Guys I have a question about creating a file tree
We're all ears
So I'm trying to use the os.path function to create a directory that I need for an Excel file to determine the amount of rows. I have a main folder and for each subfolder within the main folder, the rows = rows+1
The issue I'm having is how to nest an array to also hold the directories. Right now I can print out all the subfolders in an array and all the files within the subfolders as an array
I want to access subfolder[1 through n] and within the subfolders [file 1 - n]
I don't know how to nest the file names within the subfolders array
So the goal in the end is to count the amount of rows needed for every single subfile as a total and then use the subfolder directory to specify a row in excel and then use the subfolder files directory path to copy and paste files into excel
Sorry, but I'm completely lost. You talk about excel and directories and rows and arrays, and I have no idea how all of those are connected.
So I have a path to a main folder which contains subfolders and files within the subfolders
I want to create an array of the subfolders and files within the main folder
but I assume this is a nested array
I basically want an array with [subfolder path1, path2, ect...] and within the subfolder path is the [filepath1, filepath2, ect...]
I'm not sure how to write a nested array like that
But the issue is also trying to do this within the os.walk function
Here's what I have for code, but I need to switch the subfolders and files to a nested array somehow
SubFolders = []
Files = []
Count = -1

for (path, dirnames, filenames) in os.walk(MasterFolder):
SubFolders.extend(os.path.join(path, name)

for name in dirnames)
Files.extend(os.path.join(path, name)
for name in filenames)
print ('\n')
Count = Count + 1
print ("Rows for Excel: ", Count, "\n")
Ah shoot, I don't know how to format this
18:39
You probably want a dict, not an array. Something like {'folder': {'subfolder1': ['file1', 'file2'], 'subfolder2': ['file3']}}
Isn't the dictionary a nested array?
How can a dictionary be an array? :s
Everything on that page is blocked by my company
If your folder structure looks like this, what's the output you want to get?
folder/
    subfolder1/
        file1
        file2
    subfolder2/
        file3
@AlB The short version is "Paste your code, select it, then hit CTRL+K"
Sam
Sam
Anyone know if there's a cleaner way of getting a string containing the currently checked out branch than using the following
18:44
I want to get an array with subfolders and files of whatever location selected.
Sam
Sam
>>> print(subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "head"]))
> b'master\n'
that way when I go to my next function to develop in excel, I can loop through the elements and specify a row in excel to be a subfolder and copy the files based on these rows
So something can be selected? That's new information.
I want to copy the subfolder name to be a row and the files to be within these rows
So I imagine it would be like a nested array Masterfolder[Subfolder 1][File1] ect...
but maybe there's something I don't know that would work better
I don't think we're getting anywhere, sorry. And I've got some IRL stuff to take care of.
18:49
@Sam the only alternative I know is git branch but you'd have to parse that afterwards
Maybe its written out more like masterlist[folder1[files],folder2[files],ect...]
I'm just trying to traverse a directory and create a file tree that I can use for later
where each element in the arrays contains a directory path
Sam
Sam
@AndrasDeak Fair enough. I'll bite the bullet and strip the funky characters from it then
lunchtime cabbage
well, I might have a working dev environment by the time I go home today
Sam
Sam
@AndrasDeak Actually, converting the return type from bytes to string seemed to do the trick
subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "head"]).decode("utf-8")
wim
wim
note: you can do it directly in check_output: subprocess.check_output(args, encoding='utf-8')
Sam
Sam
19:03
Ah, even cleaner. Thanks a lot
oh, I didn't realize your question was "how do I get rid of the weird b character from the start of the string" :P
you should read about bytes vs strings in this case
[tag:cv-pls] ;)
Is it just me, or have there been a lot more 10,5 for 10.5 typo questions lately? Maybe it's worth suggesting people use a linter or code formatter, which will either complain about the 10,5 or turn it into 10, 5 (making the typo more obvious to at least people reading the question, if not to the OP)?
.. should I even respond to questions like that?
19:09
Just closing as a typo without also telling the user they wanted 10.5 probably ins't that helpful.
But doing both definitely is.
Sam
Sam
Thanks @AndrasDeak
@wwii questions like what?
so the one you cv-pls-ed, I see
Yeah, answering typos in comments is fine, we don't hate askers. It's just unnecessary to keep around in the long run.
typos are a special kind of bugs, and they are completely on topic
So for that one, off-topic typo instead of the dupe?
19:16
well if the dupe has the same typo it's fine
In the dupe the same problem is there but it's a misuse of the API. Our OP is doing both calls, so it's a legit typo. I think it doesn't really matter either way :)
FWIW I voted typo
19:42
@wwii hammered. I don't know anything about geopy, so I'll trust you that the dupe is correct :P
I hate it when people try to reimplement polymorphism in C.
I hate it even more when I have to debug it.
It's exactly why glib exists, so why reinvent the wheel, eh?
Well, yes, but this guy wrote this in a C++ file.
aka even more of a travesty
19:57
isn't polymorphism an existing thing in C++?
Yeah now I'm doubly confused
polymorphism is even a thing in yu-gi-oh. You put the result cards in a separate pile
Can someone verify @iobe's answer. I'm getting an error and wondering if it's just me stackoverflow.com/a/50454823/2336654
jpp
jpp
@piRSquared, I see AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
DSM
DSM
Works for me, np 1.14.2, mpl 2.2.2
(busy working/catching up on TV/trying to celebrate Victoria Day cabbage for all)
cabbage
20:01
@DSM, @jpp thx
Upgraded and solved
20:18
@KevinMGranger same here man.
they pooped out a solution using lines and lines of macros and static struct initialization
20:30
@OneRaynyDay Did it have any nice properties that traditional runtime polymorphism in C++ lacks?
@miradulo no. It sure did have a lot more bad properties that C++ lacks though
glib/GObject is lines and lines and lines and lines of macros, static struct initiaqlization, and void* casts. The difference is that it already works, is in use in hundreds of other projects, has a clean interface whenever you don't need to look inside the guts, and has a nice introspection facility for when you do need to look inside the guts.
oh, well that sucks :/
I had to navigate with 0 comments or documentation, and looked into the gut of the runtime dispatch and try to fish some prints out
I counted; it was about 6 levels of indirection through 3 different files
just to be sure I understand: this is a language where you just define another version of a method with a new signature and It Works, right?
20:36
@AndrasDeak what do you mean by a new signature? overloading?
isn't polymorphism the name of how different methods can behave differently in subclasses?
that's my very layman-oriented picture
more or less, yes
I'm sure it's not that simple, but from what I've seen in C++ it shouldn't involve reinventing the wheel which I guess is the point :)
Sam
Sam
20:40
I'm using the copy_tree() function docs.python.org/3.6/library/shutil.html#shutil.copytree. to copy the contents of an existing directory to a non-existing directory. For some reason (when looking at the result of the copied folder in the explorer), the dst folder seems to have a question mark appending to its name
could it be some weird trailing character? like your newline which you didn't strip off?
2 hours ago, by Sam
>>> print(subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "head"]))
> b'master\n'
@AndrasDeak Polymorphism includes other things besides just OOP overriding—C++ template-style generics, ML/Haskell-style generics, some kinds (depending on who you ask) of overloading, …
I'm afraid I'll have to google most of those :)
Sam
Sam
I mean, not in the console when I try printing the variable. Not sure if theres other way to determine that?
but thanks, I'll do that
@Sam print(repr(dirname))
20:43
shelling out to git rev-parse is probably more proper, but:
Dec 5 '16 at 16:27, by Kevin M Granger
with open('.git/HEAD') as f:
    print(f.read().split()[1])
@AndrasDeak template = you replace code during compile time, oop inheritance = you resolve instance pointer's vtable during runtime, overloading = you resolve which function to call during runtime
Sam
Sam
@AndrasDeak Oh shoot you are right
I didn't know of that function. Thanks
temporary cabbage
@OneRaynyDay I only understand overloading after that explanation :P
the "sometimes problem" with the solution for runtime polymorphism in vanilla C++ is that it relies upon inheritance. So you end up having to pass polymorphic pointers or references around (instead of getting value semantics), you usually have to allocate the polymorphic objects on the heap, things don't get inlined as well, etc.
20:45
before that I understood inheritance :D
@OneRaynyDay That definition really only applies to C++ and friends. In Python and other Smalltalk-inspired languages, there's no "vtable"; you just "send a message" and the object does whatever it wants with it.
@Sam repr is what gets printed in the interactive shell when you don't save the result of an expression to a variable
Err, overloading is only sometimes dispatched a runtime, no? Sometimes it can be statically determined
In C++ terms, overloading is never dispatched at runtime. Overriding is the thing that may be dispatched at runtime.
In Python, of course, everything is always dispatched at runtime.
ironic, seeing how pythons can't run
20:47
Yes, but they can't really compile either.
Maybe we should have constrict time vs. slither time?
These aren't differentiated statically? int foo(int a); int foo(int a, int b);
Anyway, in Python, compile time is a subset of runtime rather than a completely separate step, so…
@abarnert I only know about C/C++ :P in other languages I'm not as familiar.
so disclaimer
@KevinMGranger Yes, they are. The compiler has to pick an overload (possibly involving template specialization as well as overloads, in a complex mess of rules) at compile time.
@KevinMGranger what they do underneath the hood is they obfuscate your code, so the first foo becomes foo13243urhfweorun324or2refndosfuwebr and the second foo becomes foo234p2i3tewhifen24ern and all calls to the methods are replaced accodingly
20:49
Of course if the chosen overload happens to be a virtual method, it may also be overridden, which would mean dispatched at runtime via a vtable (unless the compiler/linker can prove through global static analysis that there are no overrides).
@OneRaynyDay But what you're saying isn't even right for C++. You described overriding as inheritance, when they're separate but related things, and then said that overloading happens at runtime, which it doesn't.
I hang out in the python room to forget about my c++ background, help
@abarnert I never described overriding as inheritance...
and yup, my bad @ overloading, I retract that statement. It's at compiletime
the code obfuscation example should make it clear that it's done during compile time, no?
(yes, and I knew it was. My background's mainly C++. I was just trying to politely challenge something I thought was incorrect ;) )
"inheritance = you resolve instance pointer's vtable during runtime". That's either not true, or misleading, depending on how you interpret it. Using the vtable at run time is what overriding, not inheritance, is about.
how does one have overriding without inheritance, though?
20:54
Inheritance is necessary for overriding, but that doesn't mean it's the same thing.
if I had to explain it exactly like how I learned it in compiler class then I would need more than one sentence, so fair if it's misleading
Better to just not explain it to anyone who doesn't care about C++, than to explain it inaccurately…
To be fair, c and c++ aren't possible to explain accurately. I think it's by design.
The only accurate explanation for non-interested people is "C++ is more complicated than you want to know about, and uses words in a way you don't want to learn."
You can write s full semantics for C, as long as you require that "undefined behavior" means "terminate"—which isn't even close to true on any real implementation, and which doesn't validate most real programs, but hey, it proves that technically, C is sound.
@KevinMGranger You can dive into C++ type erasure :P inheritance isn't the only solution, just usually the practical one.
20:57
@abarnert hey, I don't want to get in a religious war about how to teach someone something; I'm no professor, and everyone should know that, and in my opinion it's better that someone knows a eli5 than nothing, but you can agree to disagree
C++, on the other hand, I think if you gave Andrei Alexandrescu infinite time and the assistance of the gods of every major religion, they might be able to fully define it, but probably couldn't prove their definition is sound.
21:17
What's the best way to check if a variable is an iterable that can be iterated multiple times? iter(var) is not var?
that doesn't look too robust
Or should I just convert it to a list?
And see if the iterable is empty? That's what I'd naively do
I'd recommend that
Bleh. It's hard to write lazy programs in python.
21:19
How so? Why not assume it's not reusable?
The python glossary says `Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted.`
But that's not enforcable, while converting something into a list is guaranteed to work
How can I assume that it's not reusable and still be lazy? :S
work with iter(var) whatever that is
Oh, I think I misunderstood, disregard the above message.
Uh, if I work with the iterator then I definitely can't iterate twice
21:22
yes, but iterating twice is not about laziness, right?
No, not really. But it's a little difficult to combine the two. I guess I can pull something with itertools.tee
you're going to consume the input anyway if it's single-use, right? So a list seems simplest
oh, you don't want to consume it too early
yeah, I guess tee works
def nutshell(iterable):
    if any(iterable):
        iterable = map(some_func, iterable)

    return iterable
^ my problem, in a nutshell
that's a function, not a nutshell
better now? :P
21:27
now it's your nutshell in a function
ah, and the problem is that any would consume it?
There's a long thread on -ideas about defining a Reiterable ABC (which would register all builtin types, and Sequence, etc., but everything else would have to opt in explicitly), but the end consensus was that you really don't care about reiterable all that often, so nothing should be added.
@KevinMGranger Yeah.
You usually care about iterator vs. not iterator, or sequence vs. not-sequence, but it's hard to come up with an algorithm that needs to reiterate things that aren't necessarily sequences that shouldn't just be making a list or using tee.
You know, I had always said "if you're going to use tee just use a list" but I think you've found a good case for it
Using tee and iterators there may make things look a little simpler, but you're building a deque out of the iterable, under the covers, so it's not actually any simpler than just making a list.
21:29
You could optimize more for space usage by keeping track of what you've gone over yourself and then making an iterator for it that yield froms that list/deque, and then defers to the original iterator
You'd cut your space from O(N) to O(N/2) that way, assuming about half your elements are truthy. In some cases that would be worth the extra code complexity, but in general?
If almost all, or almost no, elements are truthy, though, it might be worth it.
It's a matter of principle. If I use list, my code is eager. If I use tee, it's still sort of lazy. I strive for maximum lazyness.
in this case, you're making a tradeoff of memory for CPU, almost guaranteed
But let's also remember something very important: figuring out getting it to work with tee is fun
If you're often calling the function with sequences, type-switching on isinstance(Sequence) or writing two different functions gives you re-iterability with 0 space or time cost for the common case, which is a better optimization than a clever tee that gives you N/n space cost for some n and constant but nonzero time cost.
Of course then you get the "What if I call it with a Mapping, or a KeysView, or something else that's re-iterable but not any of those ABCs?" But the core devs don't think that's a common-enough problem to worry about, and (although I disagreed at first) I think they may be right.
Is Sequence guaranteed to be iterable more than once?
21:37
Yes. It's guaranteed to iterate all of its elements each time you iterate it.
I mean, you could write something that claims to be a Sequence but lies, but consenting adults and all that.
The glossary states that a sequence is "An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence." It doesn't even mention __iter__
Well, it mentions "an iterable", which tells you it has __iter__. But the glossary doesn't really completely define most things.
I don't think it's stated rigorously anywhere that a sequence that iterates anything other than s[0], s[1], …, s[len(s)-1] is invalid, which is a much bigger gap in definition.
You could write something that has a len of 2, returns 0 for [0] and [1], returns 42 for any index other than a nonnegative int, and iterates string.ascii_lowercase the first time and reversed(string.ascii_lowercase) every time after that, and it's met all the explicit requirements of both 'sequence" and collections.abc.Sequence. But if my code breaks on your class, it's your class that's to blame.
Let's make that right now. I'll start. class Numberwang:
fair enough
So what's the recommended way to do type checks now? Should I use isinstance(..., typing.Sequence) or isinstance(..., collections.abc.Sequence)?
Trying to come up with rigorous definitions like the C++ standard might be fun. Especially since you need to allow str, bytes, and friends to be Containers.
I'm pretty sure you're still supposed to use the ABCs for runtime checks.
wim
wim
21:48
don't do type checks
Especially since the static types will lie to you—e.g., isinstance([1, 2, 'spam'], typing.Sequence[int]) is true.
wim
wim
that's TypeError
The most common case that really calls for type-switching is the ubiquitous "file object, int file handle, or string" constructor.
The only time you really come up against a need for type-switching with the collection ABCs is for mapping-or-iterable-of-pairs constructors to act like a dict.
People use int file handles?
wim
wim
I don't really like APIs that accept file objects and filenames
I prefer when it's 2 different functions
21:52
The problem is that there are already a ton of APIs that do, and sometimes consistency with existing APIs is more important than cleanliness.
wim
wim
the "I'm with stupid" school of thought
Has anyone mulled over PEP 572? I've been reading some of the mailing list discussions and am just... not sure how to feel about it.
Yeah I don't like having to guess if the string is supposed to be the contents of the file or the path to the file
What's even worse is that there are some functions in the scipy world that take a file object or a string value (like merging load and loads into a single function), instead of a file object or string filename.
wim
wim
@miradulo we disgust it already
21:53
No amount of type-switching can help there. Even better when they also take a string URL…
@wim Freudian slip there?
wim
wim
pun intended
💩
I'm surprised it still says "draft" and not "rejected" tbh
So more of a… Freudian frock? Freudian overcoat?
@KevinMGranger You still have that problem even if you have a separate function that only accepts strings and not file-like objects though
Freudian overcoat sounds alright :)
Apr 3 at 17:28, by Aran-Fey
Generally speaking, I'm a fan of languages that don't have statements because everything's an expression. 'Course, you have to trust people to be responsible with that and not write horrible code
21:56
If there's a separate function, I at least assume one takes the content and the other takes a way to find the content
Freudian one-of-those
A Freudian doctor? Wouldn't that just be Freud himself?
wim
wim
@KevinMGranger yes and the latter calls the former
@Aran-Fey Thanks! I searched up the PEP number and "assignment expressions" with no luck
wim
wim
separation of concerns and all that
21:57
@KevinMGranger The problem with a separate function is that once you have your loads that definitely takes contents, you start thinking "well then, load can take a filename unambiguously…" and someone writes the PR…
@KevinMGranger I meant what the Doctor is wearing there. But he's still pretty hard to fail to notice even without that coat.
If we had a way to do with in an expression, that would take away a lot of the desire for functions that take a filename.
00:00 - 22:0022:00 - 00:00

« first day (2774 days earlier)      last day (2399 days later) »