« first day (3233 days earlier)      last day (1699 days later) » 

1:05 AM
cabbage
 
 
4 hours later…
5:09 AM
cbg
 
+1 close vote
closed
^
 
6:51 AM
@wim I think I got all of them: view spoiler
 
7:18 AM
@wim this one can be brute forced
 
8:16 AM
Has anyone ever used sys.getsizeof productively?
 
8:33 AM
cbg
 
8:48 AM
@Aran-Fey I doubt other than for very specific purposes. I think it's basically for you to hook your own __sizeof__ methods should you desire. Though as the docs note, all built-in objects respond correctly.
 
cbg
 
seems to be doing more harm than good, honestly
 
I can honestly say I've never implemented a __sizeof__ method in my life, and I'm not inclined to alter that without a serious use case.
 
@holdenweb Me too
 
@Aran-Fey no, there is a very, very high chance of using it wrong. better to measure the memory footprint of the entire application. PyPy outright raises an error when sys.getsizeof is used.
 
9:03 AM
Ha, nice design decision
 
9:54 AM
cabbage
 
10:12 AM
hello
 
@Aran-Fey The docs say it's implementation-dependent.
 
10:29 AM
does someone here know how I can add a comment on a bugs.python issue? I'm logged in, and the issue doesn't seem to be archived or resolved. Am I just dense and can't find the comment box, or do I need more than an account to post there?
 
Hello everyone
Can anyone guide me how to write python fixtures to store and fetch a string
 
hi everyone
i need a help
 
@SomnathPal are your fixtures a general concept, or related to a specific library like pytest?
 
its regarding pytest
 
i m using scrapy to get all the text in webpage
def parse(self, response):
    webpagetitle = response.xpath('//title/text()').get()
    webpagetext = response.xpath('//body//text()').getall()
    print(type(webpagetitle))
    print(type(webpagetext))
    webpagetitle = re.sub("[^a-zA-Z0-9\s\,\.\(\)\[\]-]+","",webpagetitle)
    webpagetext = re.sub("[^a-zA-Z0-9\s\,\.\(\)\[\]-]+","",webpagetext)
    yield {'url': response.url, 'title': webpagetitle, 'text': webpagetext}
    for link in response.xpath('*//a/@href').getall():
        yield response.follow(link, self.parse)
but it is extracting text
as the type is not text
plus it is giving only \n space \n values
 
10:40 AM
@SomnathPal and the official guide didn't help enough?
 
anybody was there
to help me
 
No. I'm new to Python and doing unit test using Selenium
I wrote test cases and need to store and fetch a string
@pytest.fixture(name = "dealVal",scope = "class")
def deal_fixture():
def __init__(self):
self.dealTitle = ""
def storeVal(self, val):
self.dealTitle = val
def fetchVal(self):
return self.dealTitle
 
@SomnathPal ctrl-k does code formatting in chat messages
 
ok. anyway. u can see the code
Then I'm storing it in another method
deal_title_array = self.driver.find_elements_by_class_name('toe')
h4 = deal_title_array[0].find_element_by_tag_name('h4')
print(h4.text)
dealVal.storeVal(self, h4.text)
 
I might be confused about what you're trying to achieve, but having an inner method called __init__ is a bit of a read flag
 
10:45 AM
I am getting error "Nonetype" has no attribute 'storeVal'
 
@SomnathPal please press ctrl-k before you send a message that consists of code
You're getting the NoneType error because the fixture doesn't return anything. In a fixture you can create/manipulate an object that is returned in the end.
if you don't return anything, any python function returns None by default
 
Ok. Got it. Thanks man.
 
you probably already have a class that shows the behavior that you want, right? just create that in the fixture, monkey patch its storeVal and fetchVal methods, and return it.
no problem, hope that is everything you need. as soon as you are a bit former in the basics, I'd suggest trying to work through the pytest docs, they are really good and very extensive.
 
Sure. Will go through them. Thanks again.
 
hey guys! howzit goin?
I'm having a CRAZY issue with pymysql after redirecting my script to mysql AWS RDS.
After running a bulk insert query, I get a result saying "543" rows were inserted, my connection looks like this: `pymysql.connect( host=hostname, user=username, passwd=password, db=database, port=port, autocommit=True )`

everything runs successfully, but when I check the table in the database it shows that no data was pulled in. . . I'm losing my mind here man
 
