« first day (4106 days earlier)      last day (1067 days later) » 

00:38
Sharing horrible jokes is become something of a trademark for me :D
 
1 hour later…
01:51
Looking for some validation that I still remember some grade school math. Here is a picture of the sun. If the width of the picture is 1.0, what is the radius of the sun? And what would be the diameter (or radius) of the earth? (Image comes from this YouTube video, which is really rather soothing - 44 minutes of Solar Observatory video + woo woo music) youtube.com/watch?v=joIPg887g1A
 
5 hours later…
06:38
:53807519 will dbus work if I want to start my thing as a service from systemd ?
I did post somewhere the entire code ... where;s the latest just before I gave up on pyobex:
#!/usr/bin/python

import bluetooth
from PyOBEX.client import Client
import sys
import os.path
import sys
import signal
from datetime import datetime
#import time

#time.sleep(100)

def cleanup(signum, stack):
print("Failed : ")
for y in failed:
print(y)
print("Succeded : ")
for x in done:
print(x)
sys.exit()

signal.signal(signal.SIGTERM, cleanup)
The RPi Zero on which I want to run it on does not even have a gui ... it'a a text console only (RPiOS lite) system.
Sorry for the indentation ... I did CTR^K but it seems it did not show it correctly anyway
When I realized it was too late to try and mend it with edit
07:20
Why this warning? MatplotlibDeprecationWarning: Support for passing numbers through unit converters is deprecated since 3.5 and support will be removed two minor releases later; use Axis.convert_units instead.
ax.set_xticks([])
08:20
@Aran-Fey I've been playing around with ctypedef struct PyTypeObject yesterday to understand the special methods. I'm pretty certain it's impossible to accurately replicate special method lookup without accessing interpreter details, e.g. via ctypes.
The CPython interpreter directly accesses the C slot, it doesn't bother with MROs or any such fancy stuff.
I'm this close to asking a question on SO main...
One can probably work around this for all special methods that always exist and thus have a slot wrapper on object, like object.__init__. I'm stumped how it would work for conditional methods such as klass.__len__, and I guess it's impossible to create custom special methods.
I'm not too worried about dundermethod lookup, grabbing it from the MRO is good enough for me. I just wish there was a way to access the __dict__...
Is there even a tangible difference between extracting the dundermethod from the MRO and the way CPython does it? Can you trick it into doing something "wrong"?
I'm not sure, TBH. I guess just accessing the MRO could trigger all sorts of side-effects, like our descriptor-descriptor-descriptor-... problem.
08:36
Hmm, I don't think so, since type has all the relevant slots. I get the MRO with type.__dict__['__mro__'].__get__(cls), and the class dict with type.__dict__['__dict__'].__get__(cls). And then I just grab the descriptor __get__ from the MRO and call it. No recursive shenanigans.
class Descriptor:
    __get__ = property(lambda _: (lambda: 5))

class Demo:
    __len__ = Descriptor()

