« first day (3196 days earlier)      last day (1755 days later) » 
00:00 - 16:0016:00 - 22:00

12:06 AM
morning cabbage
 
12:43 AM
How is recursion possible in python threading module? I want to execute "run" function again and again.
Somthing like:
    ...
    def run(self):
       self.run(self)
    ...
 
Solved!
        thread1 = BruteForce(self.data)
        thread1.start()
@ReblochonMasque I think the object/class will tell you why!
 
The object tells me nothing!
 
I'm working on my BruteForce project. So I wanted to do a recursion when the password didn't find
 
def run(self):
   self.run(self)
looked like a bad idea
 
12:56 AM
@ReblochonMasque Yes. and it didn't work.
 
surprise!
 
1:19 AM
cbg
 
1:40 AM
cbg
@holdenweb & @U10-Forward
 
Much better... :))
 
what are you trying to break into?
 
@ReblochonMasque Nothing. It's just for fun. I had made this project before but it had some bugs... I fixed them.
Pyqt5,Requests,etc
 
2:06 AM
@X4748-IR Wow you're hacking?
 
2:32 AM
@ParitoshSingh Sorry for delayed reply (i was sick past few days). However I tried to execute it but i came across trouble for step three where I have to find % difference between difference values and the threshold. This is what i did.

#Initialize date values.
 
2:44 AM
@ParitoshSingh
#Initialize date values and find difference between two columns
date_value = df.iloc[:,4:].values
np.abs(np.diff(df[date_value].values))

#Find % difference between difference between values and the threshold.
target = new_df4[['Target']].values
np.abs(np.diff(df.iloc[:,4:].values)) > target

See i believe that finding % difference between difference values is wrong here, because i am finding values that are greater than target. I request you, Could you please assist me on what i should be doing?.
 
2:58 AM
recbg
 
3:34 AM
@ReblochonMasque Me too. I was under the impression that all class instances should be self starters.
 
3:54 AM
cbg
 
recbg
eh @piRSquared ? not sure what you are referring to?
cbg @anky_91
 
