« first day (4222 days earlier)      last day (733 days later) » 

5:06 AM
@Aran-Fey scikit-image scikit-image.org has some interesting stuff, but its documentation has inexplicable gaps. I had to look at the source code to find some of the functions I needed.
 
 
2 hours later…
6:42 AM
@PM2Ring Interesting, I'll check it out, thanks
 
 
2 hours later…
8:54 AM
installing open cv fried my CPU
I7 8700 :(
and then failed after ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly who made this pip
nvm i used this instead pip3 install opencv-python==3.4.13.47 from stack. works instantly
 
 
3 hours later…
12:16 PM
0
Q: How to satisfy output line length, code line length and Black code formatting at the same time? I.e. textwrap.wrap drop whitespace before wrapping?

rattlesnakeThis might be an XY-problem regarding the question about textwrap.wrap. I don't need to use textwrap.wrap if there's an easier way. I want to satisfy the following three criteria: Printed output text maximum line length of 70 Source code maximum line length of 80 Black code formatting Here is a...

I patiently waited 48 hours. 😜 Anybody got an idea? Do I really have to put a chain of print, str.join, textwrap.wrap and re.sub into a new function?
 
As far as the Y goes, aren't you just missing a textwrap.dedent call inside wrap?
 
This is the first time I've seen someone explicitly ask for formatted code
I'd be lying if I said I understand the question, but I think all you need is something like this?
 
it's nested a few levels
but what you have plus dedent might work still
well, if you put the first line on a separate line and probably `"""\` at the opening quotes
 
Or just add a text = textwrap.dedent(text.strip('\n'))?
 
12:48 PM
But it's still an additional call to another function... textwrap.dedent plus str.strip would even add 2 more calls.
@Aran-Fey Sarcasm?
 
No. It's a pretty weird thing to do. If you want formatted code, just format it.
 
I don't understand. "Just format it"?
 
@rattlesnake you can always spell them out on separate lines if you need/want to...
I doubt there will be a non-ugly alternative, you can only choose your ugly
 
You mean multiple calls to print?
 
Let's just say I don't understand your problem
 
12:54 PM
@Aran-Fey 🙈 I'm sorry. Can you give me a hint where I should improve the question?
print("\n".join(textwrap.wrap("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")))
I want this command to satisfy:

- Printed output text maximum line length of 70
- Source code maximum line length of 80
- Black code formatting
 
Like this?
 
Oh, I saw your link earlier, but I thought Andras reply cleared it up for you
He's right, this doesn't work because it's nested a few levels
That's what he replied. I'm sorry I thought you saw that
 
@rattlesnake no, just calling one function at a time
 
I'm pretty sure you never mentioned that in your question
 
@Aran-Fey I did get it from there
lipsum = """..."""
stripped = lipsum.strip('\n')
dedented = dedent(stripped)
...
 
12:58 PM
It says "the print is indented some levels", but nothing about the string
 
Just make the string a global variable and problem solved
 
put it in a global in another module so you don't have to see it, problem solved even more
 
@AndrasDeak--СлаваУкраїні Ugh, yeah 😅 I see what you mean now. Yes, I agree, that's ugly, too. Hmm...
@Aran-Fey Oh you mean like continuing the second line of the string at 0 without following the previous indentation?
 
That's also an option
 
1:01 PM
"also an option" means that's not what you meant? 😉
 
@rattlesnake that's one of the options I hate the most for what it's worth
multiline strings leaking up into higher intendation levels get under my skiin
 
That's why I'm asking about this in the first place. I wanted to make this look nice and well readable, but ended up having to chain so many calls. :( I guess the best way is to write my own pprint function for my needs. And chain the calls in there.
 
There's really no shortage of ways to create strings dpaste.com/F9G7W8VTR
And that's all without dedent
 
we should investigate how java does it, and introduce that in 3.12
 
@AndrasDeak--СлаваУкраїні I assume you're joking but this feature is part of argparse when it prints the help text for the command line options. And they use re.sub(r"\s+", " ", ...) in the formatting chain. You might remember that from a few days ago. ;)
 
1:09 PM
yes
although I'm not sure what "this feature" is
 
Really? You both agree that this is something weird? You never had to do this?
I have a script which logs output which I partially want to have long lines (keep output as it is) but also write lines that should be easily readable when going through the file. So those lines should cap at 70 chars.
I don't think "formatted output" is such a weird thing?
 
That sounds as if your wrapping input was not a string literal.
The crux of the problem seemed to be that you had this wall of text in the source code.
 
No, no. It is.
The long lines aren't string literals
The lines that I want to print formatted are string literals
 
@rattlesnake I didn't mean the text you print, I meant the code
 
1:17 PM
I mean, why does textwrap.wrap have the drop_whitespace=True option?
@Aran-Fey You have never seen code that follows a maximum line length for strings?
 
Of course I have. But I have never seen someone ask for black-formatted answers.
 
I can't tell if you think that's bad?
 
I do. Like I said, if the formatting isn't to your liking, you can just reformat it. It made the question more confusing for no real reason
Anyway, now that I understand the question (or at least I think I do), I can tell you how I'd improve it. I'd rephrase it to something along the lines of "I have a long multi-line string that exceeds PEP8's 80 char line length. How can I define this string without exceeding 80 chars?"
 
But... following Black format guidelines is part of the issue? If I don't have to follow Black, then I don't need the new lines and added indentation levels for each call and chaining calls would be much "cheaper"?
@Aran-Fey Could be an answer, yes. That's why I mentioned "possible XY-problem" at the beginning. Who knows? Maybe there is exactly what I want already in the pprint module and I just didn't find it
 
PEP8 was allowing up to 100 characters as far as i remember
 
I don't think pprint or textwrap are related to your problem at all. You want to create a string without exceeding 80 chars per line. What you do with that string later is irrelevant
 
One of the most controversial decrees
(And often violated)
 
@AndrasDeak--СлаваУкраїні from PEP8 "Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters."
 
It's also OK to ignore anything else if the team so agrees
 
Wait, docstrings and comments are supposed to wrap at 72? I've been wrapping them at 80 all this time
 
Naughty
@Aran-Fey I get your point. I do. But sometimes "basic issue A" (which has a set of solutions A) and basic issue B (which also has a set of solutions) combine into an issue C whose best solution is not to simply chain a solution from A with a solution from B, right?
Doesn't necessarily mean that this is the case here ;)
 
True, one reason why asking good questions isn't easy
 
the common question in sopython.com menu give sopython.com/canon as 502
 
Yeah, it's been like that for a while (and will probably continue to be like that from now on)
 
1:58 PM
Why? 🤔
I mean, why will it continue to be like that?
 
Judging by the state of the spoiler obfuscator
How many years has that thing been broken now?
 
@XavierCombelle You can get around it by passing a query: sopython.com/canon/?page=2
 
Yeah, but someone must have access to the server?
Hopefully even more than one person?
@Aran-Fey Yes, very, very true. Thanks everyone for your suggestions. I've collected everything and posted an answer. Maybe it helps someone else who also struggles with something similar. At least textwrap.fill is definitely an improvement.
 
2:20 PM
maybe @MartijnPieters know who has the key of sopython.com (sorry if I disturb you)
 
@davidism was running it last I knew...
Haven't seen him in a long time, though.
 
@JonClements seems around there
 
Not much point pinging everyone for a known issue
 
Ah, you're saying the person responsible for the server is aware of the issue but they won't fix it?
 
2:38 PM
*hasn't fixed it yet
 
It's open source, if you want to fix it yourself, have at it. github.com/sopython/sopython-site
 
2:52 PM
@AndrasDeak--СлаваУкраїні I was only referring to Aran-Fey's message from above 🤷‍♂️
@MattDMo That repository hasn't seen any commits since 2019. And apparently the issue has only surfaced recently. So I doubt that making pull requests to that repo will help anything. Not to mention that someone would still have to review and actually merge it.
 
@MattDMo I don't think it can be fixed without access to the db. I can get the site running locally just fine but with no questions. It's also strange that it's only something on the first page
 
Cbg. Sometimes "None" and "not set" means two different things. Does python have anything built-in what could be used for "not set"?
 
Maybe someone should ping davidism and see if he'd be willing to turn the project over to a worthy successor, or at least give admin privileges to someone trustworthy. I'm not volunteering, since I don't know much about Flask, but maybe someone else does?
 
3:09 PM
I thought that's exactly what people were trying to do, but then Andras remarked that the server owner is aware of the issues already
 
@roganjosh maybe it is a server config
 
I could take it over I guess, but Jon might already have the credentials. Davidism does know about it but he's been at PyCon and already told us it would be a week before he got chance to look at it
@JonClements do you have access to the host server? Apologies for the ping if you've already clarified that you don't
 
Hey fellas :) How u doin?
 
@KarolZlot I don't think so. Plus, using some kind of placeholder doesn't really solve the problem, does it? Python simply doesn't have type annotations for "this thing might not exist"
 
3:24 PM
notset = object() is a common pattern
 
Making some kind of union with a special NotSet type doesn't really achieve anything as far as I can tell
Rather than a union, I'd probably use typing.Annotated
 
I don't know anything about type annotation, but "sentinel values" are a common way to return a status indicator from a function
not_set = object()
def maybe_get_first_element(seq):
    if len(seq) > 0:
        return seq[0]
    else:
        return not_set

x = []
result = maybe_get_first_element(x)
if result is not_set:
    print("Couldn't get first element.")
else:
    print("First element is:", result)
Of course, if some practical joker calls maybe_get_first_element([not_set, 2, 3]), then the wrong print statement will execute. But this should be quite rare, since 99.999% of the time there is no reason to put not_set into a collection or assign it to a new name. Or really, do anything besides using it in an is expression.
Oops, vaultah suggested this already. Well, maybe my excessive detail will be of some use anyway.
 
4:00 PM
Thank you.
 
Why is object() being used for this instead of something more descriptive like class NotSet: pass? Wouldn't this have less probability of being an legitimate item of the sequence?
 
Why?
 
Keep in mind that any other objects you create using object() will be guaranteed to fail the is comparison. They're guaranteed to be distinct.
You can verify this by modifying my code to x = [object()]. It correctly prints the first value rather than saying it couldn't get the first element.
 
Ah, I understand. Thank you :)
 
4:16 PM
People do use class NotSet: pass though
 
I do think there is merit in creating a NotSet class. It may make it easier to annotate functions that return not_set, and it may be easier to debug.
 
I think you can even find examples in the standard library
 
Yes, peps.python.org/pep-0661 mentions that
Hmm, looking at it again, Rejected Ideas does not mention the approach of defining a class NotSet: pass and creating one instance of it every time you need a distinct sentinel value. IMO, it has slightly different pros and cons compared to the approaches listed there.
 
hey @AndrasDeak--СлаваУкраїні ! You helped me optimizing a function with pythran ~8 months ago, and I'm now back to it, but I have a question, if you would be kind enough to answer: there's app.py and func.py, and func.py has already been pythranized so there's this .so file aswell... Inside app.py I'm calling func just as before using 'import func'. Is that correct? In other words: after running pythran func.py on terminal, is there anything else I should do for it to work properly? Thanks
 
if I want to print a float to two decimal places I can do round(x, 2). If have a list of floats, how can I show them all to two decimal places using map()?
that is[*map(round(?), vars] ?
ah yes... map(lambda x: round(x, 2), numbers)
 
4:33 PM
@graffe Use formatting, not rounding.
1.0 rounded to two places is still 1.0.
 
map(lambda x: f"{x:.2f}", numbers) ?
 
print(*(f"{x:.2f}" for x in numbers))
 
@MisterMiyagi that's good too!
 
4:47 PM
Fizzy!
 
<.<
 
4:58 PM
That's enough socialisation for this year, good bye.
 
Bye Fizzy!
 
5:16 PM
Hey all, I'm aware that sopython canon is down, it may be a bit involved to get things updated, since it's just been running in the background for years now. Still on Python 3.6. But we've got a database backup, so no worries of losing anything.
5
Currently running on Flask 1.0.2, time to update some libraries.
 
Thanks for the clarification, davidism :)
 
6:20 PM
@lupus when the .so file is generated with a successful pythranization run, that .so module will shadow the pure-python implementation. So if you have func.py and you also have something like func.cpython-39-x86_64-linux-gnu.so then doing import func should readily import the compiled module. You can confirm by print(func.__file__), it will tell you which one you have. The great thing about these mechanics is that the fallback to the pure-python implementation works naturally.
(then again with numba you always have foo.py_func that gives you the pure-python function)
 
 
2 hours later…
8:04 PM
not_set = object()
not_set2 = object()

print(not_set == not_set2) # prints False
(Nice to know)
 
 
1 hour later…
9:29 PM
Which one do you prefer?
class Spam1:
    pass

class Spam2():
    pass
 
Why would anyone prefer the latter?
 
Something something explicit is better than implicit?
But yeah, definitely the first one
 
class Spam3(object): is explicitest
 
I was always using the latter, because I didn't know the former is correct.
@AndrasDeak--СлаваУкраїні this explicitest one is discouraged here: stackoverflow.com/a/45062077/8896457
 
@AndrasDeak--СлаваУкраїні Look, I don't mind you one-upping me, but explicitest? That's just objectively wrong. Behold: class Spam4(object, metaclass=type):
 
9:33 PM
@Aran-Fey I concede
Also, "objectively" wrong? I give up.
@KarolZlot I was trying to make the point that explicitness is a bad excuse here to use the superfluous version
 
I half expected you to counter with class Spam5(builtins.object, metaclass=builtins.type):
 
Laurel
@AndrasDeak--СлаваУкраїні Melon
 
 
1 hour later…
10:36 PM
I need some help figuring out the numpy array interface. The code I see in PIL doesn't quite match the description from the numpy docs.
It says there that the object should have an __array_interface__ attribute, but PIL images have an __array__ method instead, which returns an object with an __array_interface__ attribute. And the docs say data should be a 2-tuple, but PIL just puts a bytestring there.
Plus, I've seen some snippets that claim to create a (read-only) numpy array from a PIL image, but PIL's __array__ method creates a copy of the data with self.tobytes(). Nothing makes sense to me
 
10:54 PM
@Aran-Fey I meant "claim to create a (read-only) numpy array from a PIL image without copying"
 
@Aran-Fey there's a bit of a zoo of dunder array protocols, some of which are explained to some extent at numpy.org/doc/stable/reference/…. Specifically __array__ is only mentioned in passing. Unfortunately I don't really know these. They are on my long-term TODO list to learn about.
I guess it all might be down to numpy.org/doc/stable/reference/c-api/… which allows objects to define how you can convert them to arrays
it would make sense for this machinery to allow the creation of what are essentially views into a non-ndarray buffer
__array__wrap__ also suggests that __array__ is to be used by that. It would probably help if we knew what kind of numpy functions and methods made use of __array__...
 
Oof, my brain is fried. I can barely understand a word of that __array_wrap__ documentation
It's a shame it's not properly documented, but maybe I don't even need to deal with it. I got some ideas. But that's for tomorrow. Thanks for the help
 
sounds like it would allow PIL to convert arrays into PIL Images within a numpy function
 
Yeah, PIL can turn a numpy array into an Image no problem. What I'm struggling with is turning an image into a numpy array without making a copy
 
OK, I see. There has to be a solution for that.
 
11:08 PM
The getdata() method and its return self.im # could be abused comment seem promising, but... tomorrow
 
11:33 PM
@Aran-Fey Does this code do what you expect?
import numpy as np
from PIL import Image

width, height = 5, 4
img = Image.new("RGB", (width, height), color="#ffaa55")
print(img.size)
a = np.asarray(img)
print(a.shape)
print(a)
 
There was a bug or two in PIL .fromarray, but that's been fixed. gist.github.com/PM2Ring/b09216123cca86e9b9cf889bfd3c5cec
 
If you change the image then the array doesn't change.
In other words, asarray returns uses a copy of the data, which corresponds to the tobtes call Aran mentioned earlier
I think one could wrap the raw data through img.im.ptr, which is a PyCapsule and I can't figure out how to get at the contents with ctypes...
 
@AndrasDeak--СлаваУкраїні Ah, ok.
 
I think I'd need ctypes.pythonapi.PyCapsule_GetPointer, but it seems I have to define an appropriate signature for that to work, and I can't even figure out what function I have, let alone its signature...
so something tells me this is not normal
>> ctypes.pythonapi.PyCapsule_GetName(img.im.ptr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1
>>> img.im.ptr
<capsule object "PIL Imaging" at 0x7f2977114360>
>>> type(img.im.ptr)
<class 'PyCapsule'>
Is this normal?
in the C world the right approach would probably be numpy.org/devdocs/reference/c-api/…
 
11:50 PM
I know nothing about PyCapsule
 
same...
>>> ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
>>> ctypes.pythonapi.PyCapsule_GetName(img.im.ptr)
b'PIL Imaging'
now we're talking
 
stackoverflow.com/questions/72165827/… Any canonical for this, where OP tries to use code with input at the interpreter prompt, such that part of the code is understood as the input?
or should I come up with another reason to close (not reproducible, or about general software are the ones I'm thinking)?
 

« first day (4222 days earlier)      last day (733 days later) »