« first day (4268 days earlier)      last day (674 days later) » 

7:15 AM
Here's another mess that needs cleanup: duckduckgo.com/…
 
And the mess is...?
 
there are a lot of questions in need of closure and a canonical
 
Ah, my bad. I clicked your link before the edit got submitted.
 
the problem in the code is caused by a typo, but the question is about Pycharm behaviour.
yeah, I had a problem with URL escaping, so the search results weren't limited to Stack Overflow.
 
I don't really see the legitimate question about PyCharm behavior, though. Those all just seem like typo questions.
 
7:19 AM
there is a useful underlying question, but all of these questions come from idiomatic debugging requests, and thus lack a MCVE (emphasis on M)
I would rather be able to point people at an authoritative source that says: 1) this is not an actual Python error, but a Pycharm diagnostic; 2) you get the diagnostic because of (what the message says - detailed explanation, because people can't read); 3) here are the most common causes and what the most likely correct code is

rather than having to wait for two more votes and also leave a comment pointing at the line of code in question and writing out the relevant information
 
That's fair. Closing as a duplicate is much more expedient and useful than closing as a typo.
I'd offer to hammer multiple pages of dupes against a canonical once you have one, but I assume you can do that already yourself?
 
but infinitely more important than that: I would like that when someone puts in that search query (which is an entirely reasonable one if someone encounters the problem, and exactly the kind of searching that we should be a) encouraging, per meta.stackoverflow.com/questions/261592 and b) facilitating, per the site mandate), that said person actually gets a good result.
I do have the hammer, yes
(generally when I come in here pointing out a problem like this, it is more about discussion; if I actually thought it was a problem needing mod assistance, I would explicitly say so)
 
You mean you wouldn't just post a random message and hope a mod happened to look in the room at that very moment?
Where is the fun in that, Karl?
 
:V
(specifically, I am looking for input regarding: 1) did I manage to overlook a reasonably good canonical candidate? 2) if I/someone else creates one, what needs to be in it?)
and I'd rather ask it while the idea is fresh, than wait until there are people paying attention to the chat
 
Not aware of a good duplicate for these.
If you want to make a canonical, I think it would be fine to list the PyCharm error and a few examples. As far as I can tell, there are basically typos (== instead of =) or not using print/assignment because people are used to the REPL behaviour. Those cases still seem reasonably focused, since they boil down to "don't throw away results".
 
7:50 AM
ah yes of course, I hadn't considered the "evaluate expression and don't print it, because REPL" case
I guess if there's a single question to extract, it's something like "what sorts of code cause this message, and why?"
 
user17416440
how I can unrar a rar file in python (Jupyter lab)
 
@Zaif Did you try searching Google? I typed your query (minus the parenthetical) into Google, and I got this question as the first result.
 
user17416440
PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z),
 
user17416440
getting this error with the code in the link
 
Yes, that's what one of the comments underneath the answer says, too. Apparently, to use that specific tool, you need to have an existing piece of software installed that supports extracting RAR files, like 7-Zip. This software is free, but probably not convenient to install in an online container. Did you try the other answers?
 
8:00 AM
i suppose thats an important point to make, it's not just about blindly copying the top answer, the comments and other answers can contain useful information too. for example, you would have already seen that the error you got is already mentioned on that post and explained
 
Additional Googling can also be useful: stackoverflow.com/q/50315989
(Anyone know why a question about Google Colab would be tagged [ubuntu]?)
 
it shouldn't be, and I removed it
a lot of people use tags to describe the environment in which they are trying to solve the problem, even when it clearly shouldn't have anything to do with the question. it's help desk/tech support mentality; they're accustomed to being asked for these details if not provided,
"So far I have tried installing python libraries and also ubuntu packages like "unrar ,rar ,unrar-free ,unar ,unp"" is presumably the part that prompted OP to tag that way.
 
Even at a Help Desk, you wouldn't tell them that you're running Ubuntu when you're using a fully web-based service.
I did also think it was odd they mentioned installing Ubuntu packages when they're using a web service.
Is there such thing as a locally-hosted instance of Google Colab?
 
I don't think so, but using it apparently does involve "installing" stuff... on the remote side I guess?
judging by the answers, anyway.
I have a pretty fuzzy mental model of what Colab actually is
 
8:12 AM
"A service that Google will probably cancel soon" is all I know
 
They will? Huh.
@KarlKnechtel it's more or less a jupyter notebook hosted by google
 