4:20 AM
Your surprise comment was in reference to a class method that ran itself (self starter) /shrug (-: @ReblochonMasque
 
ah, okay, thank you @piRSquared
using a tuple, an array, or a list to represent a Vector is hurting my sense of geomtric purity!
 
 
2 hours later…
6:44 AM
cbg, I am really confused by this question stackoverflow.com/questions/57056029/… and would love to have some input.
Quick context: From the issue discussion/comments/test-code it seems like InitVars and ClassVars are somehow similar, and I just don't get why. Of course a ClassVar doesn't need a factory, since there is only one. But there is one InitVar per instance, so why would it make no sense to have a factory there? You can call it in __init__, and I don't see how it could go wrong.
 
recbg
 
hello
 
Hi @BálintCséfalvay
 
6:59 AM
I'm just learning Python. But I made a small game I uploaded it to pygame, but I'm still working on it.
https://www.pygame.org/project/4110
What do you think about it?
 
7:30 AM
90 % towards mugging :P
 
7:58 AM
Is assigning a result of a list operation to it's own slice an inplace operation? For example if I want to reverse only the latter half of a list, will this be considered inplace?
In [72]: lst = [1,2,3,4,5,6]

In [73]: lst[3:] = lst[3:][::-1]

In [74]: lst
Out[74]: [1, 2, 3, 6, 5, 4]
since I am not creating an extra list, and updating the older list itself
 
@DeveshKumarSingh you have your answer
 
Well, lst[3:] and [::-1] are still creating extra lists
 
right, I was going to add that it depends on one's notion of in-place
 
Ohh okay, so those are being created implicitly by the operations, but are not visible explicitly to a user
 
they are explicitly visible as lst[3:] and lst[3:][::-1] :P
 
8:02 AM
I am preparing for interviews, and lot of questions ask for in-place, or O(1) space solution, so I was wondering if this approach will be considered as such
 
but the moment you reassign to lst[3:] these lists are gone
@DeveshKumarSingh in such a situation I'd ask for clarification
if in-place == O(1) space then no, it's not in-place
 
so this is in-place but not O(1) right
 
???
 
I mean the example I provided is in-place but not O(1) space?
 
depends on your (or your interviewer's) definition of "in-place"
 
8:05 AM
we just covered ^ that
and I literally said "if in-place == O(1) space ..." which suggests that this is one possible interpretation
off the top of my head I'd have called it in-place because you end up with a mutated original list, but Aran's remark and your O(1) thing suggests that this is probably wrong
3 mins ago, by Andras Deak
@DeveshKumarSingh in such a situation I'd ask for clarification
 
yes, therein lies my confusion, and yes asking for clarification is better I guess
 
instead of trying to shoehorn concepts into vague categories again, try to come up with exact categories
 
so those exact categories will depend on the interviewer interpretation if he asks to solve in a particular approach
my question was more towards websites like leetcode, and when they use such terms, how to interpret those
 
I'm guessing in that context it means "update the original list rather than creating/returning a new one"
 
@DeveshKumarSingh try with the easier one, and if it fails due to memory implement the harder one. They are probably sloppy and just want you to mutate
 
8:11 AM
Yes, the easier one works with mutation, for example this one works with mutation
s[:] = s[::-1]
 
there's no O(1)-space solution for reversing strings in python
 
> Write a function that reverses a string. The input string is given as an array of characters char[]
^ weird definition of "string" haha
 
actually, char[] arrays would be doable with a bytearray :)
 
how about this solution
def reverseString(s):
    """
    Do not return anything, modify s in-place instead.
    """
    i = 0
    j = len(s) - 1
    while i <= j:

        s[j], s[i] = s[i], s[j]
        i += 1
        j -= 1
 
try and see what happens
 
8:16 AM
that challenge is actually very specific: "with O(1) extra memory"
 
assuming s is a list of characters, which the question specifies and not a string
 
@Aran-Fey nice, it's rigged against python
@DeveshKumarSingh then yeah
 
@AndrasDeak okay then it's O(1) space, but how different is it to s[:] = s[::-1] ?
 
it's n-1 less
 
In my understanding, both are same
 
8:18 AM
no, we explicitly covered earlier that list slicing creates copies
 
I wonder if s[:] = reversed(s) would be O(1). Probably not.
 
that's what I'm thinking, I thought probably yes
 
okay so it is creating a copy, it's just that the copy is short lived since the copy is assigned back to the original list?
 
the point of reversed iterators should be that when you have a reiterable you probably don't have to store it in memory
@DeveshKumarSingh yes, as we've explicitly covered it earlier
short lived because there will be no references to the copy after the assignment
 
8:20 AM
@AndrasDeak Yeah, but I'm thinking the slice assignment is probably converting it to a list internally because it (probably) wants to know how many elements you're assigning
 
static PyObject *
list___reversed___impl(PyListObject *self)
/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
{
    listreviterobject *it;

    it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
    if (it == NULL)
        return NULL;
    assert(PyList_Check(self));
    it->it_index = PyList_GET_SIZE(self) - 1;
    Py_INCREF(self);
    it->it_seq = self;
    PyObject_GC_Track(it);
    return (PyObject *)it;
}
@DeveshKumarSingh indeed
listreviterobject, smooth
listreviter_next looks good github.com/python/cpython/blob/…
 
@AndrasDeak got it, it is such questions I will probably get stumped with in interviews, but thanks for the clarification
 
if (index>=0 && index < PyList_GET_SIZE(seq)) {
    item = PyList_GET_ITEM(seq, index);
    it->it_index--;
    Py_INCREF(item);
    return item;
}
 
So am I correct in assuming that using list slicing by assigning back to a slice is using extra space, albeit temporarily so it's not O(1) space in true sense in terms of the whole function?
or even this is upto the interpretation of the question and the interviewer?
 
there's only one sense of O(1) space, and it's not
The interpretation only applies to vague notions such as "in-place". O(1) time or space complexity is exact.
Think of it like this: O(1) time means that if your list occupies 90% of your memory you'll probably be able to do the operation anyway. O(n) means you can't.
 
8:25 AM
got it, where O(1) space is in reference to the size of the input, making copies by using say list slicing anywhere in the function makes in O(n) space complexity
 
now what I just said is not exact, just a hint of how you might think about the difference
@DeveshKumarSingh if you create a list with size m then you get a memory hit of m. If m scales with n then you are in trouble. If m doesn't scale with n but you create the m-sized list k times, where k scales with n, you again have O(n).
 
are we using space and memory interchangeably here?
 
To be exact, you have to count the total memory need (in whatever units) of your algorithm, and look at the end result and see how it behaves for large n as a function of n, where n is the characteristic size of your input.
@DeveshKumarSingh I am
 
aah okay, I was confused for a moment there
 
What else could space mean?
 
8:29 AM
Now that i think about it, the program is loaded onto memory and executed there, so the space actually refers to the memory usage of the system
 
9:11 AM
^ closed
 
9:21 AM
Reading your comments, this isn't O(1) in space?
s = ["h","e","l","l","o"]
s[::-1] = s
I always thought it is
 
that's an obtuse way of doing s = s[::-1] or are the two different ways of achieving the same thing?
 
isn't s = s[::-1] version creating new variable?
 
new variable? no. new list? yes.
 
Yes, I mean new list...
But s[::-1] = s isn't creating anything new. Or it is?
 
interesting, i wasn't aware that we could pass a step size on the lhs, never tried it before. slicing lists on rhs will create a copy, so that's occupying some space. that notation on the lhs, i'd imagine is not using any extra memory. i don't know for sure yet though
 
9:27 AM
I think it is also creating a new list and assigns it to the new name s
 
@ParitoshSingh list_ass_slice strikes again
 
heh, indeed
 
    if (a == b) {
        /* Special case "a[i:j] = a" -- copy b first */
        v = list_slice(b, 0, Py_SIZE(b));
        if (v == NULL)
            return result;
        result = list_ass_slice(a, ilow, ihigh, v);
        Py_DECREF(v);
        return result;
    }
so good catch, but it has to copy otherwise the list would get mangled
 
okay so we have a special check to achieve s[::-1] = s in cpython
 
Otherwise you'd run into trouble while mutating the list item by item. In any other case you don't have to do this, you can even put generators on the right-hand side and they'd be consumed item by item I think
 
9:32 AM
i dont understand what a and b refer to here
 
The left- and right-hand operands. In general, a[i:j] = b
/* a[ilow:ihigh] = v if v != NULL.
 * del a[ilow:ihigh] if v == NULL.
 *
 * Special speed gimmick:  when v is NULL and ihigh - ilow <= 8, it's
 * guaranteed the call cannot fail.
 */
#define b ((PyListObject *)v)
 
So s[::-1] = iter(s) is catched by this special case too?
 
Probably? I don't know.
 
But this won't work since the size of the LHS slice is fixed
s[::-1] = s + s[::-1]
 
"won't work"?
s[::-1] is a new list and s + ... is especially a new list
 
9:38 AM
In [135]: s = list('hello')

In [136]: s[::-1] = s + s[::-1]
ValueError: attempt to assign sequence of size 10 to extended slice of size 5
 
@AndrejKesely if I had to guess, (PyListObject *)v will turn your listiter back into the list
 
@AndrasDeak yes makes sense, hence the sizes don't match up for the slice assignment which I suppose means that the size of LHS is calculated before the slice assignment
 
but that's really just a guess
 
@AndrasDeak This works too s[::-1] = iter(lambda i=iter(s): next(i), None) Its some black magic
 
I keep forgetting the two-arg form of iter
@AndrejKesely no idea
 
9:49 AM
Should I open question on SO? Maybe someone will know
 
The regulars here might know too
 
10:18 AM
v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Any chance that this consumes iterables?
In which case there could only be problems with sequence-like views of lists, which probably don't exist
But this would also mean that lst[:] = map_object will create a sequence for the right-hand side
 
according docs.python.org/3/c-api/sequence.html#c.PySequence_Fast it creates new list from iterable, or returns the same tuple/list.
So yeah, it's creating temporary list on rhs and then assigns to slice, if i understand correctly
 
it would seem so
 
It must create some temporary variable, it's not possible without it
 
I guess this is the only way to guarantee that no surprising things happen with complicated backreferences
 
10:36 AM
n/m
 
10:54 AM
lst = ["h","e","l","l","o"]
for i in range(len(lst) // 2):
    lst[i], lst[len(lst)-i-1] = lst[len(lst)-i-1], lst[i]
print(lst)
Should be O(1), no?
In space i mean
 
Yes
although it creates O(n) 2-tuples :P
 
for when some_string[::-1] just isn't good enough though :)
 
11:08 AM
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
Ummm.... interesting template to start with...
 
teaching people how to write bad code, as many of these websites tend to do
 
@Aran-Fey well it is called "leetcode", after all
 
hehe... and they didn't even spell l33t properly either :p
 
11:57 AM
laurel, I am preparing to give interviews, and the website provide me good interview questions, but with a grain of salt
 
just a grain? :p
some of those sites need an entire mine :)
 
Question: is it allowed to post a lmgtfy link as comment? Since I see questions if I copy and paste their question in google, it's the tophit.
 
cabbage
 
@Erfan You can do it (unless they've since tightened restrictions on that link), but it's likely to be deleted and you could be flagged as being rude
 
@JonClements, did you say you would recontact those that answered your call for volunteers for the psf job listings?
 
12:05 PM
As frustrating as the tag can become, you'll gain nothing from posting that link. It's better just to leave the question feed if you're getting frustrated
 
@Erfan it'll just get deleted and make you look like a twat - so best you don't...
 
Thanks, makes sense. I was just frustrated couple minutes ago, because I literally saw 6 questions in a row which were tophit at google. Now I have common sense again, I will probably never post that link. @roganjosh
 
@ReblochonMasque umm.... been a little while since I've focused on that... care to give me a run down?
 
about 2 weeks ago, you asked for volunteers to review the job postings on the psf jobs board; I stepped forward, and you replied that you had a few things to tie up first, and would come back to us.
You don't remember?
 
no I do, and we had a meeting and on-boarding session as it were, it's my bad if you weren't sent an invite :(
spinning too many plates...
if you're still interested though, there's definitely room to welcome you :)
 
12:20 PM
cbg
 
haha, okay, no worries, this happens. Yes, if you still need help, I'd be happy to.
 
For those who saw my questions about pulling data from a Flask server that was providing data using stream_with_context, I came up with the approach for the client side using requests.
You can use a vanilla requests.get() call, and you will pretty much skip all the streaming aspects - requests will get() repeatedly until all the data has been streamed, and then the client proceeds as normal.
 
Presumably then, if you didn't use stream_with_context then the second request onward would lose things like the fact that you're logged in?
 
But if you want the client to stream also, then:
1. call requests.get with stream=True
2. repeatedly call resp.iter_lines or resp.iter_content to get the stream in chunks (where resp is the response returned from requests.get)
iter_content uses a default chunk_size of 1, so if you don't set this, performance will be, um, poor. iter_lines uses a default chunk_size of 512, but delivers data line by line.
@roganjosh No, it's just that the server has to build one big response first, instead of yielding a bit at a time.
There is still just one call to GET
At least as far as the client code and server code are concerned - may be more going on under the covers. I may delve a little further today with packet capture and Wireshark to see.
 
Ok, so my take-home from that is that it's functionally similar to the article I linked to about streaming content in chunks
Whether or not it's more/less efficient or one/the other method didn't exist at the time of writing, I don't know, though
 
12:30 PM
@PaulMcG could get complex where flask has not bothered streaming but the front-end web server allows it/caching it
 
Actually, I wonder if the caching side is significant because perhaps some account needs to be made re: nginx etc.
 
I don't think I've ever used streaming in production
(at least on the back-end framework side)
 
I haven't either, but twice this stream_with_context method has piqued my interest :)
I'll put that to one side, there's now a sparrow in my house. Forget the bees. God's sake
 
It's just generally more constructive to have stuff return asap and have the client connected to a server side only websocket and then push to that instead
(for web pages at least... ymmv on other things)
 
Disaster over, caught it in a tea towel :)
 
12:40 PM
You're moving up in annoyances it seems... are you working yourself up to an escaped polar bear in a year/two :p
 
I certainly hope not! I keep the back door open because my house tends to get the sun on the bricks all day. I've tried draping a duvet cover over to keep things out but the poor thing found its way in anyway. Its mates were on the outside of the window trying to break it out; thankfully easy enough to catch and free
 
good news then
one flat I used to live in, because of where it was, every bloody time we had the windows cleaned, you could almost guarantee a bird would fly into it and break their neck :(
 
Oh :( Well, there's a simple solution to that :)
My laissez faire approach to sorting out the garden is probably causing some of these issues, but it would have worked wonders on your window problem!
 
which obviously wasn't desirable... what was even less so, was when you want out to the garden and they were still twitching :*(
 
Gosh. I've seen birds hit windows before but not with that kind of force. What a shame
 
12:52 PM
Could anyone tell me how to find the anaconda cloud link to the re module? The one you use as import re... re.sub(...). I can only find regex there
or is this a silly question?
 
I guess it depends on how far through the room they can see. Perhaps the ones that I have seen, only intended to land on the windowsill on the inside of the window, not go significantly through the house
@Sosi it's part of the standard library so you should already have it
 
@roganjosh maybe we just had too good of a window cleaner :)
 
Something for the cleaner's business card :P
 
1:05 PM
As I said above, I'll be happy to help if you need my help @JonClements - what is the next step?
OTOH, I don't have to, so you should not feel obligated, it is all cool and good.
 
thanks @roganjosh
 
1:21 PM
@ReblochonMasque give us a "hi" to jobs@python.org and we'll say hi back to ya :)
bloomin' heck - listening to some music on random - I'd completely forgotten that "Gorilliaz" were a thing
 
@Reblochon thanks... so sorry for my oversight... getting an old puppy these days it seems :)
 
1:43 PM
So no new tricks for you
 
"Can't teach an old dog new tricks"
 
oh, you can still teach an old puppy new tricks though :)
sorry - mind blanked for a moment
 