10:56 AM
@RinkuYadav since your example cannot be run, can you clarify what you mean by "but it is extracting text; as the type is not text"?
 
so as an example, this is exactly how it is run:
 
@pythonian29033 Maybe an omitted commit, or a different autocommit setting on the two environments?
Looks like it ought to work, but clearly isn't. Maybe there's some surrounding transaction you aren't aware of that's getting rolled back?
From https://blog.hassler.ec/wp/2018/07/07/using-pymysql/:
"Heads up: Note the line conn.commit(). Don’t forget that — this is what actually commits the update to the database. Forgetting this line and wasting hours debugging is somewhat of a rite of passage, but let’s just skip all that." Are you doing an explicit commit?
Bulk updates may use different rules than regular transactions.
All obvious thoughts, so you've probably had them already, but that's the best I can do.
 
11:26 AM
Does anyone know if there's a library which I can use to plot %%timeit measurements. Only one I found is this, but the last commit was 6 years ago
 
You might be interested in checking out perfplot
Some of my favourite SO answers use it.
 
Turn on Stack Overflow for a look at new questions and the first question I see: stackoverflow.com/questions/57625356/…
 
I knew I had seen that one somewhere, just couldnt find it anymore somehow. Thanks @ParitoshSingh
 
No worries.
 
I really can't understand how the OP is getting that. The WinAPI is usually solid enough, I checked the docs and there is no way that mouse_event() should do that. I'm intrigued, although I suspect it's something else causing it.
 
11:50 AM
Just another sinkhole in the swamp that is Windows.
I now have Parallels on my Mac, it really is a superior way to run Windows.
 
Yeah, or it may be a dodgey plug in the back of a desktop causing it... I agree though Windows is often rubbush, C# is probably the only redeeming feature
 
What should I do if I want to calculate the difference between two values, but have it be relative to the value size. So for example 1 compared to 1.1 would end up the same as 100 compared to 110. abs(x-y) but with some percentage part mixed in?
 
divide one by the other.
>>> 1.0 / 1.1
0.9090909090909091
>>> 100.0 / 110.0
0.9090909090909091
 
Oh damn, you got me feeling like a dumbass
 
12:03 PM
@smci No imo. It's a good link for a "Related" kind of read though as a comment.
 
no problem, brainos happen all the time
 
Thanks!
 
yesterday or so i googled to make sure that 2 + 3 is actually 5 ¯\_(ツ)_/¯
 
@ParitoshSingh If not a dupe, then how is the OP's question any different than asking the difference between concat and merge (with specific column-order)?
 
12:05 PM
Ack, i really shouldn't have replied. I knew it was bait!
 
I really like the people on that question. Another Guy asked it and Some Guy answered it. If I didn't know better I would say that guy is rep farming
 
as long as it was not THAT guy!
 
Interesting. Looks like no major pattern quite yet though, but if one arises this should be easy to flag. For now though, i think it's fine.
 
Yeah, just coincidence
 
12:26 PM
Hello, I'm looking for "lore" or jokes for a python course, I want less serious stuff to show to the students in between exercices. So far i know of the imports this __hello__ and antigravity but i'd like more and possibly things that are't imports would be cool too.
Also I wanted to make sure, this kind of question does not have it's place on stack overflow right ?
 
Questions asking to recommend something are off topic "Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it."
 
@holdenweb Yeah, and in fact I suspect that STORE_NAME is being intentionally invoked instead of other faster name-storing opcodes exactly because it's in a class body. The compiler recognizes that the namespace is going to get bundled into a dict and sent to the type constructor anyway, so it may as well put the names straight into the f_locals dict instead of saving them on the stack or wherever first.
 
@Taek some of these might do, depending on the target audience: avilpage.com/2014/12/14-great-quotes-about-python.src.html
@Kevin it has to do that. The metaclass.__prepare__ result (usually a dict) is the namespace used to execute the class body.
you can actually modify the namespace while it is built, e.g. accumulating values of duplicate names
 