@AndrasDeak--СлаваУкраїні I don't have any specific insider knowledge. I'm just going based on larger trends where Google cancels all of the useful services eventually.
 
I'm sorry that my cynicism was confusing. :-)
@AndrasDeak--СлаваУкраїні Yes, that helps a lot. Now, the statement can be amended to: "I have a pretty fuzzy mental model of what Jupyter actually is"
 
well for all I know Karl could have come across notebooks
 
8:40 AM
Can we call functions/methods by assigning dictionary to choices in argparse
parser.add_argument('-t',help='Pass test command to run',choices=testHandlers)
 
choices is only used for verifying the argument; effectively, argparse makes an if argument not in choices: raise ArgumentError check.
In order to select and call the function, you would have to fetch it from the dict yourself.
Note that if you want to convert the argument directly, then type=... is the correct thing to use. For example, type=testHandlers.__getitem__ should work in your case.
Defining several subcommands with appropriate action might match your usecase as well.
 
9:39 AM
Today I had to convince someone that f = lambda: x holds a reference to x
Wonder what they thought would happen if x was garbage collected. Would it throw an UnboundLocalError? Would the interpreter crash?
 
Nasal Demons fixes everything!
 
 
2 hours later…
12:07 PM
@AndrasDeak--СлаваУкраїні Very nice. When OP comes back in another five years, I'm sure he'll be pleased.
 
12:33 PM
Cbg
Is there a way to mark run unittests as skipped? I have tests which depend on external resources and I want to run them and then when I get an exception like resource not available to mark the test as skipped(resource wasn't available)
 
If you're using pytest you can just catch the exception and call pytest.skip('reason')
 
For unittest, just raise unittest.SkipTest inside the test.
 
12:53 PM
ah cool thanks :) My google results just showed me how to run a skipped test, for whatever reason :D
 
1:27 PM
given that i have mentioned b=42, i want the output to be "42 is an even number", how do i do that?
print (b "is an even number")
the step that i got problem is this
 
@AdilMohammed have you read a good python tutorial yet?
 
Didn't know about skipping tests, that's actually pretty handy
 
1:49 PM
@AndrasDeak--СлаваУкраїні just started learning 2 days ago
which book would you suggest?
 
@AdilMohammed You might want to go through the official Python tutorial. It covers your question very early on.
 
 
1 hour later…
3:10 PM
6 hours ago, by Aran-Fey
Today I had to convince someone that f = lambda: x holds a reference to x
Status update: I failed to convince them and I just found out I'm not the only one they're trying to have this discussion with
...and I already invited them to join us in chat so we can clear up some misunderstandings
 
Do they at least believe that the equivalent def variant works as you say?
 
I have absolutely no idea
 
Have you tried paddlin' them off and on again?
 
Pretty much all they've done so far is to quote snippets from the documentation, but none of them were really related to the topic
 
In case you need a demonstration:
def foo():
    x = 12
    return lambda: x


print(foo().__closure__[0].cell_contents)
The disassembly should also show things clearly.
 
3:26 PM
Oooh, dis might be a good idea. But first we'll have to figure out just how many things they have misunderstandings about. I'm fairly sure they don't actually understand what references are, for example, which would certainly explain why the discussion hasn't been fruitful so far
 
FWIW, the relevant spec is binding-of-names and I'm 50% certain it's wrong.
It says "If a variable is used in a code block but not defined there, it is a free variable." but the rest of the spec uses "free variable" to refer to what most people would call global.
Which is tricky, because a free variable does in fact not hold a reference to its target.
 
4:02 PM
@Aran-Fey eh
sys.getrefcount/gc.get_referrers/weakref?
Hmm, if it does hold a reference, how does late binding work?
 
Well, getrefcount doesn't tell you who is holding the reference, get_referrers is tricky because it's an indirect reference (lambda references a namespace dict, and the dict references the object), and weakref doesn't achieve anything since we still have a strong reference also
Hmm, I guess you could make a weakref and demonstrate that it dies exactly when the lambda also does
 
@AndrasDeak--СлаваУкраїні The details depend on whether it's a closure variable or global variable. If it's a global, the function just holds a reference to the global namespace and looks up the variable name there. If it's a closure, then the function looks up the value through a "cell" object, but I don't know how the contents of the cell are updated if someone else assigns a new value to the variable
 