Trivia for anyone who might not have seen the news today - any guesses on the most-played song of 21st Century (on radio)?
 
gotta be despacito
 
1:52 PM
Nope. Though I would bet that wins on YouTube (note the caveat at the end - on radio)
 
umm...
so tempted to look and cheat :(
can you give a clue of the decade?
 
radio? isn't that those black boxes with tiny singing people inside?
 
Bah! Tonight is quiz night for me - no cheating :P
 
Gangnam Style? :P
 
Nope
@JonClements I'll do better - 2006
 
1:54 PM
wow
okay, then, what was really big in 2006?
 
Ha, that's pushing it a bit with clues :P
 
although it didn't need to be really big then, just until now
 
It was big, though you're correct that it didn't actually top the charts here (IIRC)
 
band/single artist?
 
Not sure what you're asking - isn't that the answer?
 
1:56 PM
was it a band or a single artist?
 
A band with multiple albums
 
but someone that never reached 1 here!?
2006 was a while back... ummm
 
No, I was referring to that particular single, but let me check I have my facts straight 1 sec now
The song's highest rank in the UK looks to be 6th
 
ummm okay
2006 - I'm tempted to take a punt at Coldplay
 
^ that's what I thought too
but I checked, and viva la vida was 2007
and that was their biggest one, no?
 
2:02 PM
but they had tracks like "yellow" and "the scientist" before that
 
(waiting for roganjosh...)
 
Not sure whether that was the biggest for Coldplay, but this song wasn't by them
Another clue?
 
was it a cover song or original?
 
Original
 
"engineered"/natural group?
 
2:04 PM
It's a love song that features automobiles quite a bit
 
gasolina - daddy yankee
:p
 
Ahaha
I wanna give you that answer just for the chuckle it's given me :P
 
nope
not yet
was it new that year?
 
Shall I put you out of your misery or try think of another clue?
 
I'm checking out Azure Notebooks... I might like it better than google colab
 
2:06 PM
Azure is pretty impressive
 
Unpacking a set into return for a multiple variable
python 2 please, anyone?
 
ughghghgh... struggling now @roganjosh - was it an all girl/boy group ?
 
@JonClements male group
 
ugh male groups in 2006... ughghgh
 
Seems the oldest songs I can think of are from 2010-11... jeez, 2006 was a long time ago
 
2:10 PM
link to quiz question
 
Actually, I'm pretty sure you'll know the song, Aran-Fey, and will probably be shocked that it comes from 2006
19 mins ago, by roganjosh
Trivia for anyone who might not have seen the news today - any guesses on the most-played song of 21st Century (on radio)?
 
@AlperAyna Not sure what that means. Returning multiple values is usually done with tuples, so are you asking how to convert a set to a tuple...?
 
Our House - Madness?
 
if you'd have said female group, then I'd have taken a punt at it being pussy cat dolls or something, or were they '05 or '07 - I don't know
 
Nope
 
2:11 PM
(-:
 
@Aran-Fey I might be false to set a set instead tuple
 
@piRSquared that was 80's :)
 
@AlperAyna like a, b, c = {1, 2, 3}?
I'm trying to think what you're asking. Is that along the right lines?
 
@roganjosh nope, I'm giving up I think... without looking it up I'm completely out of ideas
 
Snow Patrol - Chasing Cars
 
2:13 PM
no way
 
seriously?
 
Guess I was doomed from the start - never heard of that song in my life
 
Sorry, wrong example
 
Seriously. I was reading about it this morning and was shocked myself
 
I quite like Leona Lewis's version of that one :)
 
2:15 PM
Pretty much the only Leona Lewis song I know is Bleeding Love which is great to just belt out on an open road on a road trip :)
 
it's the fifth result on google if I enter "youtube snow patrol". they have 4 other songs that are more googled.
 
I actually prefer Set the Fire to the Third Bar (though I don't understand the title). But yeah, apparently it's Chasing Cars
 
@roganjosh music.youtube.com/… is also nice :)
@roganjosh and music.youtube.com/… was really popluar
 
Ah, this is true. I guess my mind gets overpowered by "Bleeding Love" when I hear her name, but I know those songs and their lyrics
 
and I absolutely loved "Better In Time"... but that's maybe just me
 
2:19 PM
whoa! wait! what is that?! Most played on what radio? All radio stations? Or one guys radio?
ooooohhhh, in the UK!
 
@piRSquared But now I've gone back to find the proof that's an important distinction that I should have made. That's my bad, sorry. I think I overstated the fact in my head
 
I know that song though... It's a good song
I didn't know the name but I've heard it all over the place
 
@piRSquared WELL how does it feel?? :P
 
Sticky
 
@JonClements I doubt you missed it, but that song was used at the end of Kodi Lee's performance on America's Got Talent, which is something of a tear-jerker
 
2:28 PM
wowsers, so if the beeb ran the stats, I'll accept that, I'm still surprised though
wonder what the most played song ever is though
 
I would assume that will exceed the scope of our records. It's probably a best-guess, I'd probably either go for a Beatles song or something like Slade - Merry Christmas
 
@roganjosh now I've done a little bit of research, officialcharts.com/charts/singles-chart/20060101/7501 is quite interesting
@roganjosh yeah, probably Beatles or a popular American Country singer or an xmas or "gift aid" kind of song would be my guess
 
Old xmas songs that are popular are at least gonna keep cropping up over the years, maybe "do they know it's Christmas" is the best of the bunch
 
cbg
 
cbg
 
2:44 PM
Is it a good idea to do try/except for every use of requests?
 
That depends on what you're trying to do
 
I'm trying to send a request I guess
 
What exception are you expecting?
 
It's a good idea to use try/except whenever you think an exception might occur and you want something to happen other than "crash the program"
 
In some cases where it is viable that a 404 may be returned (by design) there I use it but in other cases do I make it except requests.exceptions.RequestException which is where all exceptions inherit from
 
2:46 PM
If you're going to wrap every request in your own try/except then you should consider a function that does this for you, instead of repeating the same construct over and over.
That is, if your handling of the exception is the same every time
 
I mean it could be that the person who's using it has their internet connection error or maybe the backend is being updated or something
 
Ok, and what do you want to happen in those cases?
 
@aadibajpai handle requests if you know how to handle them. Otherwise, don't.
 
@aadibajpai do you mean you want your server not to crash?
 
It wouldn't look neat if the program straight up crashes I guess, so maybe catch the exception and print it before exiting?
@Arne No, I'm talking about the client-side application
 
2:48 PM
Should the exception be crashing the program at all?
 
"print the exception and then exit" is what uncaught exceptions already do :-P
 
Can we have some context here?
 
It should show the error and exit I believe
Um, yeah basically downloading and displaying some data.
 
^ That's not particularly helpful.
 
I'm tempted to recommend putting your entire program inside a single try-except whose except block prints the error in an aesthetically pleasing way.
No need to wrap each request individually if all errors should be displayed in a consistent manner
 
2:51 PM
If downloading "some data" doesn't work, why should it just crash your program and leave the user with a Python error/traceback?
 
def main():
    #whole program goes here

try:
    main()
except Exception as e:
    print(e)
    log_error(e)
If you don't print the stack trace I strongly recommend saving it somewhere because you're not doing anybody any favors by discarding diagnostic information
 
@roganjosh I'm not sure how to explain but it's one request if everything goes okay and a series of them if it doesn't. For example say you do a GET request against an english dictionary with a string. If it is a word you get a 200, if not, the program then queries a backend server as a fallback and if it is not found even then, it opens a github issue on the repository.
 
So the API expects single word searches. Why would you promote invalid input to a github issue?
You can filter out multi-word inputs to your server and just send back a signal that the input is not valid
That doesn't even have to be an exception; the API input doesn't pass your tests, so you tell the client that and just reject it. You don't crash your server
 
I think there are three categories of input here. Words such as "coconut", which return a 200 response; word-like input that isn't in the dictionary, such as "florby"; and invalid input such as "123 x \r %^#$%&\0".
 
And if you're the one that's sending the request, then this is also an easy-enough situation to handle because you can catch the invalid input prior to making the request in a huge majority of cases, and pass the error back to the user if it fails
 
3:02 PM
"You don't crash your sever". Wait, I think I missed something. Who said that input could make the server crash?
The server returns either 200 or 404 and in either case keeps on trucking
 
14 mins ago, by aadibajpai
It wouldn't look neat if the program straight up crashes I guess, so maybe catch the exception and print it before exiting?
 
14 mins ago, by aadibajpai
@Arne No, I'm talking about the client-side application
 
I have taken that to mean that it should crash with an error, but the context suggests that this isn't the case
The server just shouldn't be exiting
 
Anyway, this is all incidental to the point I was making. Exception handling is not magic and it can not be used as a substitute for clear design requirements. If you don't know what kind of errors you want to catch, and you don't know what you want to do when you catch an error, then don't bother writing an exception handler.
 
@aadibajpai who's your target audience with the app? this sounds like it is technical people who can stomach seeing a traceback. If it is non-technical people, convert the error to a nice error message.
 
3:11 PM
Don't handle exceptions just because you feel like you "should". In the worst case it makes your program more buggy and actively impedes debugging
 
3:28 PM
The dictionary thing was just a simplified example. When I say crash what I mean is that the client runs the script and it fails with the requests error which isn't handled.
@MisterMiyagi Nope, end users just need to have python installed.
So for example the whole ConnectionError message when there's an internet problem may be confusing to a person who's not experienced with that. In that case I'd want to output something like check your internet or so.
Whereas if there's an HTTPError the first time then the script would know it should query the backend since the appropriate response wasn't received
@Kevin This was what I was confused about mainly, like in the above cases I have an idea what I want to do. However I wasn't sure if every requests call should have a general try/except or no.
404 Client Error: NOT FOUND for url: httpbin.org/status/404
might be more preferable than
Traceback (most recent call last):
  File "C:/Users/aadibajpai/.PyCharm2018.2/config/scratches/scratch.py", line 5, in <module>
    bad_r.raise_for_status()
  File "C:\Users\aadibajpai\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 940, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND for url: httpbin.org/status/404
for the end user.
 
You don't have to have a try/except; it's only throwing an exception because you called raise_for_status()
You can also just look at the status as well
I can't remember what happens if it can't connect, but that may throw an exception
 
@RobertGrant it gives a ConnectionError
 
00:00 - 16:0016:00 - 22:00

« first day (3196 days earlier)      last day (1755 days later) »