« first day (4302 days earlier)      last day (650 days later) » 

2:02 AM
stackoverflow.com/questions/73131462 here's a new question, separate angle on why I want to have a general "how does calling a function work?" sort of QA pair.
 
 
1 hour later…
3:08 AM
https://stackoverflow.com/questions/40273822/python2-7-selenium-using-for-loop-to-find-element

Is there a better canonical for "how do I interpolate an integer into a string?" ? The best I can find are https://stackoverflow.com/questions/25675943 (but I'm talking here about questions where OP doesn't have an approach in mind, certainly not one using `+`), and https://stackoverflow.com/questions/5082452/string-formatting-vs-format-vs-f-string-literal (but that might be too general and again it's comparing approaches from a perspective of someone who already knows some approaches).
stackoverflow.com/questions/21684926 How did this get 4 upvotes o_O
Far worse: stackoverflow.com/questions/22397261 this got 11 upvotes and no downvotes, and thousands of views - despite being a code dump with no attempt to ask a quesiton, and showing a problem that's a clear duplicate.
 
3:52 AM
Aha! Looks like the "better canonical" is stackoverflow.com/questions/2960772. Needs more attention.
 
 
1 hour later…
5:26 AM
hello
 
hi
 
how are you?
 
tired :D
 
pain, me too
what py projects you working on
 
6:12 AM
Currently, an OCR module based on google cloud vision
 
 
1 hour later…
7:18 AM
@KarlKnechtel Do we already have a category on sopython for that canonical? I couldn't find one but remember handling such questions often.
Is there a proper way to find out whether a file is opened in bytes or string mode?
 
with open(path, mode) as f: print(f.raw.mode)
dunno if that's documented etc, just discovered by exploring
oh, also f.mode which is probably better
@MisterMiyagi ^
 
ah, nice!
that should work well enough for my case
 
7:45 AM
You can also check if it's an instance of io.TextIOBase
 
8:05 AM
cbg all. Two weeks ago I asked you all for your advice, and didn't get any substantive replies (other than one comment from AD, thanks), on how to process a dataset with an irregular multiindex on the columns, and a multiindex on the rows too. Essentially a 3D datacube where the 3 dimensions are: Circuit, Nature_of_case, Status. The dataset, with screenshot, URL, and starter code, is: chat.stackoverflow.com/transcript/6?m=54926024#54926024
@JonClements I posted you the MCVE you asked me for.
I'd appreciate any suggestions. How does anybody handle a data-cube with seriously non-uniform multi-indexes, whether in pandas or otherwise? Presumably not in numpy. Do I just decide semi-arbitrarily which of the 3 dimensions is the 'highest' (presumably Circuit), then convert the cube into a dict of 2D dataframes?
 
I would go with your idea of string-merging the levels. I would probably also drop the "total"s, since they can be reconstructed easily but make the structure more complex.
Depending on what you need to do with that data, it might be worth having separate data representations for each/several query.
 
8:21 AM
@MisterMiyagi (As already mentioned the totals can and should be dropped) I don't understand what you mean by "having separate data representations for each/several query"?
 
Well, ultimately the data is there to answer some question. So depending on the question you can drop/simplify some of the structure. If you can't find one pleasant structure for all your questions, it might be worth using several structures optimised for different questions.
 
@MisterMiyagi Sorry that's too vague and generalized. Give me a specific example please; I already gave the column and row mutliindices names, the screenshots, the URL to the data, and pandas starter code so everyone here can ingest it. Also, I hate the idea of writing ad-hoc Python/pandas code, it's enough to make me quit and migrate to Spark/Scala already...
...If this dataset illustrates the limits of what pandas/numpy can/can't handle (datacubes with NAs or anything other than entirely int/float data, and/or irregular multiindices), then folks just tell me, and tell me what you use? Even SQL might be better here.
 
Sorry, I cannot give any less vague advice without any less vague idea of what you intend to do with it.
 
@MisterMiyagi As I previously said: ingest, clean and then aggregate the datacube by Circuit, Nature_of_case, Status. chat.stackoverflow.com/transcript/6?m=54926072#54926072
 
8:37 AM
Hello
 