@Taek Correct, don't ask these on main. There's also import this for the zen, and frankly you might be able to teach a lot of good habits in a fun way just by showcasing the zen. (sorry it's another import though)
 
fondly remembers some dozen switch types
 
12:34 PM
While trying to find an amusing from __future__ import [something] message that I vaguely remember, I came upon python.org/doc/humor. I haven't actually verified that any of its contents are humorous.
 
I'm reading through that as we speak :P
They are funny, but not really stuff that is directly linked to code or something to be shown inside the language, so I don't quite think they're appropriate for what i assume is the target audience of students here. You need context for a lot of them.
 
Ah, now I remember what it was:
>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance
 
Yeah, one of my faves too.
 
Fun but I don't think that helps from an educational point of view, unless you are doing raising errors. That may cause more confusion than good
 
I loved that one a lot when i came across it
 
12:38 PM
You have a lot of faith in these students if you think they'll get all the way to the chapter on Exceptions before encountering their first SyntaxError ;-)
 
> Python is the "most powerful language you can still read".

- Paul Dubois
 
They're as like as not to see it in chapter one exercise one when they mistakenly type print(Hello, world!)
 
@ParitoshSingh No, it's not a loaded question, you might be right, I just can't see that it's different (except for explicitly specifying column-order, which is just a special-case of concat vs merge/join). But it seemed essentially a dupe to me
 
Ah, in that case, essentially the "dupiness" of a question in my eyes falls on two things: 1. It showcases the right function to use (which this dupe has a big checkmark on) and 2. It's easy for someone to "infer" their answer by even a quick glance if they aren't familiar with the topic beforehand. For me, it's this criteria that this, and most pandas dupes, fail to meet. However, i think this one is more "subjective" to think about.
 
@Kevin They are also likely to see "Unable to initialize device PRN" (from typing in CMD and not Python). I made that mistake when I was learning, I know, I needed help, but I was self taught
 
12:44 PM
Looking at it from the perspective of someone trying to solve a specific problem, i know i can use "merge" or "concat" somehow. But if my problem is answered by a link that only tells me "use merge/concat" but doesn't help me understand how exactly i could use "merge" in a manner that actually helps solve the problem for me, then There's a gap between what i consider a dupe and what is presented. full disclaimer though: this is my personal criteria for dupes, and it's perfectly ok to disagree.
 
Every once in a while I type python code into the command prompt, thinking it's a REPL. I'm worried that one of these days I'm going to accidentally erase my hard drive by doing that.
 
Unless you are running the command prompt as admin, it's not going to happen Not going to commit myself
 
good thing python code is too readable for the command prompt. :)
 
I frequently run my command prompt as admin though :>
 