@Aran-Fey sounds like it doesn't hold a reference in the global case
 
The cell contents are writeable.
 
4:17 PM
I'll play with this later, on mobile now
 
I guess if multiple functions share the same closure variable, they also share the same cell?
 
Yeah.
 
Someone should submit a PR for dataclass(frozen=True) that goes and reassigns all the __class__ closures
 
Does it allow naughty things?
 
I don't think you can do anything particularly interesting by messing with the __class__ closure
 
4:27 PM
Well, you can change the class to whatever you want it to be, no?
Or is it separate from assigning to self.__class__?
Hm, probably yes...
 
Wait, I meant slots=True
Man, I've been writing and deleting answers to that question for the last 8 minutes. I've discovered some new things...
Turns out that all methods share the same __class__ cell
But still, the closure __class__ is not the same thing as self.__class__. The former affects the methods defined in the class (in particular, the type they pass into super() calls), but the latter affects one particular instance of the class
Here's a small demo of what I had in mind in regards to @dataclass(slots=True)
 
4:56 PM
Cbg. How do I make this code accomplish this so that the calculation in df.col is done considered grouping by day (say, by df.day column)?
Q1 = df.col.quantile(0.25)
Q3 = df.col.quantile(0.75)
IQR = Q3 - Q1
no_outliers = df.col[(Q1 - 1.5*IQR < df.col) & (df.col < Q3 + 1.5*IQR)]
outliers = df.col[(Q1 - 1.5*IQR >= df.col) | (df.col >= Q3 + 1.5*IQR)]
df = Pandas Dataframe
 
I've been told that "it's common to convert methods to functions", as in converting class Graph: def add_cycle(self, nodes): ... to def add_cycle(graph, nodes):. And apparently the reason for this can be found in "any OO textbook". What do you folks think? It sounds like BS to me
 
The idea that any OO textbook, no matter which, says the same is BS.
FWIW, it's possible to convert any method to a function but the entire point of how class and def interact is so that you can do the reverse.
 
Surprisingly, they actually took the time to explain that statement in more detail:
> Understanding a class entails understanding its interface. This is one reason that smaller interfaces are usually better: they are easier to understand. Classes with large interfaces are called monolithic, and are considered a code smell.
>
> A general rule of thumb is that if a method can be implemented without accessing member variables (private members in other languages), then it should probably be a function instead. This keeps the interface small.
I still sounds stupid to me, but at least there's some logic to it
 
5:14 PM
They aren't Julia programmers by any chance?
The bogus part about this kind of arguments is – IMO – that for all intents and purposes, the methods-written-as-functions are still part of the interface you have to know to use a type effectively.
It's also somewhat questionable to motivate the interface based on implementation details...
"can be implemented without accessing member variables" isn't something the interface should be concerned with. Quite the opposite, actually.
 
@MisterMiyagi Don't know, but there's no indication of it in their recent posting history. It's all python
I pretty much look at it the same way as you. Ripping out a part of the interface and putting it somewhere else isn't the same thing as making the interface smaller
You could even argue that it only makes the interface of the library larger
 
There's also the issue of polymorphism. thing.copy() is polymorphic by design, copy(thing) is not.
You need at least dispatch or fall back to methods to make them equivalent.
 
5:34 PM
They gave me this article to read. Turned out to be a surprisingly productive discussion, considering it took place on the internet and all that
 
> (Do we really want to go out of our way to make our users commonly have to look up which functions are members and which ones aren't? That already happens often enough even in better designs.)
This sounds like an argument for methods
 
6:12 PM
Hi all, I have a question about pytest that I believe isn't worth opening a post for.

I'm using pytest to unit test a class for an application I've built. rather than recreating the class for each individual unit test, am I correct in my assumption that I should create a single fixture of the class and then pass that fixture to the separate unit tests?

https://docs.pytest.org/en/7.1.x/how-to/fixtures.html
 
6:23 PM
@JacobBumgarner if that setup works for you and you're not testing class instantiation then yes, I think so.
 
Ok, thanks :)
 
6:42 PM
Just make sure not to botch the scope of your fixture. Each test should have its own instance of the class, otherwise you risk accidentally sharing state between tests
 
Could you describe more how I might incorrectly alter the scope of the fixture? Based on this section of the docs, I was under the assumption that a new instantiation of the fixture was created for each test. Thanks

https://docs.pytest.org/en/7.1.x/how-to/fixtures.html#fixtures-are-reusable
 