I guess the irregular column-multiindex is the biggest pain, so I'll just blast it into flattened string abbrevations, and get on with it... then maybe revisit things on the next iteration if I achieve any more clarity.
 
8:58 AM
cdixon.org/2012/07/08/how-bundling-benefits-sellers-and-buyers I'm reading gitlabs pricing strategy and it's a great read and popped up this interesting article, fascinating. As the article mentions I also though that bundling will disappear, but they show clearly why it can benefit both parties. It's kinda a nice alternative to individualized pricing and I think most people enjoy properly bundled products
 
 
1 hour later…
10:06 AM
Nice
 
@Hakaishin I don't quite get their reasoning why it benefits buyers. It seems to run on the assumption that people want to buy the uninteresting stuff either way. Basically it's "buy two and get one free" when you only wanted one, not three.
 
10:32 AM
@MisterMiyagi Well yeah one way to put it is that people want to buy uninteresting stuff. The other way is to say that there are groups of users with different utility functions and often low utility regions of one group overlap with high utility regions of another group, thus a bundle can deliver benefit. With media and subscription services this doesn't only apply over different users but also over time with the same user
 
Does anyone have experience with pyenv being used with jupyter? We can point the kernel at the virtualenv and it works, but all new installs into that env don't. Restarting the kernel/closing the script etc. don't seem to work. I don't know if it's how pyenv handles the packages installed in a centralised fashion because virtualenv works fine
 
@MisterMiyagi Also it rests on the assumption that most users don't have 0 utility, but a very low one for a given extra feature in the bundle, which is probably a fair assumption
 
Perhaps there's a way one can get pyenv to function more like a typical virtualenv when we create the environment? Just hoping there's a handy flag on the tip of someone's fingers that I can use to get a head start at fixing this
 
@Hakaishin you might be underestimating the cost of hopping over to different tooling, especially if one assumes that the bundle is temporary and you'd get yourself locked in to a new vendor you never really meant to use.
I'm sure there are people being enticed by bundles, and even happy about them, but I wouldn't guess that this is the majority of prospective buyers (by far).
Especially in a tech field where people are more likely to at least try and be rational about buying tech. Unless it's a new gadget or whatever :P
@roganjosh NB. I haven't used either of those tools, but what does "new installs into that env" mean? Are you sure you're using the same env's install tooling? (Usual "wrong pip" problem.)
 
Good point, yeah I'm thinking more of permanent bundles, as a way to package features into one sellable product. Like gitlabs Free, Premium, Ultimate tiers. But yeah switching cost is huge I know, we just switched from bitbucket to gitlab a few months ago and it is bigger than expected, even though I expected it to be high
 
I think you guys are thinking more of physical hardwareshop style "super sale, awesome % discount" bundles. I'm talking more about the case where you have x features you can sell and you could sell them all individually or in some aggregate form
 
https://albertauyeung.github.io/2020/08/17/pyenv-jupyter.html/ might help
Sry I'm on phone and I am bad with phones
 
@AndrasDeak--СлаваУкраїні I can't actually answer that properly. A certain subset of packages seem to be installed but then it's just frozen in time. New installations into the env don't propagate through even after you restart the whole kernel
 
Sounds like pyenv isn't a virtual env, and isn't enough by itself. You end up installing to some global module.
 
From a user perspective it might not even look like a "bundle" it's just I'm buying product X(gitlab, bitbucket or whatever) but they explain nicely on their pricing page the different approaches they tried and that selling features individually was worse than to group them together: about.gitlab.com/company/pricing
 
10:40 AM
@ParitoshSingh Yeah, that's what I think is happening, something like its own global cache to reuse across envs. Unfortunately I don't think brew is going to be available to us
 
@roganjosh but that also doesn't answer how you're installing things. In jupyter? On the command line? What command?
 
pip install with the env activated
pip freeze shows that the package is indeed installed into the env, it's just inaccessible in jupyter even when it's pointing directly at the env
 
From cmd yeah?
 
Is "point directly at the env" a well-defined thing? I don't know jupyter.
 
Yeah. You can kill the kernel and there's a dropdown to pick a new environment and it'll start it up again
 