demo = Demo()
print(len(demo))  # TypeError: 'property' object is not callable
CPython doesn't even care if it's a descriptor, it just calls the __get__
@MisterMiyagi I seem to remember suggesting as much.
But it wouldn't be the first time I'd been wrong. Fortunately it hasn't been fatal so far.
I hope it stays that way. :P
Either way, it's one of those things for which looking under the cover is more educational than knowing the answer.
And more madness inducing... :/
@Aran-Fey I'm just not sure if "just grab the descriptor" is even possible.
In CPython, they really just fetch a C function pointer and call that.
self is passed explicitly as well.
To what? To the __get__?
08:52
Whatever object/type put into the slot when building the class. :/
Into which slot, though? This evidently isn't the case for all dundermethods, as you can see in the code I posted earlier - it doesn't call the Descriptor with demo as the first argument. It does call Descriptor.__get__ with the descriptor as the first argument though.
As far as I can tell, the only thing where there can potentially be a difference is the obtaining of the dundermethod and/or the __get__. In other words, there would have to be a discrepancy between what CPython stored in the slot, and the first object we find if we loop through the MRO. And since there really aren't many ways to modify class attributes, this doesn't seem terribly difficult to test
There are essentially only 3 situations when CPython needs to update this slot:
1. When you explicitly define a dundermethod inside a class
2. When you inherit from at least 2 base classes
3. When you assign an attribute to the class
4. When you delete an attribute from the class
09:19
Hm, that's true. The C-API docs make mention that the slots are inherited.
Is there a way to modify a class's __dict__ other than assigning and deleting an attribute? You can't access the dict directly, only a read-only wrapper, right?
And even if you return a dict from __prepare__, python copies it as far as I know
I thought classes could use custom types for their __dict__, but I haven't checked it.
I'm currently trying to figure out why len invokes your descriptor. ^^
If you mean "I'm inspecting the C code to figure out where this happens", I have no clue. If you mean "I want to know why this invokes descriptors", it's probably because some methods are (automatically) turned into staticmethods or classmethods. __new__ is a staticmethod, for example. So python really doesn't have much of a choice there. It finds a descriptor, it invokes it
Hmm, __new__ is actually not a real staticmethod. It's only treated as such. __init_subclass__ however really becomes a classmethod
09:40
As far as I could piece it together, __new__ is "static" because its descriptor just isn't invoked.
It's option A, by the way. And sadly.
len effectively invokes Py_TYPE(o)->tp_as_sequence->sq_length(o); but I'm not quite sure what is in the slot to begin with.
Well now I'm completely confused
class Descriptor:
    __get__ = property(lambda _: doesnt_matter)

class Demo:
    __new__ = Descriptor()

demo = Demo()  # TypeError: 'property' object is not callable
It still invokes the descriptor ._.
Did you check what parameters are passed in?
class Descriptor:
    def __get__(self, instance, owner):
        print("__get__", instance, owner)
        return self.pingpong

    def pingpong(self, *args, **kwargs):
        print(args, kwargs)
        return 1

class Demo:
    __new__ = Descriptor()

demo = Demo()
# __get__ None <class '__main__.Demo'>
# (<class '__main__.Demo'>,) {}
Nothing out of the ordinary there
Indeed. That looks pretty much the same as one would do it in pure Python.
I thought maybe this is a special case because it noticed that __new__ isn't callable, but making the descriptor callable didn't change anything
09:52
It's just Demo.__new__(Demo)
That's... wow
> __new__() is a static method (special-cased so you need not declare it as such)
And by "special-cased" they mean "we do literally nothing"
Class __dict__s are normally mapping_proxy objects, whose emergence is documented in detail in this bug report.
@MisterMiyagi (The above was supposed to be the reply).
@holdenweb Thanks, much appreciated!
Spelunking Python's history can be fun, but honestly some of the discussions just go too deep and assume too much background for me to follow. There are only so many hours in the day.
There still has to be a mutable mapping hidden behind that MappingProxy, but I don't think there's a way to access it. The docs for __prepare__ say that the class namespace is copied into a fresh dict, so you can neither choose what kind of mapping it is, nor can you hold a reference to it
10:04
I seem to have missed that. Thanks for pointing it out.
Is "conditonal import" antipattern?
Depends. In most cases probably not, but there are certainly ways to do it poorly
10:24
TIL that cpyext provides all the type slots in PyPy. I'll probably go for Cython, then...
Hi, anyone can help me on placing a frame on the bottom using grid? I just realized I've mixed `.grid()` and `.pack()` and it's also why my buttons couldn't be moved to specific columns properly. I'm using `.grid()` to create my frame to put the buttons and now the frame wouldn't expand compared to using `.pack()`