here is the section fixture scopes: docs.pytest.org/en/7.1.x/how-to/…
you are correct, the default scope is function-level
 
I probably made it sound like a bigger problem than it is. The default behavior is correct anyway, so it's all fine unless you go out of your way to break it. Which you can do with @fixture(scope='class') for example
 
I see. Thank you both, and thanks @Arne for pointing out the doc
 
7:17 PM
would you mind sharing your test code, or an approximation thereof? I'm curious what it looks like
 
Having only a list of values from a Pandas dataframe, how can I get the list of indexes of these values?
from a Pandas dataframe column*
 
7:35 PM
Something like df.index[df['col'].isin(values)]?
 
Perfect, a few minutes ago I found the following answer concerning yours: stackoverflow.com/a/39120806/2369957
Thank you very much, anyway
 
8:00 PM
@Aran-Fey it's common if you find yourself refactoring a codebase full of poorly motivated classes, I guess. But I am skeptical of the claim that anything "can be found in any OO textbook". Most of what I've seen written on the topic of OO is bad; people disagree widely about what OO even is, and when you can find agreement, it's often near awful Schelling points (like Java-style COP)
the two greatest sins of the Python standard library (really, its legacy) are trying to write C, and trying to write Java
(though the C is partly built into the language too)
meta.stackoverflow.com/questions/418767/… This seems promising. Bullish for the creation of new canonicals, one might say.
@Aran-Fey Oh, yes, I've seen this advice before. It comes out of the C++ world IIRC. What they have in mind is to avoid jamming all of your "sugar" methods into the class itself. For example, if the implementation of add_nodes is to iterate over the provided nodes and call add_node for each,
From a Python perspective, add_nodes is "part of the interface" whether it's a method or a free function that wraps a simpler method. But in C++, there are serious considerations about compilation time here, due to how the class mechanism interacts with the preprocessor-based "inclusion" and static compilation/linking system (i.e.: the lack of a proper import mechanism).
changing things that are outside of the class is less likely to require large amounts of stuff to be recompiled, vs. changing things that are inside the class - because changing the class' code makes the compiler have second thoughts about the actual structure/layout of the class data (since, again, it has to prepare those kinds of things statically).
IIRC, yosefk.com/c++fqa touches on this in several places.
 
8:16 PM
@Aran-Fey is this test off somewhere?
import weakref

class Foo: pass

x = Foo()
l = lambda: x
ref = weakref.ref(x)
assert ref() is not None
del x
assert ref() is not None
del l
assert ref() is None
$ python foo.py
Traceback (most recent call last):
  File "/home/adeak/tmp/foo.py", line 10, in <module>
    assert ref() is not None
AssertionError
this is after del x
 
However, there's another potential upside: by pulling add_nodes out of the Graph class, we raise the possibility that there exists some other class (possibly not even one related by inheritance!) for which the "iterate and call add_node" algorithm is useful. Then we get improved code reuse.
 
@KarlKnechtel Interesting. I had a feeling that this "pattern" (if you can call it that) may be related to C, but I couldn't put my finger on anything specific
 
Python actually practices this in some limited ways. For example, while .sort is a method of lists (a mutable sequence is needed to do in-place sorting, after all), sorted is a free function (because the underlying logic can operate on any iterable, without needing to know any implementation details).
 
@AndrasDeak--СлаваУкраїні No, that's all good. The difference here is that x is a global variable. You only have one of it, and del x deletes it. The lambda has a reference to the global scope, not to the object stored in x, and you removed x from that global scope.
 
@Aran-Fey which would mean that "f = lambda: x holds a reference to x" is not true
 
8:22 PM
When people teach C++ with a heavy focus on the standard library (and do a good job of it), the <algorithm> header figures heavily in the lessons. The Python rough equivalent is a subset of the builtins: sorted, len, min, max, any, all come to mind.
(ironically enough, one of my blue-sky proposals for Python is to have support for hooks to optimize some of these, or make them work for certain non-iterables)
(oh, and sum of course)
 
@AndrasDeak--СлаваУкраїні Ok, if we're going to go there, let's clarify some things first. Because technically, that statement doesn't even make sense. You can't hold a reference to a variable, you can only hold a reference to an object. So what's really happening is that f holds a reference to the namespace dict (locals()), and this dict holds a reference to (the object stored in) x. So f indirectly references x. If you remove x from the namespace, it's gone for good.
 