I do think it'll be pinned to how pyenv stores its libraries. I'll have to focus there. It would be fine if the workspace weren't pinned to 3.8 and the library pinned to 3.9 all for the sake of functools.cache :/ I think I'll just go blitz the library to pull that out because this isn't the first time this has caused issues and the owner is on holiday so he can't stop me :P
 
well yeah, that's not a very good reason for 3.9 alone
 
There could be other reasons I guess, but that's the only one I've actually seen when I've drifted through the repo
 
quick hack to find out:
>>> import functools
>>> functools.cache = functools.partial(functools.lru_cache, maxsize=None)
>>> functools.cache
functools.partial(<function lru_cache at 0x7f3b00f0f700>, maxsize=None)
if you temporarily patch the namespace and run it in 3.8 it will either run or point to other 3.9-only features
hmm, that won't work, hold on
You need functools.partial(functools.lru_cache, None) because the kwarg is passed positionally by @functools.cache...
or maybe it doesn't work, ugh
Final offer: functools.cache = functools.lru_cache(maxsize=None). Darned decorator factories giving me a headache so early in the morning :P
 
11:13 AM
Re: the value of bundles. I'm not too fond of them, myself, because I often have a pretty narrow and well-defined goal when I'm looking for a tool. One bundling strategy I do think is valuable: selling multiple layers of a tech stack, with the guarantee that the layers plug into one another easily and won't require tedious configuration before you can get a Hello World
 
You mean like having an editor, an interpreter, a debugger and version control handling in the same program? In an integrated environment?
 
If my goal is to display "Hello world" on any web browser when it goes to some url, I might be inclined to go with a web host that will register my domain name for me and provide server space/cpu time and set up ftp credentials for me and preinstall db software and flask and jquery for me
 
don't forget the blockchain
 
If they offer it for cheap, sure. I do want to play with distributed ledger technology at some point, so they may as well do the hard parts for me.
Meanwhile in timeline B, the Kevin that decided to get everything separately is still browsing the ICANN website, looking for a digital store where he can buy a url
 
More like ICANT, am I right?
 
11:25 AM
Yes you are right
 
11:39 AM
@AndrasDeak--СлаваУкраїні I grepped my way through. That was considerably more difficult than I thought - it was used everywhere
 
Yeah, that's why I suggested patching the functools module itself before anything gets to use it.
 