Snippet: https://paste.pythondiscord.com/imafohadeb.rb
Would be nice if we didn't need pygame and 3 icons just to play around with a tkinter problem
10:40
ohh right haha i'll change it so that you guys can test it, my bad
Snippet (without pygame and images): paste.pythondiscord.com/yecedabahu.rb
So you want the buttons to grow horizontally? If yes, how much? Across the entire window?
Also, you seem to misunderstand how grid works. Rows and columns in a grid can have different sizes. The audio button is in column 2, but there's no space between the buttons because column 1 is empty.
yes, across the screen, even when the window is maximized. Something that .pack(side=tk.BOTTOM, fill='x') does
My bad I'll just rephrase my question. I wanted the audio button to move to the far right or being moved to specific column, it couldn't because as you said, there's nothing in between.
So for example, I need the speaker icon to move to the right at specific position, but I can't position without having something in between to push it to the right.

Screenshot: https://imgur.com/a/fu6QbPO
10:56
Let's start with the frame. You have to 1) make it sticky='NSEW' and 2) allow its column to expand. With self.grid_columnconfigure(1, weight=1) you've told tkinter to assign all extra space to column 1, so column 0 can't grow.
Honestly, I don't see why the window uses grid instead of pack. You have the video on top and the buttons on bottom. pack can do that much more conveniently than grid
Same thing goes for the button frame, really. You're arranging the buttons in a straight line. Why do that with grid?
I actually don't know a good way to create empty space between the buttons. I think you'll just have to put an invisible widget there, like a frame
I'm not sure if this is the right way to do it but I initially use .pack() to create that frame and then increase the padx value using .grid() for the audio button, that works but then I was told that padx just increases the border
Ah right, pack can't do empty space between widgets
Tkinter is such a joke
 