OK, I don't think that means that it holds a reference to the variable or the object if we're being technically correct.
 
Not directly
 
@Aran-Fey Ah, yes, definitely C++ then. GotW = guru of the week, a series by (IIRC) Herb Sutter
 
I would expect that "holds a reference" literally means "increases its refcount and prevents it from being destroyed". Which is true for the non-global case.
import weakref

class Foo: pass

def foo():
    x = Foo()
    return lambda: x, weakref.ref(x)

l, ref = foo()
assert ref() is not None
del l
assert ref() is None
this works ^
 
8:27 PM
2000s era wisdom.
 
The big difference there is of course that there's no del x
 
But now I understand how you meant "holding a reference". That it can be located from the function's state. Which would be true e.g. with a weak reference too.
@Aran-Fey well, x doesn't exist in the scope that l is in
that's close enough for me :P
 
But it exists in the scope where the lambda looks for it (:
 
that's fake news
everything in a function that's done executing is dead to me
 
8:31 PM
Andras: "You're legally dead"
x: "But I'm alive"
Andras: "Not my problem"
 
exactly
let me get my footgun...
 
while we're on the topic of fun internal stuff though: any third-party libraries out there to treat Python bytecode as a machine code, and implement an actual "assembly language" on that? I mean: the standard library dis can give a code listing, but it's in a format meant more for debugging than what would actually resemble assembly. I also can't "assemble" it (i.e. re-create the code object from the listing), or deal with bytecode intended for older versions of the Python VM
 
@KarlKnechtel "Frequently Questioned Answers" is a fun phrase, I like it
 
Last night I prototyped something that hacks the bytecode for recursive functions, to replace global lookups for the recursive call by loading a constant (also added to the co_consts). It's not really for optimization purposes (although it kinda does that) but because I wanted to be able to decorate (not just wrap, but reuse the name) a recursive function and have the recursion call the original function. (which I guess is never really a hard requirement but, you know, aesthetics)
 
I'm gonna throw the name "Nuitka" out there just in case, even though I'm pretty sure that won't help you
 
8:55 PM
that does sound familiar
 
9:25 PM
Hello, I want to ask for help with FastAPI. I am making a small using API as my backend (with some extensions), but I also have a simple UI of just HTML. I have a login/register functionality, where I want the user to log in.
After following a guide, I implemented JWT and OAuth2 for authentication. But these work only when working on the SWAGGER UI (localhost/docs) and not when logging in from the browser. What must I do, so as to create a session after the user logins and keep it until he logs out again?(from the browser, not but just calling endpoints)
 
10:12 PM
Did SO just introduce a new up/down vote design? That breaks my "click the upside facing triangle" say to newcomers
Well, technically there is still a triangle, so :P
 
@DelriusEuphoria there's an ongoing A/B test, yes
@DelriusEuphoria good news: nagging users for upvotes is bad form anyway.
@Mikhail at least that doesn't shock me
 
actually it works, I had them behind a PyCapsule which is another python builtin type :-/
 
heh
Do you have to monkeypatch a class like that?
 
Yes
 
OK
it's your feet after all
 
10:18 PM
One another annoyance is that a few python builtin types (used for interoperation) like PyCapsule don't have type hints, and aren't recognized by most interpreters. While they are built in they don't appear in typical lists of built ins.
 
AttributeError: module 'builtins' has no attribute 'PyCapsule'
 
indeed, but its part of the python C api
 
What would it mean for a PyCapsule to "have type hints"? I thought PyCapsule was a ctypes wrapper for an extension module, and you even have to tell ctypes the argument and return value types if you want to call one.
 
the type hint would simply say that its a function object
 
I might be conflating multiple ctypes idiosyncracies there
 
10:21 PM
Its the same issue as you'd have if you were to write a function that accepts a regular lamba
But for me the issue of a lack of a type comes from the need to automatically generate a large number of stub files - rather than lets say the usefulness of the stubs.
 
@Mikhail but it's not, is it?
 
semantically its simliar
 
OK, I wasn't confused:
May 8 at 23:53, by Andras Deak -- Слава Україні
>>> ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
>>> ctypes.pythonapi.PyCapsule_GetName(img.im.ptr)
b'PIL Imaging'
 
Seems the guy from pybind11 had the same issue: stackoverflow.com/a/62258339/314290
 

« first day (4268 days earlier)      last day (674 days later) »