I missed it, had already started on my Odyssey :(
 
"find every line where it's used and replace it with lru_cache" would hardly be a recommendation :P
 
I mean, that's what I suggested to myself. I'm not happy about it as a suggestion, but I think it worked
 
and perhaps your IDE can refactor all those @caches automatically
*could have :P
 
11:43 AM
I don't know whether there comes a point where so much is cached that I should be wondering what's actually going on. It kinda feels like a flag for some deeper issue to see it that frequently
 
Yeah, memoization doesn't usually come about that frequently. You could try running some tasks with the library, then checking fun.cache_info() to see if there were a reasonable amount of cache hits.
hopefully nothing is cached that's supposed to be rerun :P
 
caches have bitten me so many times, I think they are the arch nemesis of every programmer
 
Misuse of tools leads to problems! More news at 6.
 
On the flip side, this is probably the most problematic project we have, so anything could go really. The data engineers just left the data ingest crashing for weeks so they were getting the truncated files I was talking about earlier; I've put an end to that. When you're hamstrung from the start I guess you might end up coding anything
I have to rewrite the whole ingest from scratch; it's also the one where I was fighting the decryption. Even just snippets of the code make my eyes bleed
newDir="./"+file.replace(".zip.pgp","")+"/"
#j=1
for item in listdir(newDir):
    print("Cleaning ",item)
    call(['python3','dataCleaner.py',newDir+item,'|'])
    print("Cleaned",item)
    print("Deleting",item)
    call(["rm",newDir+item])
    exex=item[-4:]
    newFile=newDir+item.replace(exex,"")+"Result"+exex
    print("Renaming File")
    call(["mv",newFile,newDir+item[:-13]+".txt"])
I don't know how some things ever come to pass, but that apparently happened
 
12:23 PM
@roganjosh Ugh. That looks like bash ported to Python verbatim.
call(["rm",newDir+item]) makes me shudder.
 
I'll spare you the SQL. There's one query hundreds of characters long, all on one line. I think that makes it run faster? "Perhaps if I just sort the indentation out, I'll at least be able to understand what they're trying to do". I do not understand what they are trying to do
Deduping - MD5 hash every single field... and there are still dupes. So the people in my team don't have a clue what we're being fed, and the problems just build from there. Once I get this code in the bin I will feel better
 
@roganjosh Indentation is a main gripe of non-Pythonistas, so by induction cramming everything into one line should be readable for everyone.
 
How inconsiderate of me to not think of others. Apologies :(
 
@roganjosh at least it's a proper GIGO model
 
GIGO Done Right. Love it
 
12:41 PM
@roganjosh i..have a newfound appreciation for people on my team. This...this scares me.
 
What's there to be scared of? It's been running "fine" for 4 years
 
The whole reason I was trying to effectively hack the decryption is because every semi-authorised route to try work on this resulted in "You should speak to Person X - he wrote it". I don't believe that Person X and I would collaborate very well
 
Hi all - I am writing some separate python projects that are going to have shared code. My first thought was to package my own library of this shared code - and each project could import accordingly.

However as this is still early development I will need to be debugging and building the shared code. From my initial look it seemed that debugging and updating a packaged library is not easy. Essentially I would need to repackage and update (reinstall) every time I make a change. And as for debugging I imagine I would need to setup some quasi test environment.
Any thoughts or suggestions would be much appreciated
 
Incorrect, there's installs in editable mode
 
12:52 PM
python3 -m pip install -e route/to/package. You won't look back; editable mode is great
 
^This. We've got a a similar setup of several internal projects. People usually just install them in editable mode and that's it.
 
about editable mode I just talked today about it, that it would be nice if I can switch branches with git checkout and don't have to install the package again. I use -e but the problem is that different branches needed different library versions. Is there an -e option for dependencies?
 
I'd go for separate venvs into which you -e install all the development dependencies manually.
 
awesome thanks all
will read up and try this
 
hi
 
12:59 PM
@MisterMiyagi hmm so I git checkout foo and then switch venvs. That seems the same amount of effort as calling pip install -e . after checkout
the current process uses two commands so any improvement gotta use only 1
 
Is it just me or raise syntax is unnecessarily complicated unlike assert?
Validating user input with assert is sweeter to read and maintain
But asserts are ignored when code runs with -O option
 
I like how concise assert is, too
 
I will dare to say raise is anti-pythonic ;-)
sorry: not pythonic
 
finally on a pc, no more one liner typing for me. (oh wait, this is a one liner)
there's i suppose a bit of a semantic difference in how programmers use raise vs assert
 
I still get a kick out of perl's assert/exception syntax: chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
 
1:09 PM
raise is nice because 1. it lets people calling your* code decide if they want to handle the case differently by catching it and 2. raise is still in the realm of "i think this can happen.". assert sends a soft signal to a developer that "i swear there's no way this can ever happen, but im paranoid. here, have an assert"
 
Me, to my broken program: "so you have chosen... Death"
 
Raise is 3 lines of code though, unnecessarily?
 
raise is just raise no? why 3 lines
 
Which lines do you have in mind? Keep in mind that you don't need a try-except block for every raise statement in your program.
 
sorry, 2 lines:
 
1:11 PM
oh, i get what you mean. two lines maybe?
 
if condition:
 
yeah, figured
 
raise
 
Oh, ok. Yeah, I too appreciate that assert requires fewer statements than a conditional plus a raise.
 
Why would it be that way? Different time raise and asserts were implemented? Or philosophy - make it clear this will stop the Prod code. The latter kind of removes the freedom of expression from developer's hands
 
1:13 PM
line count shouldn't become your objective goal, though. if raise is the right way to raise something then sure, just use raise, even if it means two lines instead of one. A complaint along the lines of "i wish there was a shorter syntax for raise" is then...sure, fair enough.
 
It's often simple enough to do if condition: raise whatever all on one line, but I don't like single-line if all that much. I've had bad experiences with its equivalent in .NET, one too many times.
 
Or asserts are more of technical nature hence shorter, whereas raise message are quite long, so a separate line incentivizes longer message / more info?
I do not like if condition: raise either, it does not read well
on one line
 
That might have something to do with it, sure. Ideally, an assert condition will never ever be true when your code is running in production. But uncaught exceptions might happen all the time, for any number of reasons beyond your control.
So it stands to reason that an exception message should be detailed enough that it's useful to a developer that can access the logs but can't step through the code. Assert statements, on the other hand, can be shorter since they'll only trigger when you have your full suite of debugging tools available.
 
Thanks guys, this is therapeutic
 
Simply make your code so robust and unbreakable that it never raises an exception ;-)
 