2 hours later…
13:05
@PaulMcG You don't have enough info to get the actual radius of the Sun (or the Earth) from that picture, but you can find the Sun's radius relative to the picture's dimensions.
You have a segment of a circle. You can find the radius via Pythagoras. (I'll use ^ for exponents). From the sketch below, u^2 + y^2 = r^2 and r = y + v where u & v are known. Substituting y = r - v & rearranging, we get r = (u^2 + v^2) / (2*v)
Note that r isn't quite the full radius of the Sun. If d is the centre-to-centre distance between the Sun & Earth, and theta is the angular diameter of the Sun (about 0.53°), then 2r = d * sin(theta).
See astronomy.stackexchange.com/a/47731/16685 for some relevant sketches.
How do we know v? Would you have to actually measure the image?
Actually, d is the distance from the observer to the centre of the Sun. Of course, that doesn't make much difference at this scale. ;)
@MattDMo Yes. You measure u & v directly off the image.
OK. Well, we know u is 0.5 because the image is 1.0 across. I was trying to figure it out just based on that, I didn't measure v.
The "canonical link" in the meta should work well for c/p.
I forgot my password to sign in to the Apple store so went through the rigmarole of resetting it. That involved multiple codes sent by text, then an email code, then a 24 hour wait to receive another email that tells me they'll text me my recovery code to my number they've already validated.... on the 25th Jan! What's that about?!
A different way of thinking
I just want to install their terrible version of Excel so that I can read spreadsheets :'(
@roganjosh that sweet exclusive luxury experience
14:03
"Only a heathen would forget their Apple ID password!"
Have you tried, like, just buying a new Mac and creating a new account?
4
I wouldn't have forgotten it if the App store had loaded more than a blank white screen for the last 6 months :/ I got so excited when I accidentally clicked the icon and saw that it actually loaded, only to immediately lock myself out
You could still use your old mac to track your enemies
Yeah, I think a new purchase is the only way forward with this one
@AndrasDeak Advice noted and acted upon. Thanks
14:18
Why not use the canonical [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) instead?
14:30
Any of y'all write Android or iOS apps and open for consulting?
@duhaime Have you tried room 15 by any chance ?
I wanted to start here because these are my people
14:48
I know one of our regulars does Android dev (& he has gold Android & Java badges), but he hasn't been around for a few weeks.
14:59
@MattDMo I think the text and link is fine for highlighting. No need for additional formatting. The ones that get the message get it either way.
15:26
Huh, I just realized you can't inherit from multiple base classes that have __slots__
But you can inherit from a class with __slots__ and a class "without" __slots__, even though that class implicitly gets a __dict__ and a __weakref__ slot
Eh, best not dwell on it
 
2 hours later…
17:24
@Aran-Fey you can inherit from multiple base classes with __slots__ specified — but only if all but one of the bases has __slots__ set to an empty tuple
17:34
I guess I phrased it poorly. I was thinking in terms of slot descriptors, so a class with an empty __slots__ tuple wouldn't count as a "class with slots"
Interestingly, if you use multiple inheritance to create a class with 2 __dict__ descriptors, they both do the same thing:
>>> class Foo: pass
...
>>> class Bar: pass
...
>>> class FooBar(Foo, Bar): pass
...
>>> foobar = FooBar()
>>> foobar.attr = 5
>>> Foo.__dict__['__dict__'].__get__(foobar)
{'attr': 5}
>>> Bar.__dict__['__dict__'].__get__(foobar)
{'attr': 5}
 
2 hours later…
19:21
@PM2Ring Ha, yes! Given that we are just back-of-the-enveloping (and measuring on a fuzzy outline of the sun's image), I think we are in the ballpark.
@PM2Ring Yes, I was looking at getting the radius of the sun in some dimensionless value, and then googling the actual radii of the two. Measuring from the image, I get 0.3 for v, and as @MattDMo says, u=0.5. From your analysis, rᵢₘ ≅ 0.57. The google gives us rₛ ≅ 430,000 miles, rₑ ≅ 4000 miles. Rounding, rₛ ≅ 110rₑ , so in image units, rₑ = rₛ / 110 = 0.005. So in this image, the earth's diameter is about 0.01, or 1/100 the width of the image.
Was the Earth in the first picture? If it was, I totally didn't see it
it was hidden behind the gorilla
It wasn't - I added it for reference in the second
I never get tired of looking at pictures like that. Movies are even cooler...
19:39
My previous post linked to the YouTube video.
 
1 hour later…
20:45
Is there a function apply such that apply(f, x) = f(x) in the Python standard library? I thought I saw it once but can't find it (I looked under functools).
Pretty sure there isn't. What do you need that for?
I mean, functools partial is kind of what you want but also... why do you want that?
def apply(f, x):
    return f(x)
I mean... I don't know why you would want that
because you're literally just trading one line of code for another line of code
Making some dysfunctional code more functional? :P
I'm using this combinator a lot in my code (along with multi-argument map). I can easily implement it myself, of course, but I was wondering if it already existed.
def apply(*args):
    return (args:=list(args)).pop(0)(*args)
also works for n-ary functions
20:59
For example, using map(apply, fs, xs, ys, zs) rather than (f(x, y, z) for f, x, y, z in zip(fs, xs, ys, zs)).
you could probably use argument unpacking to simplify that a bit, but the tradeoff might eat your simplification
There was an apply function in early Python 2, but it was removed. python-reference.readthedocs.io/en/latest/docs/functions/…
That might be where I'm remembering it from.
Something like [f(*args) for f, args in zip(fs, zip(xs, ys, zs))]
21:12
That's good.
Alternatively, don't store the arguments in 3 separate iterables to begin with
21:22
The opening paragraph of en.wikipedia.org/wiki/Apply seems to indicate that apply is pretty important in languages using a functional paradigm. Python is multiparadigm, and it's about 13% functional by volume. Too little to justify an apply function in the stdlib, but large enough to allow the user to build their own equivalent if they really want to.
@user76284 Python 3.11 will include call() in the operator module that will do this. docs.python.org/3.11/library/…
the future is now
It's good to see the combination of modern technology and the age-old Python tradition of naming things differently.
Cool, next they should do call/cc
You might also look at operator.methodcaller docs.python.org/3.11/library/… (In ignorance, I wrote my own version of this at my last job, and my boss just looked at me, like ...)
methodcaller is not new though.
I'm looking forward to seeing how people will use that to avoid opting for a clear comprehension
21:34
Guido was never a fan of the functional stuff. IIRC, apply was dropped at the same time that reduce got moved into functools.
Wim likes to recall that Guido called functools a dumping ground developers.slashdot.org/…
Adding call to operator kind of makes sense, though. It has versions of all the usual dunder methods.
I guess
22:20
Does anyone have a clean, legit case where they've had to use global? I actually don't have a single example in my code but, in the interest of a "balanced" argument (this person needs to rip global out of their code ASAP) I'm curious if there's a good use-case in the wild
something with callbacks perhaps
also watch out because you often have globals without using globals, if you have mutable containers
I thought as much. So, straying into tkinter et al (if we stick with just python)?
I'd wait for a proper python dev to answer, but that's where I'd start. In non-callback situations you usually have the option of actually returning stuff from a function.
The one use case I think of is if you want to initialize some global thing on demand. For example, create a requests.Session() the first time you make a HTTP request
@roganjosh had? No. Potentially 100% of the time I've used global it's just been out of convenience.
22:23
@Aran-Fey do you read that as ha te te pe? :)
What gave it away? The "a" in front?
yeah, for the second time in two days I think
@WayneWerner I'd like to think you know what you're doing here, though :P But, fair point, I wasn't clear on that
And we do the same thing in Hungarian. Took me forever to stop reading API as a pee.
That's why I was surprised to learn that even Anglo-Saxons read GUI the way we do.
@Aran-Fey you can pass that session around, though, or make it GLOBAL in the module?
22:26
globals are just module level class-level variables. They can be useful, but often times they're just abused.
Honestly, the pronunciation of "h" is weird. My brain refuses to accept that it needs to put an "an" in front
@roganjosh nice use of MIYAGICASE
there are very very few instances where global data improves readability. TBH, I find this the case even within classes. My personal approach follows the "ask for what you need" (or demand) style
I think the last time I used global, it was in fact within a tkinter callback.
@roganjosh You can create it as a global constant, but maybe you don't want to instantiate a Session at all if you don't have to
22:27
@WayneWerner I doubt that it ever improves readability. I can only imagine that in some situations it's borderline inevitable.
This problem is almost ritualistic abuse. Almost every function now has 3 or 4 names declared global. I've already gone through the code with them once and stamped them all out, and now the new code is just using them again
Like... if I have a function that is making a database call, it won't ever create a database. It will be something like def get_something(*, database, thingy, maybe_other_thingy):
@roganjosh ugh
whatever knows about get_something is gonna know that it needs a database connection passed in
@roganjosh oof. My other experience is that it's a sign of lazy programming
(or, newbies)
It's someone coming from R
22:30
I think "there is no acceptable use case for global" is an acceptable white lie
I'd expect that most of those 3-4 globals are actually superfluous, and it's more of a cargo cult thing
Namespaces? What are namespaces?
coming from R? Yeah, I'd agree with Andras here :)
@WayneWerner I don't see your point
can you explain how that relates to globals?
They are totally superfluous, but I already know that this becomes such a tight knot that, in the last encounter, I couldn't unpick it after an hour straight so I just re-wrote the whole module with them from scratch
22:31
Sometimes when I need easily accessible mutable state in my tkinter programs, I'll put the whole thing inside a MyCoolApplication class, and create exactly one instance of it per program lifetime. But sometimes it feels like unnecessary hoop-jumping and I'll use global instead
@roganjosh just delete every global statement and iterate the code in Vigil
@Kevin I once saw someone opting for an empty-or-single-element list in the global scope to "avoid using globals"
:-/
@AndrasDeak some people would use global connection - or whatever the equivalent was for their domain
Out of curiosity, how long has this person been a developer for?
Define "developer"
22:33
"paid to write code for" :)
@WayneWerner would that have to be a global?
it's not you, it's me: I don't know databases at all
@roganjosh How long have they been torturing you with their incompetence?
No - that's my point. Some folks are lazy (or new/ignorant) so they'll reach for the convenient thing: global state
and rather than passing functions what they need, the functions just grab the state out of the global state
But you only need global statement when you do more than read or mutate
So, nearly 2 years in the current position, but they have another position of 4 years before that with SQL so I'm not sure what that involved
22:35
still not great, but already a different level of subtlety than what roganjosh is fighting with
Oh wow, that's a lot longer than I expected
first he has to fight the "please no global statement" fight, and then he might have to fight the "please no global spaghetti state" fight
Yeah - my example isn't a very good one because I don't usually have the problem where I'm trying to make one thing happen in two different places...
OK, just wanted to understand your example. Thanks.
that's really what globals end out doing is like... if you have problem A but you artificially split it out into functions B and C
(because it should just be one function)
22:38
How to avoid using global in one simple step: Write all your code in the global scope (:
there are probably other reasons that folks reach for the global hammer... I need to hang out with some more novice developers and watch them solve problems lol
I think I have enough ammunition with the tkinter callbacks. I know they won't be familiar with them at all, but clearly "just don't ever use global" won't work and, given that it does exist, it sounds somewhat unreasonable for me to say that it's a non-feature
@Aran-Fey note to self: if I ever want to write intentionally horrible code I must use multiple "__name__ == "__main__" guards all over the global scope
I shall try again
@roganjosh if you had examples that you could share, one might have some better responses
22:41
if __name__ == '__main__': is overrated. Real devs use if __name__ != Path(__file__).stem:
3
@roganjosh you can try the angle of "non-feature when you have the option to return things from a function (i.e. almost always)" and "lack of globals makes your function testable Which is Very Important"
I don't think there's a reasonable example I could give because it'll jump between so many functions and I'd have to redact so much. It's just someone not understanding the flow of returning from a function and then passing values as arguments to the next function
@Aran-Fey I find myself doing the inverse along the Z axis of this. Specifically, I just write my code as functions in modules and avoid classes. But I explicitly pass arguments to my functions, and expect them to return the results, so there's not any global state
sounds like a normal way of writing code
@roganjosh that kind of goes to my argument - I can't think of any good bad examples because I'm so used to saying, "oh, this is the responsibility of function X" instead of trying to do something in several different functions
22:43
also tell him about spaghetti code
Good bad example: remove every argument to the function so that there's nothing in the function signature. Make every name global. Do this for 10 functions.
I gotta say my favorite horrifying example though was my first job where a developer there created a Class. Well, the Class. There was one instance of it, and it contained everything. There was a collection of Shipments and when you wanted to select one you would put one of them in the Class.selectedShipment and literally everything in the program from client to server side expected to get that Class and its selectedShipment.
We passed the instance to the server and back for any request we wanted to make
I tried to unwind the application and make it even remotely sensible but that actually would have required a complete rewrite - literally every function was expecting that monstrosity.
Since this person has already been committing crimes against humanity for 2 years, it might be worth a shot to dig up one of their old crime scenes and force them to look at it. "You wrote this 2 years ago. Do you think this is easy to understand?"
They're writing it now so I don't need much digging
"this is a month old - is it easy to follow?"
It's also useful to give examples of atrocities next to well-written code
"Out of these two examples, which one is easier to follow and understand?"
22:47
@WayneWerner you know it's good when it's a named pattern
@roganjosh The difference is that the freshly written code is still fresh in their memory. If you ask "Do you think this is easy to understand?" the answer will be "yes". But if the code is 2 years old? That's a different story
Every module is numbered; there is no coherence in the program. 01_my_module.py runs, then 02_my_module_analysis.py etc. Internally, the modules are full of globals
@AndrasDeak Well, I definitely was cursing someone when I was dealing with that object /:-)
@roganjosh it's full of stars
@WayneWerner get this man in Marketing, stat!
@roganjosh I don't know if R is similar but I could totally see a professionally untrained MATLAB user do that
22:49
@roganjosh coincidentally, the author of my god object ended out going to an entirely different department (-:
except in MATLAB you can't just throw functions all over the place (or maybe you can these days?), so the specific global problem wouldn't materialise easily
I could also see people socialised on jupyter notebooks commit similar crimes more easily
that might just be anti-Jovyan prejudice on my part
Trying to get stuff moved from jupyter into a workflow is another headache :/
just ban the use of jupyter, problem solved :P
Oh god, if only...!
I'm probably guilty of that in a Jupyter notebook - but also I've only done those as short-lived examples. Mostly it's just stuff like:

x = do_something()
y = do_something(x)
z = do_something(x,y)
22:57
There's a difference, though. I can, if I get cornered, barf out 1000 lines of code in a day to try get at what I want. I, and I'm pretty sure you, know that at the end of the horrid experiment, we can condense the outcome into something reasonable. That last part doesn't exist in some cases
@roganjosh This is COBOL being written in Python
Had the same thought - just had a conversation in work about globals and Cobol
@WayneWerner This too is a well-known COBOL "pattern"
Passing that beast around gives cover for the "but I'm not using globals, just function parameters" argument. (At least it used to.)
One situation I sometimes use a global is in a recursive generator, and I want to know the total number of recursive calls. Each call increments a global counter.
23:04
@PaulMcG I guess that's where R takes its inspiration, then, once you try to put it in production. I know they can't program COBOL but that seems to be the R way these days
It just translates so poorly to Python. This seems like the most relatable example to me @PM2Ring, thanks
good luck getting "recursive generator" past your guy
"Look, I'm not being totally unreasonable. You'd absolutely have a reason to use this with a recursive generator. I'm just saying; maybe we should not be using global here"
Diplomacy +1 for roganjosh
Admirable. After 2 years I would be on the warpath
I looked up their linkedin for those timings. I haven't been dealing for it for that long, but I happened to pick up their github and notice that all the code I rewrote is now baked into more code exhibiting the exact problems I wrote out of the original problem code
23:13
You don't need global for that counter, but it's a lot cleaner than (for example) passing in the counter as a 1 item list. To make it modular, you can attach it as a function attribute. Or wrap the function & use a nonlocal. I think that's what lru_cache does for its cache_info() docs.python.org/3/library/functools.html#functools.lru_cache
It's also possible that they're still stuck in the "code just needs to work" mentality that beginners tend to have. Maybe something like "Look, our goal isn't just to write code that works. Our goal is to write code that's easy to read and modify" will get through to them
I'll try. I think I was quite taken aback by the fact that I specifically said "do not use globals" then showed exactly how to avoid it for quite a lengthy session out of the blue, only for it to revert back. Anyway, I've prattled on enough
Especially in Python. We primarily optimize for fast readability & maintainability, not execution speed.
Well, the code that uses globals doesn't work. So speed isn't a factor
23:40
Hmm, apparently classmethod and staticmethod have a __wrapped__ attribute now. That's kinda weird, considering they aren't even callable
>>> classmethod(len).__wrapped__
<built-in function len>
Surely all decorators are callable?
Heh, well, depends on what exactly you're talking about. The decorator itself is of course callable, but its return value isn't necessarily
I don't understand ~"they aren't even callable" - len is surely callable?
I understand decorators aren't obliged to return a callable.
classmethod(len) isn't callable
Ah, gotcha.
23:50
@Aran-Fey because it's a descriptor?
Well, not because it's a descriptor, but... yes
Heh, OK. Half credit.
(I understand that descriptors are allowed to be callable)
>>> @classmethod
... def f(x):
...     return x
...
>>> f(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'classmethod' object is not callable
>>> type(f)
<class 'classmethod'>
>>> class A:
...   @classmethod
...   def f(cls, x):
...     return x
...
>>> type(A.f)
<class 'method'>
>>> A.f(42)
42
It's possible the metaclass does something special to turn classmethods into methods?
Come to think of it, it takes a lot of effort to resolve foo.bar. No wonder Python is slow.
@holdenweb descriptor protocol makes A.f return a (classified) method
@holdenweb Are you familiar with descriptors? The metaclass has nothing to do with it
23:56
I'm glad you chose yesterday to teach me descriptors :P
Ah, I observe the __get__ method's presence on A.f. And also on f.
There certainly has been a lot of descriptor talk recently haha
Now I'm one of the cool kids
>>> f.__get__(f)
<bound method f of <class 'classmethod'>>

« first day (4106 days earlier)      last day (1067 days later) »