I do too, sometimes... when things are blocked..(don't tell my IT! )
 
12:48 PM
I can only execute iisreset (an essential task when doing asp.net work) if I have administrator privileges, and I don't always close the command prompt window right away afterwards
 
accidentally executing a python script with bash is the worst - import x takes a screenshot and saves it as x.png. First you wonder why your cursor suddenly looks weird and nothing happens when you left click, then you figure it out and have to clean up 5+ screenshots in your home folder
 
Oh wow haha
 
(I'm using "the worst" very loosely here)
 
That's pretty amusing for sure
 
@MisterMiyagi , @ParitoshSingh thanks !
 
12:52 PM
cabbage
 
I'm guessing that without admin privileges I won't be able to brick my computer, by deleting system32 or whatever. But I can still erase all my documents/scripts/programs/photos/etc.
 
I think I came a bit late to this conversation. Is someone here trying to brick a computer? XD
 
I'm trying to keep my computer from being bricked, but my greatest enemy, me, is endlessly cunning in his stupidity.
 
12:56 PM
Make Virtual Machine, brick Virtual Machine, profit
 
@ParitoshSingh Log your crimes: use sudo (but not, I guess, on Windows)
 
Yep, no sudo on windows. sudo is a bit of black magic to me, since i never really used linux much.
 
Sudo is a mysterious thing for me as well, it's mystifying in a way to see what you can do with Linux
 
I guess I'll tune out before I start ranting about linux permissions again, rbrb
 
@ParitoshSingh It's a way of lending root privs on a per-command basis. Highly configurable, but very easy to configure for a single user. It runs your command(s) in a root-privileged shell.
 
1:01 PM
My knowledge of sudo begins with that "sudo make me a sandwich" xkcd, and ends with "... It probably stands for Super User DO?"
 
That's not a bad foundation
 
It's a magical incantation that makes broken commands work sometimes. Like the "!" descriptor in CSS, or except: pass in Python.
 
except: pass is another level of magic entirely, it's a reckless brand of magic but the results speak for themselves
 
@holdenweb Python needs a sudoadded to the syntax
 
I misremember, the CSS syntax is !important.
 
1:12 PM
I also came here because I'm quite lost with pytesseract so idk how to deal with problematic images. I made a question but I think I didn't explain myself very well so I haven't gotten response so far stackoverflow.com/questions/57582468/…
 
Or that it's simply not a simple problem to solve, and no one has a good answer for it that just works.
 
It might be worthwhile to edit the post to include the code that produces the "out of range" error you mention, along with the complete stack trace of the "out of range" error
 
I linked the answer where I got it but I should do that as well. Thx
 
There's a lot of work that has gone into improving OCR performances, and all you can do is try different things out. The shadows are particularly rough to deal with.
 
I've tried desaturation and different blurrings but so far I've been unsuccessful
 
1:15 PM
Use these steps as a guideline on things to try, however i do not anticipate perfect outputs because of the shadows.
 
But even if you explain yourself perfectly, sometimes there's just no good answer to "how do I make this OCR library do OCR better?"
 
Fair enough. I haven't used StackOverflow for a while so I thought I hadn't phrased it well enough XD
 
The question is more or less fine imo. It's just not an easy problem to solve.
 
If your post has zero downvotes, that's a good indicator that you phrased the question well enough
 
After you deskew the image, i think your best bet is looking at thresholding
 
1:19 PM
That is good to know, thx for all the help :D
I'll edit the question as well XD
 
Play around with different choices of thresholds, see if you can get away with absolute thresholds set to a very low pixel darkness. If not, take a look at adaptive threshold
 
I think users are wary of answering "fuzzy" questions, in general... They don't want to put an hour into inventing an approach that gives good output for your sample image, only to discover that it performs poorly on the 99 other images in your test suite. Compare to "firm" problems where an answerer can formally prove that their answer is correct before submitting it
 
Indeed, especially when these "fuzzy" questions involve a lot of trial and error and require a significant time investment.
 
I didn't know working with Tesseract was so tough. Makes sense considering it is literally text recognition but still
 
user11006952
Sorry to interrupt the conversation! I am new to flask and python and I'm following this tutorial. hackersandslackers.com/organizing-flask-with-blueprints | I have a (hopefully) quick question: In the "Defining a Blueprint" section, it uses @main_bp.route() decorator. I'm wondering whether that's a typo and it should be @admin_bp.route()...?
 
1:26 PM
Looks like a typo to me, since main_bp doesn't appear to be defined anywhere before that line.
 
user11006952
@Kevin Thank you for confirming! I'm just learning Python so I wasn't sure whether I just missed something.
 
I think I accidentally stumbled upon a thresholding code at some point while attempting to clean the image. It didn't work so I think I'll jump straight to adaptive thresholding just in case XD
I'm sure it'll be harder but it seems promising
 
Note that don't just blindly use thresholding code. you need to actually "set" good thresholds for your use case if you use absolute thresholding
But yeah, try different things out, see what works for you.
 
I've been looking at the RGB values of pixels and the issue is that going too low will make some letters disappear but too high will make the shadow to the bottom right swallow quite a lot of text
 
Ok, in that case yep, sounds like a no bueno
See if adaptive thresholds fare better
 
1:38 PM
From the preview images it seems like it will. I also found out that bilateral filtering removed some noise so I could try combining those two
It made the image very smooth and consistent but ofc it didn't do much about the shadows
 
The code at stackoverflow.com/a/4632685/953482 definitely looks weird... The guy is accessing pixel objects using indices 0 through 5, which seems wrong to me because RGB images only have 3 values, and RGBA images only have 4. Commenters, including the original answerer, admit that this is a problem.
 
Nice! :)
 
The issue is the person who made the code seems to have forgotten what the code's intent was so he was never able to fix it
Which is a shame because it looked promising as well XD
 
If you're still interested in pursuing that approach, try pastebin.com/e1cUB0ws. I changed the indices to something that makes more sense to me, although admittedly I don't know what the algorithm is actually trying to do
 
I'd probably forget code i wrote for someone else after a gap of 8 years too no doubt :P
 
1:41 PM
I think I'd forget it even after 2 or 3 years XD
Also, I'll try your code to see if it works :D
 
I've edited 3+ year old questions before. Last time it was because a commenter wrote "why did you recommend weird approach X and not typical approach Y?" and I replied, "... I don't know" and then I edited my code to use Y instead of X.
This demonstrates that, in principle, you can still edit your answer even if you had no idea what you were originally thinking
 
Still seems as hard as guessing what you ate five months ago
Actually that worked quite well, thx a lot @Kevin
It left a bizarre edge shadow but I'm sure Tesseract can deal with that
 
1:57 PM
Hmm, I think I was calculating the total momentum of a system incorrectly yesterday, since I was just adding up all the scalar magnitudes of each momentum vector. It occurs to me that this is probably wrong.
 
If they all go in the same direction it should be correct
 
@Kevin indeed
 
Imagine a system with two planets of equal mass. At time T=0 they both have velocity 0. Thanks to gravity, they start to accelerate towards one another, and by T=1 they each have a momentum of 1 kg ⋅ m / s. But the total momentum at T=1 is still 0, because they're pointing in opposite directions.
Ok, now my system only loses 0.00001% of its momentum over 20 years, which is good enough. Much better than the 400% gain I had yesterday.
Good news: fixed a logic error that I found while debugging.
Bad news: bug is still happening and now I have no leads.
 
That is such a specific amount, it really doesn't seem like it should happen at all
 
If a planet starts at 0 kg ⋅ m / s momentum and ends up with 357840257 kg ⋅ m / s momentum, it must necessarily pass through exactly 1 kg ⋅ m / s at some point in order to get there
 
2:10 PM
That makes sense
 
intermediate value theorem
 
It's not likely to happen exactly at time T=1... Except I have conveniently omitted the unit of my time measurements, which I now define to be "1 tick = the amount of time it takes for the planet in my thought experiment to accelerate until it has a momentum of 1 kg ⋅ m / s"
 
makes sense
 
2:29 PM
ah fun, spammer dude was back for a bit today.
rate limiting works thankfully!
 
2:49 PM
system unstable
 
Cool diagram. What parameters did you start with? i.e. the positions/masses/velocities of your bodies?
 
is there any way to suppress the RuntimeWarning for individual un-awaited coroutines?
 
@MisterMiyagi There be dragons!
 
There are a couple ways to hide warnings described in docs.python.org/3/library/warnings.html. Or maybe you're asking "what is the proper way to handle unawaited coroutines, so that I don't get a warning in the first place?". I don't know the answer to that one.
 
Await them?
 
3:01 PM
If Miyagi doesn't know, who would i wonder.
 
That would probably help, yeah
 
@ParitoshSingh Quite.
 
laurel
that got a chuckle out of me.
 
I'm just barely getting a handle on multiprocessing, so I should get around to coroutines in five years or so
 
System made rapidly unstable by using bodies 10,000 times more massive than Earth

AU = (149.6e6 * 1000)                # 149.6 million km, in meters.
SCALE = 250 / AU
sun.mass = 1.98892 * 10**30
body1.mass = 5.9742 * 10**29
body1.px = -1*AU
body1.vy = 29.783 * 1000             # 29.783 km/sec
body2.mass = 5.9742 * 10**29
body2.px = 1*AU
body2.vy = -29.783 * 1000            # 29.783 km/sec
 
3:04 PM
@Kevin Since i don't know how to use async, i guess i'll wait.
 
sun is initially static
 
@ParitoshSingh But while you're waiting, you can do other things!
 
GUIWarning a slow running process has blocked the main thread, cannot respond.
 
@Kevin the warning is useful in general, but I have some coroutines that may or may not run depending on an external condition
 
@ReblochonMasque Thanks. Now that I've got a test case that I know the approximate outcome of, should be useful for debugging my simulator
 
3:05 PM
Unstable system are a lot more fun to watch!
 
@ReblochonMasque But turned into "here comes the sun" real quick.
tu do do do.
 
@holdenweb I was thinking more along the lines of generator.close - but without me doing it explicitly
 
not quick at all, for some reasons, turtle gets very, very slow after a little while!
My sim is also extremely very stupendously naive!
 
does anyone know how to suppress an Unresolved Reference on a specific line in PyCharm?
 
3:21 PM
@inspectorG4dget if you run the Code -> Inspect Code... you can directly disable checks generically, by file or by line
 
@ReblochonMasque What's the time frame for your simulation? How long does it take for things to go wobbly
 
With the settings I gave you, not long - maybe 20-30 years?
 
@MisterMiyagi I don't see a way in that window to disable a specific check on specific lines of a file. Could you elaborate, please? Maybe I'm blind
 
I am stepping daily
 
Me too, but the planets vanish off my screen on day 1
 
3:25 PM
hahaha
check the orders of magnitudes, maybe?
 
scratch that. I see the Ignore References window (widget? tab?). But I don't understand how to use it. I guess I'll ask 10 ** 10
 
Cheeky :P
 
@inspectorG4dget running the Inspect Code... should open an Inspection Results tab. you can select and disable them there.
 
I know what you were going for, so im going to let it stand :P (but power 100)
 
units are MKS, except velocities in km/s
Maybe you are in m/s?
 
3:27 PM
also, if you click on the offending code, a lightbulb should show up at the left side of the window. clicking on it gives a small menu that allows to disable the inspection as well
 
Yeah, I think I used the wrong unit around there.
Yep. Now they're orbiting the sun normally for the first year. I'll try a 20ish year timespan after lunch.
 
cool - bon apetit
 
@MisterMiyagi oooh! This is cool. Thanks
 
3:40 PM
'morning cabbage
 
wim
anyone else think xkcd quality is decreasing
not many of them have been funny recently, just meh, I wonder if randall is preoccupied with other things
 
4:00 PM
just looked at the current one... meh
 
I've gotten fewer chuckles out of recent ones.
"The author is losing his touch" and "I'm becoming more jaded and humorless" are equally plausible explanations
When describing the name resolution system to newbies, one might say "when you do print(x), Python looks in the current scope for x, and then moves outwards to enclosing scopes until it finds the variable or runs out of scopes".
Playing with dis, it seems like this usually happens at compile time - Python already knows exactly what scope x is in by the time the byte code is produced. Are there any situations where this is not the case? Is nested-scope-iteration name finding ever done at runtime?
 
there are only ever three choices and all are obvious at compile time - local, closure and global
 
4:16 PM
Compile-time scope resolution is incidentally why this code crashes:
z = 1
def g():
    z = 2
    del z
    def h():
        print(z)
    h()
g()
 
I don't think lexical scoping can ever produce an ambiguous situation
 
You'd have to solve the Halting Problem if you wanted to know at compile time which z still exists by the time h() runs
 
z exists. it just has no value.
 
For certain definitions of "exist"
I wouldn't be surprised if its key was still present in g's f_locals, pointing to NULL
or f_localsplus or wherever closed-upon variables live
I bet cells are involved. Still haven't gotten to that part in this Python internals tutorial I'm reading.
 
@Kevin indeed they are. You can inspect the __closure__ and see that the cell is there, but empty
def g():
    z: int
    def h():
        print(z)
    return h.__closure__
 
4:27 PM
Interesting, I didn't think a type annotation could affect scoping on its own.
 
4:37 PM
KevinScript implements closures by simply never deallocating any objects, ever. I should probably learn a thing or two about compile-time detection of lexical scoping if I ever want sane garbage collection.
 
4:49 PM
Ah, this tutorial has a fun snippet that lets you swap out the globals dict of a function: eval(func.__code__, new_dict_goes_here). I recall that @ParitoshSingh had a problem the other day and we were looking for a solution like this.
n = 999
def f():
    print(n > 7)

exec(f.__code__, {"n":3})
#result: False
Compare to exec("f()", {"f": f, "n":3}), which prints True
 
wim
5:12 PM
spotted in the wild, gvanrossum linked to an answer from antti bugs.python.org/msg291380
 
Nice
 
wim
@MisterMiyagi and builtin
 
@wim damn, I always forget about that one
 
wim
@Kevin wow, cool hack
 
Simple, yet effective
The builtins vs global distinction could be the basis of a lame riddle, along the lines of "when is it possible to access two differently-scoped variables with the same name?"
print(abs) #builtins namespace
abs = 1
print(abs) #global namespace
 
5:32 PM
@Kevin Oh that's a sweet find Kevin, awesome! This is perfect
 
Tadaa. This is a lame riddle because the documentation sometimes refers to globals+builtins as a single "top level namespace", for example the part of docs.python.org/3/reference/… that talks about the global statement
 
does anyone know if there are builtin types that release the GIL for some operations? say str, since it is immutable?
 
are you referring to creating a variable or even operations count?
(not that i know of any methods on say, lists or something that release the gil)
 
I mean something like my_str.split()
 
My understanding was that python went to great lengths to make all builtin operations atomic.
So that the GIL could actually be released freely, but never actually mess up anything.
But I am no authority on the subject, could be wrong too.
 
5:49 PM
Google tells me that the GIL got a facelift in 3.2 that made it less likely to thrash when multiple CPU cores are each trying to run a thread, but it still doesn't let you run two threads truly simultaneously.
That article was from 2010 though so maybe things have improved since then?
 
wim
I've got a very lame riddle vaguely related to recent discussion too
>>> class Potato:
...     # your one line of code here
...
>>> repr(Potato)
"<class 'Potato'>"
 
I don't think the GIL changed too much overall though, the articles i read on the topic a couple years back made it sound like it was just really tough to make the GIL be more liberal without sacrificing single core performance
 
wim
what do you put in that class namespace to get that repr?
 
@wim I am not sure whether to call the answer "obvious" or "WTF"
 
@wim Or maybe we're the jaded ones...
 
5:58 PM
If it helps, it's not obvious to me. I have no idea how repr actually works though :D
 
@ParitoshSingh Pretty much. And that's been Guido's guiding principle on not changing the GIL
 
@ParitoshSingh you don't have to change repr ;)
 
Sneaky answer: view spoiler
 
@ParitoshSingh I was thinking more along the lines of Cython's with nogil, but perhaps it was just my imagination playing tricks on me :/
 
6:00 PM
Hmm, there's supposed to be three spaces there... I wonder if that's a bug in my userscript, or a bug in the page
 
clever
 
If I had bothered to read another line of documentation, I might have come upon the less sneaky answer, view spoiler
 
wim
where can I find older archives for comp.lang.python? these only go back to 1999..
 
could you link to the documentation you're reading? I tried to find out how repr calls are made, but failed spectacularly.
 
That first spoilers rather funny, got Kevin'ed on the second tho
 
wim
6:07 PM
well done. I found the trick when spelunking in the pytest sources (spoiler)
 
@ParitoshSingh docs.python.org/3/reference/datamodel.html is always my first stop when I need to override default object behavior and/or utilize a double-underscore attribute
 
Ooh, i see. thanks!
Oh, i think i spot it too
 
I don't think you can completely deduce how repr() works from just that page though
 
EDIT: nvm got it.
 
Lunch cabbage
 
6:12 PM
@Kevin laurel! how did you, what even. haha
cbg!
 
Thought you could do it with __qualname__ too, but alas it doesn't work that way. :( It's just a fancy __name__.
 
It helps that I've been reading articles about the attributes of PyObjects all day, so I'm at the right frequency to think about tricking the interpreter
 
I'm happy to just have some of the wisdom passively rub off
 
Incidentally everything I've said about Python internals in the last two days may be completely wrong. Caution: may contain nuts.
 
Oh i finally see what you meant wim about the convo above being related
 
6:15 PM
I'm trying to converge towards the truth by adopting incrementally less wrong mental models as I go along
 
So I’m printing something in python and it’s coming out as ['crown' 'crown'] What does that mean? I expect it to just be a string of crown.
 
@MikeJenkins Almost looks like a list, except there's no comma.
 
Yeah! There is no comma.
 
I bet that's a numpy array
you should print type instead. that's more useful.
 
Coming from JS?
 
6:17 PM
@MikeJenkins I tend to do print(type(v), v, repr(v)) when I encounter things like this
 
Yes!
Good call, I'll try that.
 
Python won't automatically concatenate strings for you
 
Yay for python.
 
<class 'openfisca_core.indexed_enums.EnumArray'>
I'm not asking it to concatenate anything.
 
wim
@roganjosh yeah it will :P
 
6:18 PM
But, strangely, Python will automatically concatenate string literals:
>>> print("Hello, "    "World!")
Hello, World!
 
Ah. Okay. I wasn't right on numpy array then, sad me. :'(
 
With a comma involved :)
 
I've never accidentally broken my code by forgetting to put a comma between two string literals, no sir >_>
 
So how do I access my string?
 
Anyways, you still have a container then, something array-like. If you need just one string, you need to iterate one more level or access the element inside it.
Sadly, i don't specifically know anything about this particular type of object, but i presume it supports indexing or iteration
 
6:20 PM
I've done a bad. I'll shut up, sorry.
 
If you only want to print the first element of the object, print(the_object[0]) ought to do it
 
^ basically this.
 
Skimming through openfisca.org/doc/openfisca-python-api/enum_array.html, that might end up printing an integer rather than "crown", though. Let's wait and see.
 
wim
>>> ast.dump(ast.parse('"abc"'))
"Module(body=[Expr(value=Str(s='abc'))])"
>>> ast.dump(ast.parse('f"abc"'))
"Module(body=[Expr(value=JoinedStr(values=[Str(s='abc')]))])"
what is a JoinedStr
 
[redacted]
 
wim
6:23 PM
surprised it doesn't collapse to a normal Str when there is nothing to format
 
Yeah. I get "ProcurementType.crown"
 
Wild guess: try print(the_object.decode_to_str()[0])
 
Essentially, now that you know the type of object you're getting, you can quickly consult the docs and get whatever you need
Kevin already linked them above
 
Yeah. I just haven't pythoned in a while. :P
 
To be fair, this isn't exactly native python, since libraries and custom objects are involved.
 
6:27 PM
.decode_to_str()[0] is the winner. :D
Thank you. Saved me some head banging time.
 
6:43 PM
github.com/python/cpython/blob/… suggests that JoinedStr occurs if an f string contains "any literals", which I assume means "anything outside of a curly bracket". So I'm surprised that ast.dump(ast.parse('f"{1}"')) also gives a JoinedStr.
 
Literal 1?
 
I thought that would qualify under a FormattedValue node if there's just an f-string (with no leading or trailing literals) so I don't know why the FormattedValue is being nested inside a JoinedStr
 
ast.dump(ast.parse('f"{int()}"')) ?
Now we know what we trained for the other day
 
@AndrasDeak Worth a shot, but that's a JoinedStr too: "Module(body=[Expr(value=JoinedStr(values=[FormattedValue(value=Call(func=Name(id='int', ctx=Load()), args=[], keywords=[]), conversion=-1, format_spec=None)]))])"
 
Nice and pure...
Challenge: find anything that doesn't do that
Empty f-string perhaps :D
 
6:49 PM
My suspicion is that all f strings compile to JoinedStr nodes. I'd love to be wrong though.
>>> ast.dump(ast.parse('f""'))
'Module(body=[Expr(value=JoinedStr(values=[]))])'
 
Okay, that's as smoking a gun as it gets
 
f strings behave like ''.join'ing the string parts and expressions
have a look at dis.dis("""f'abc{a}def'""")
interestingly enough f'' is not a constant, but f'a' is
 
I'm filing this under "behaves wackily because this is a newish feature and doing it the 'right' way is way down our list of priorities"
 
for the people with Python3.8.... does f'{b:=3}' work?
@Kevin IIRC the optimiser runs after the AST is built
as far as the AST is concerned, an f-string is an JoinedStr
 
wim
7:10 PM
@MisterMiyagi nope
unhandled NameError
 
hey
say you build a python project
ie multiple code files
how would you package it up to distribute? like compiled code so that noone can fiddle with the code?
 
you could run it and send out the .pyc/.pyo files. But you might run into architecture dependency issues that way. All packages submitted to pyPI are open source, so you could technically fiddle with anyone's code on your machine.
Why the restriction?
 
Even compiled code can be fiddled with. This is true of all programming languages.
If the bad guy has physical access to the computer running the code, and an unlimited amount of gumption, you're doomed
 
That.
@Permian so it depends on how zesty you are about keeping the code private. If it really matters you should just be SaaS.
Otherwise, don't even worry about it, your software isn't that important anyway :P
 
wim
@Permian impossible
 
We know that protection of code is difficult because triple-A game companies spend plenty of R&D on DRM, and their schemes are regularly cracked within a month of product release
 
Source code for an in-house language with zero publicly available documentation would be hard to decipher I'd guess. Specifically if it was minified like some JS code I've seen. It could be viewed but how would anyone ever make sense of it
Not that they'd be using some custom private language, but if so, they might worry less about who sees what.
 
8:49 PM
Arguably one could unminify js code with dictionary words for var and function names, then try figuring out what happens
It wouldn't be great but doesn't need NSA levels of motivation, I'd think
I guess just an instance of security through obscurity (which doesn't work)
 
 
1 hour later…
10:02 PM
@AndrasDeak Not knowing the language paradigm would make the task more challenging as well. My mind immediately began to make a portmanteau of security and obscurity but then I realized that obscurity is naturally a portmanteau of the two words, neat.
 

« first day (3233 days earlier)      last day (1699 days later) »