1:25 PM
haha, that's the dream every programmer "thinks" they can achieve :P
 
When my program fails, I like the catastrophe to unfold organically. There's no need for me to do if len(foo) < 3: raise ValueError("can't process foo: too small") if I'm going to be doing bar = baz + foo[2] on the next line. Let the natural IndexError shine through :-)
 
that's really good advice, if the natural error is good enough, let it bubble up as-is. In case of data validation though, especially if you're designing end points for others to consume, that's when proper error messages come in handy
 
True. And proper error subtypes would be handy too. Perhaps the consuming user would like to be able to catch all FooProcessErrors, but not all IndexErrors. Then it would be nice of me to explicitly raise a FooProcessError.
I don't often design end points for others, but when I do, I'll be sure to use the right tool for the right job
 
1:59 PM
@ParitoshSingh except: pass what's the problem? :P
 
no program, no problem!
 
no problem <-> no program
 
2:48 PM
I have a function that does something OAuth-related. It has a whole bunch of parameters like auth_url, token_exchange_url, etc. for which I could provide default values, like auth_url="https://accounts.google.com/o/oauth2/auth". The problem is that these will probably change sooner or later; some APIs already use oauth2/v2/auth for example. Is it still a good idea to provide default values even if I know they'll become wrong at some point?
Oh, and this is a library. So changing the default value means breaking backwards compat
 
If you know they'll become wrong, and that five years from now they'll always be wrong, then you shouldn't use a default.
even old version of your library won't work with the default in the future, so it's not enough to break the default on every major version
you could help users set those defaults in a config from which they get loaded
 
Now that I think about it, I'm actually not sure if they'll become invalid... If they did, wouldn't that be google breaking backwards compat?
 
Well, "won't work" and "nobody will want to use it" are different but probably close enough from a design standpoint. Assuming that's the case.
if you want a default to spare users having to pass them all the time, but the URLs can be project-dependent especially over time, a config thing might make more sense
 
Funny, today I came across one thread with answer from Andras Deak on f strings and if conditionals :-)
 
Honestly it doesn't even really matter because most users will probably download a json file that contains all of these URLs. I'm just pondering this for the sake of it
 
3:01 PM
Feels like meeting a celebrity :-)
 
@aeiou oh, I'm not very happy how that took off. My point was that avoiding the situation is best, yet people keep upvoting it presumably because they think it's "smart" or "cute".
 
A language I have to use for work (scala) has a builtin that does something like this and it's very nice
def add(p1, p2): return p1+p2
def raiseIf(funcToCall, params, assertion):
    retValue = funcToCall(*params)
    return retValue if assertion(retValue) else Exception
print(raiseIf(add, (5,5), lambda x: x==10))
print(raiseIf(add, (5,5), lambda x: x==15))
 
is there an easy way to tell if a commit is after or before another commit in git?
 
@Hakaishin that question doesn't have an answer in general, as asked
What if the two commits belong to diverging branches?
 
@Aran-Fey i've almost always regretted default values in functions i've made for others, if that's any consideration.
 
3:11 PM
Yeah I mean ofc only if they are in the same branch, otherwise tell me none
 
@ParitoshSingh That's scary. I have a lot of those ._.
(Default values, not users)
 
3:29 PM
Well, on the flip side, i haven't really designed a lot of code for others, so my sample size is small, dont worry! :P I think default values can be great for things that truly won't change, but each default value needs to be considered very very carefully.
 
3:39 PM
Bye guys, I'm again on holidays for 2 weeks. Enjoy the summer and hear you all later
 
4:14 PM
question, im trying to wrap my head around imperative code and declarative code. i read that map is an example of declarative code...but i dont understand why. isn't map also just looping over items and applying some function? how's that any different from writing the loop explicitly
 
When you use map (speaking generally not just about Python) you don't define any aspect of how map works you just declare "apply some function to everything in a list". When you define a loop you are saying to the computer "it is imperative that you do x y z"
 
@ParitoshSingh in other words, you never told it explicitly how to do that - you left it up to implementation of map. Will it multiprocess it, chunk it, do something else? Who knows! Although I'm stretching my own thought process here because I'm not sure it's a useful distinction
What difference does it make if behaviour is specified in the base language or specified in the docs of a library that you import, which has to (somewhere along the way) itself behave in a procedural way
 
yeah, i mean, to put it differently, if i wrote a loop that is able to apply a function on each item in some iterable*, made a function called "my_map" out of it, then started using that, am i being declarative all of a sudden?
 
4:29 PM
Yes, and it's turtles all the way down.
 
By whatever you're reading's standards, apparently yes
 
i...uhm...okay.
 
Get off towardsdatascience.com
 
this isnt just that site anymore, im wayyy deep in the rabbit hole, and it's clear that map filter and reduce are agreed as building blocks of "declarative" code.
 
I thought that was functional...
 
4:30 PM
Honestly, it's all wishy-washy. You automatically move from imperative towards declarative the more high-level you get
 
and functional too, sure.
Is it literally just the fact that it's abstracted?
so, declarative code is basically an abstraction on imperative code?
 
Yeah. That's my understanding, at least
 
@ParitoshSingh watch out for "declarative code in python" nonsense. Look up something that's meant to be declarative from the start, e.g. prolog
 
@ParitoshSingh I'd call map functional, not declarative. Declarative would be something like patterns (even regex) where you're giving structure and it's up to the runtime to figure out what that means.
 
@AndrasDeak--СлаваУкраїні this actually might be the root problem im running against, let me explore what prolog is
 
4:35 PM
It's probably moot unless you're using a declarative/lazy language because otherwise "implementation details" such as ordering and concurrency matter quite a lot.
 
Let me save you some time swish.swi-prolog.org/example/examples.swinb glhf
 
@Aran-Fey You might want to use a generic core API without defaults and offer a version/flavour-dependent convenience API that fills in the appropriate defaults.
Perhaps a more practical example of declarative languages/programming would be Puppet and similar configuration management suites. In Puppet, you don't say "delete this file" or "write this content", but instead say "this file is absent" or "this file has this content".
 
Or something like slf4j which can implement a number of logging frameworks, but when a dev writes logger.warn("bad stuff is happening") they don't have any way of knowing which framework is being used under the hood (unless they go look of course)
 
When you map in such a language, you don't "run code" in the sense of doing something; you merely declare new targets that the system has to achieve. For example, you would map absent onto a list of files.
 
5:12 PM
Hey guys I was hoping someone could help me with this, I am using FastAPI and SQLAlchemy to save a many to many relationship but I am getting an issue where the pre-existing child element is being inserted by SQLAlc as a new item and then erroring that the record already exists. I would expect it to update the element (or just leave it alone).

I created this pastebin which replicates the issue:
https://pastebin.com/ryNm5fVZ
 
Google's python libraries are so weird... some look like they're 1-to-1 clones of a gross Java API written by someone who has no clue about python, and then there are some that are clearly written by someone who does know python, but writes code like this
 
I was actually griping about that to a colleague recently. There are some very popular (data science) libraries out there that you'd expect to be well written, but then I look at some of the function definitions and the first thought I have is "...huh...why?" ...but I usually dismiss it as my own ignorance...
 
5:40 PM
code I have written today as part of a diplomatic compromise with a coworker: update grommets set price = 4.99 where grommet_id in (select grommet_id from grommets where color = 'red');
 
Wow, if that's the compromise I'm scared of seeing the original proposal...
 
The part in the parentheses is their half of the query, and the part outside is mine. It's very much a "draw a red line down the midpoint of the room" sitcom situation.
 
I hope you made sure to commit it from his account
 
Now, supposing the terms of our ceasefire is that I make no changes to the parenthesized text... I could adhere to that requirement, and change the outside to update grommets set price = 4.99 where color = red; --
the parenthesized text remains completely intact, just nudged off into the land of comments
[bugs bunny sawing the border of Florida and pushing it into the sea .gif]
 
 
1 hour later…
7:01 PM
@MisterMiyagi I only see sopython.com/canon/31/… and sopython.com/canon/80/…; the latter seems to duplicate the former, and it's pretty tangential and missing the opportunity for a broad topic
I have a major personal project that I expect to be working on for the next few weeks; but after that I'm thinking of doing a bunch of work on the canon since I have edit privs now
for that matter, sopython.com/canon/70/… seems to duplicate sopython.com/canon/71/… ? (I just searched for string)
@PM2Ring Thanks for the fix on stackoverflow.com/questions/6039605, I overlooked that when editing. However I think the title is not very good even with my edit. I'm not sure what to do with that
I don't think it's the kind of question that people with the problem are ever likely to find, exactly because they don't know what the problem is. I guess if they actually put in the MRE steps.... :/
but it should IMO at least have a title that is easily recognizable for dupe closers, and in general I don't like these titles that are just "why does this code give <error>" since they don't identify the relevant feature of the code
the searchable form would be something like "why can't I reuse a builtin after assigning something to that name?" but a) that makes it sound a bit dumb and b) it's broader than what was asked. (but we do use this target at least somewhat more broadly, e.g. if OP reassigned a string to input rather than str; I don't think it's getting used for e.g. reassigning a list to list)
the thing is that the question got interpreted by a lot of people, not as "what is wrong with assigning to str and then trying to use the builtin str?", but instead "what are the common causes of the listed error message?".
 
7:30 PM
stackoverflow.com/questions/73143569 surely there is a canonical?
My front-runner so far is stackoverflow.com/questions/9520075/…. That's kind of depressing.
 
I don't mind seeing error information in the title. I suspect that improves the SEO strength of the post if I paste that same error into google.
If I google "FooProcessingError: too small", the SO post with the title "why does my code give FooProcessingError?" will probably be pretty high up. A post with the title "Why can't I frobnicate my foo when it has a length of two?" may be farther down the list, even if the post body contains "FooProcessingError"
 
agreed, but that isn't the problem I'm getting at
suppose there are multiple logical causes for FooProcessingError, and the error message isn't always helpful in deducing which one
 
Very well, I have supposed it. (and I think that was even my original intention when I invented FooProcessingError this morning)
 
if we're really on the ball as debuggers, in the reassign-to-str example, we might deduce that str is the string that we're trying to call, and then see that the code assigns to str. If we somehow still have a question at this point,
then the question is about why that assignment prevents the builtin from working, and we can explain "oh, they aren't keywords or anything, but they also aren't any kind of 'privileged' names; the lookup finds the thing that you assigned, just like it would any other time"
 
It would be nice if Googling "FooProcessingError" gave you a link to "I'm seeing a FooProcessingError and I have no other information, what are some likely causes?" as well as to "I'm getting a FooProcessingError, here is my complete code, please fix my specific problem, thanks"
 
7:43 PM
in the bulk of cases, it's a logical error, but a lot of beginners won't understand why it's a logical error
well yes, that's the thing
 
The first post will have five upvotes, the second one will have five hundred. Such is the way of nature.
 
the question has been treated by many as "what are some likely causes", but people who close dupes on stack overflow will want a "why does reassignment cause a problem" target
 
Hmm, yes, there's a conflict there
 
(but yes, the problem of course is that humans are far too social of creatures; even when you select for the nerdiest, most technically oriented sliver of the population, they generally would still rather talk about their problems in a free-form way with other humans, rather than look up information and figure it out themselves. :V)
I have a few quibbles about that canonical (and doubts about my rewrite); I think I will try a meta post later
 
8:12 PM
stackoverflow.com/questions/14573021/… stumbled on a useful canonical that I am surprised doesn't get more attention.
 
8:36 PM
Hey guys I need some pandas help
I'm in a situation where I have as df with 3 columns.. I want to replace the value in col 3 with the mean of the value in col 1 and 2 given a certain condition is met (if the difference between col 1 and col 2 is less than 50% of col 1, for example)

Any idea how I might go about doing this?
 
well, can you write code that checks whether the condition is met? Can you write code that computes the mean? Can you write code that replaces the values? Where exactly do you get stuck?
 
I can do all of those things individually but connecting it to make sure the values get put into the correct spots in the third column is what I'm not sure about
 
If the problem is "I can do this for individual rows but I don't understand how to use Pandas stuff to apply it to the entire dataframe", then the trick is to modify the approach: always replace "the value in col 3", just use the original value when the condition isn't met.
Taking that approach, you can for example write a function that computes the value that column 3 should have, given the values in column 1 and column 2; and simply apply that to each row
 
so could I just loop through the third column with a for loop and use an if else statement
 
I [asked a question](https://stackoverflow.com/questions/73143910/how-do-i-find-the-line-and-column-offsets-for-imported-python-modules-with-ast) about finding line and column offsets for imports. I realized my post was actually two questions in one, as I've since figured out how to do the line offsets, but not the column offsets.

Should I edit the question to decrease the scope, then split into two different questions?
 
8:44 PM
don't loop over dataframes; the reason for using pandas (and numpy) is to let it do the looping for you
hold on, better yet: pandas.pydata.org/pandas-docs/stable/reference/api/… use this to select the rows where column 3 should be replaced
 
@Kyle think of it like two separate operations. first, calculate the mean of col 1 and col 2. no concept of condition yet. then next, make a boolean mask via the condition, and then use these results and pick which values to update using this mask
the idea is, you just calculate all mean in one go, then you just selectively update all spots you wanted to update in one go using a boolean mask
 
@Stevoisiak I'm a little surprised. I haven't looked into this, but I would have expected that either the same call gets you both offsets, or at least that getting the column offsets looks the same as the line offsets
actually, wait, hold on. why would you need or want column offsets? These are import statements, so they're the only thing on the line.
 
should I create a new column with the mean or can I compute it and update without creating a new column. sorry I am a total noob
 
@KarlKnechtel There is an attribute for column offset, but it seems to be based on where the "import" statement starts, rather than where the module is
@KarlKnechtel I'm working on a linter auto-correct rule that replaces incorrect module names
 
@Kyle create a new variable with the mean (it will be just a series, you dont have to attach it to your dataframe)
 
8:48 PM
oh, you want to find the point within the line where the module name appears?
 
@KarlKnechtel Exactly
 
@Kyle when you do the computation, you will get a series. You can either make a new column with that, or overwrite the existing column, with the same syntax.
@Stevoisiak oh. so I guess that entails, figuring out which token is the module name, and then getting a column-offset property from there
 
It looks like .node has attributes for lineno and column_offset, but the column offset is 0, meaning it's likely for the start of the import rather than the module name
Hence why I'm wondering if I should split into two questions or not
Since it would only be a partial answer
 
9:34 PM
stackoverflow.com/questions/36141153 another potentially missing canonical? I don't think this is a typo; OP genuinely didn't seem to understand the idea of instantiating the class. But I'm not even sure what the title could look like for a good canonical here
we have stackoverflow.com/questions/735975/static-methods-in-python, but I'm looking for something that addresses the case where the method shouldn't be static and OP simply doesn't understand the idea of instantiating the class (and tries to call instance methods directly on the class)
separately: should stackoverflow.com/questions/625083 be edited so that the code in the OP actually makes some kind of sense, shows a class etc.?
(for example, copying the code from the top answer)
stackoverflow.com/questions/9663562 what on earth is this question. I hate "what is the difference between X and Y" questions
 
9:51 PM
thanks guys... took me a second but I figured it out w/ your help using the masking technique
 
10:48 PM
@KarlKnechtel The title isn't great, but it's adequate. And we really don't want to change the title on a question with 880k views, especially one that's a popular dupe target.
@Karl One reason why some Python newbies have odd ideas about classes is that they're learning from a teacher who's been teaching Java for years & has only just learned Python recently themself. So they write & teach a very Java-flavoured dialect of Python.
 

« first day (4302 days earlier)      last day (650 days later) »