« first day (3131 days earlier)      last day (1809 days later) » 

3:05 PM
Although, I do have a more philosophical question. In order to use @group_required(['Master']) on view functions, all of this needs to work together. That's feeling very un-unit-y. At the same time, not testing it as a whole makes me think that's not a good test. Should I be testing each component separately?
 
It's interesting that the Python docs call = the "assignment operator" even though it is unlike most other operators in a number of ways
e.g. The LHS can't contain arbitrary expressions, you can't stick it anywhere an expression could usually go, etc
 
Cbg all
Was PyObject_Malloc removed at some point during python 3.x?
 
cbg
 
I guess it's hard to borrow a formal term for it from mathematics since the language of proofs doesn't have a rich grammar for mutable state
Even "let x equal 2" is more like a with ... as than an assignment
@OldTinfoil It's still in the C api documentation, at the very least: docs.python.org/3/c-api/memory.html#c.PyObject_Malloc
Or are you saying "was it removed briefly, and then reinstated?"? That I do not know.
 
Thanks, rooting through the cpython source was apparently the wrong place to be
Now to figure out why this autoconf script is whining about not being able to find it
 
3:15 PM
Searching through Python's github repository can occasionally give the impression that a function declaration/definition doesn't exist, if its name is constructed via preprocessor trickery
 
Good to know
 
Last month I was trying to find something with a name like u64_dothing and that literal name does not have a definition because a whole suite of dothing methods were all defined in one go by a macro that looked like [DATATYPE]_dothing
 
Bah, time to leave the office
Cheers for the help Kevin
Do you often deep dive into a python's innards?
 
Once a week or so. Usually when I'm about to make a public statement about how Python works under the hood, and I get the creeping feeling that I'm about to put my foot in my mouth
For example my most recent foray was related to when exactly an object's refcount gets reduced when a new assignment unbinds it from its only name
I have never written a line of C in my life so the process is much like trying to read Italian when you only know French
(Or is it like trying to read French when you only know Italian? Exercise: determine whether "Italian : French :: C : C++" is more accurate than "French : Italian :: C : C++", and provide arguments backing up your claim)
 
How @Kevin deep dives into Python's innards
 
3:31 PM
Is that from Princess Bride?
 
Yes
 
3:45 PM
Programmers of Unusual Pedantry? I don't think they exist. [I am immediately full-body-tackled by a man yelling "Well Actually"]
 
As much as I love The Princess Bride, that GIF is starting to get annoying. But hopefully it'll soon scroll out of view, I don't want to send it to the Rotating Knives.
 
i can help with that
 
Oh good. :)
 
There, it's off my screen. Anyone that can still see the gif is advised to buy a smaller monitor.
 
4:04 PM
It seems that pit is full of Vanilla.
 
It seems that my gif contribution left the room stunned and chatting ceased until @PM2Ring became annoyed with the animation (-:
btw I'm on #TeamRedPanda
 
@Kevin chinchillin' out
 
Unless that's a fox then I'm on #TeamRedFox
 
definitely red panda
you of all people should know pandas
 
Those animals are, from the top down: red panda, sugar glider, chinchilla.
 
4:07 PM
shhh, please keep it down
Sugar Glider?! Ok looking that up
 
sugar glider?
 
yup, they're adorable
they can even yamming fly (sort of :P)
 
I've never had a chinchilla as a pet but the ones I've seen are so skittish that I've been turned off the idea of ever having one.
 
lol...poeple ask strange questions
 
Ball of fluffs. But I'm not sure they are very petlike. If you want a great rodent pet, get a rat :) They are amazing. But they need rat pals and a lot of attention if you want them to be happy.
 
4:13 PM
Rats are amazing :)
 
Even though sugar gliders are native to Australia, I've never seen one in the wild. They're nocturnal, and mostly stay up in the canopy.
 
If I don't care about their happiness, do they still make great pets?
 
Did you have rats?
 
@piRSquared no, get a goldfish then :P
@Hakaishin yes, but just the one, and I didn't have enough time for him :(
 
Long-shot math Q: I've got four 2d vectors, A B C and D. I want to perform one scaling, one rotation about the origin, and one translation, so that A becomes C and B becomes D. I can calculate the necessary angles/scales/deltas manually, but is there an easier way? I don't necessarily need the individual rotation/scaling/translation matrices, I'd be happy with the product of the three.
 
4:15 PM
@piRSquared: They become like your family, need attention
 
My sister had a rat. I admit, they are super smart and social. They can even be downright cuddly.
 
Sugar gliders are also found in New Guinea, and a few other islands to our north. It's illegal to keep them as pets here, but that's not the case outside Australia.
 
@AndrasDeak goldfish are the worst. Pointless pet. Should be called not_able_to_pet
 
My step sister had 4-5 not sure, but they are really fun to play with, they're also smart animals
 
I could try to solve [a and b] * [scaling matrix] * [rotation matrix] * [translation matrix] = [c and d] symbolically for theta/scale_val/delta_x/delta_y, but that's like O(N^4) so I don't want to if someone already did it in the 17th century
 
4:17 PM
@Kevin you have M*A = C and M*B = D which can give you 4 linear equations for the components of M...
 
Q: why do we call smarmy people or those who inform on others rats. Seems unfair to rats.
 
there's probably a smarter way
 
I had a Pomeranian, who needed to be woken up whenever there was an Earthquake.
Even though he was a dog, he would just keep sleeping.
And, we had to save him upon listening to his screaming as a male-cat would often beat him
 
Pomeranians are fluffy rats that forged doguments to get into the kennel club.
5
 
Google suggests that "to rat out" originates from the idea of rats fleeing a sinking ship. So it's not "one that informs on others" specifically but rather "one that abandons their associates"
 
4:21 PM
I totally agree, they are not dogs!
 
So in its original formulation you could be a rat for behavior not related to informing on others. For example, maybe you'd call in sick on the day of the big gang war.
 
But wait, was it just one rat leaving the ship? Or did one rat tell the rest "Hey, get off the ship! It's sinking."
 
[a1  a2  0   0 ]         b1
|              |
|0   0   a1  a2]         b2
|              |
|c1  c2  0   0 ]         d1
|              |
[0   0   c1  c2]         d2
 
And maybe humans misunderstood for whom the rats assumed to be their associates
 
@Kevin let the matrix on the left be A, the vector on the right b. Then np.linalg.inv(A) @ v is a vector and it contains M11, M12, M21, M22, respectively
(hopefully it's numerically stable)
we could probably compute the inverse on paper :)
 
4:25 PM
All the rats run in the same direction, as I have seen in documentaries.
 
(we could reorder the rows so that it's a 2x2 block diagonal matrix)
 
Hmm. Is it reasonable to expect that there's exactly one solution for M? I was worried that there would be multiple solutions unless I nailed down e.g. the order of the transformations
 
I wouldn't be surprised if two pairs of from->to vectors pinned it down
linearity is a strong constraint
 
One potential complication is that, since I want a translation step, I'm representing my 2d coordinates as (x,y,w=1). That might be one degree of freedom too many.
 
oh, translation
that's not a matrix, and not a linear operation
(i.e. 2*T(v) != T(2*v))
 
4:30 PM
I'm thinking about it in terms of transforming the line segment AB to CD. I'm pretty sure the solution must be unique.
@Kevin Oh, if you're using homogeneous coords, then the solution is unique up to a non-zero factor, which will go away if you renormalize the w of the result.
 
That's me, the one behind, when I see high level conversations here
Singletons convo did that to me, 3-4 days ago, lol
 
If it makes you feel any better, I don't understand half of this conversation either
When I ask a math question at the edge of my understanding, I recognize that I'm jumping out of an airplane with the hopes that I can build a parachute on the way down
 
"that I can build a parachute on the way down" - lmao, am going to use it from now!
 
I stole that phrasing from somewhere. Google suggests goodreads.com/quotes/…
I bet there are earlier formulations than that though
Time to read up on np.linalg.inv
 
4:38 PM
"An entrepreneur is someone who will jump off a cliff and assemble an airplane on the way down." - This is nice too
 
Perhaps it's more like, I jump out of the airplane with the hopes that I'll meet some kind strangers who will make a parachute for me
 
@Kevin what I wrote will only work for rotations, I think. Translations won't give you a single matrix transform like that
unless homogeneous coordinates work like that, I don't know how they work
generalizing it to your actual problem is left as an exercise to the reader
there's probably also a simpler (more elegant) way to put that matrix together
 
My limited understanding of homogeneous coordinates: translation is not a matrix operation because no matrix can turn [0,0] into anything else. But if we add an extra dimension to the problem and declare that w is always nonzero for all inputs and outputs that we care about, then by definition we don't care what [0,0,0] transforms into. In this way, we can write a "translation" matrix, even though it's not actually a translation matrix because it doesn't modify [0,0,0]
 
Homogeneous coordinates are awesome. They allow you to unify translations with the other transformations, so you can multiply all your transformations into a single matrix. And they automatically handle points at infinity.
 
so...this means the transform Kevin is looking for is not 2x2, but still a matrix
 
4:48 PM
Yeah.
 
you could write the 9 equations together with those "ones" to get an equation for the big matrix...but something tells me that the magical scaling might mess with this
also constructing a 9x9 matrix by hand wouldn't be any more elegant than what you have right now
 
I don't think the W component messes with anything if I declare it to be 1 by fiat. But there would certainly be a lot of algebra.
 
It shouldn't be that messy. You want to transform AB to CD. Translate AB so that A & C coincide, scale it to get the right length, then rotate it to get B on D.
 
Yeah, that's pretty much what I'm doing at pastebin.com/H9BhM1EN. (although I might have gotten the variable names backwards)
 
5:01 PM
If you scale both segments to a length of 1, you can get the cos of the rotation angle from the dot product, and use Pythagoras to get the sin, so you don't need to use actual trig functions to construct the rotation matrix.
@Kevin I'll have a look, but I'm getting pretty sleepy, so I may not be able to offer constructive suggestions. ;)
That looks ok.
 
The program that this problem is embedded in produces the right result, so if it's wrong, it's exactly the right kind of wrong where all the fencepost errors and axis inversions etc cancel out
This is a common outcome when I flail about in the problem space of 2d coordinates
 
5:17 PM
Hey all, is it poor form in a pandas DataFrame to have a column where datatypes are mixed e.g. for some rows its string, other boolean?
 
yes
 
ok thanks
 
@Andy Pandas DataFrames should be thought of as organizing data types by columns and observations by rows. By that assumption, yes, it is bad form. However, it isn't enforced and under certain circumstances, it doesn't matter.
 
@piRSquared ok thanks that's a helpful way of looking at it. My problem is as someone that programs in solitude I don't want to drift into bad techniques
 
@Andy don't program in solitude (-: keep chat open. These types of style questions are important to forming how you code. There is a lot of chaf in chat but it's all sfw and you get really good insight occasionally.
 
5:31 PM
chat helps distract from coding, makes it easy to procrastinate getting anything done
 
@piRSquared ah will do :)
 
@Andy there are several reasons for why this is bad practice, one being that a mixed column will be of object dtype and that will stop you being able to use "vectorized" methods, which can increase the speed of operations by several orders of magnitude. So it's not just stylistic
Not that anyone suggested it was, but I thought it worth saying that it does have real implications
 
^^ and ^ True
 
Ok, I did the algebra for my problem, with a dollop of tool assistance along the way: pastebin.com/NKTChkFP. The system of equations is considerably less nasty than I thought it would be, although still too nasty to work out on a cocktail napkin.
 
5:47 PM
And certainly not in the margins of your notebook
 
the problem is that it's not linear in theta, though for practical purposes it's probably close enough
 
I suspect that if I actually did work out the solution, it would look a lot like the "calculate scaling, then use that to calculate rotation, then use that to calculate translation" approach I had at the beginning of all this
 
@Code-Apprentice And thereby keeps us (in)sane ;)
 
Or maybe that but backwards. Whichever.
 
or perhaps you can solve for cos(theta) and sin(theta) separately and scale them back so they obey the Pithagorean theorem ;)
 
5:50 PM
@Kevin What is the assumption of the transformations? Are you transforming point A to point C and point B to point D?
 
ah, v has two components, nevermind
 
Even if I give up here, getting the symbolic product of the three transformation matrices should let me improve my project's runtime by a couple ms. Time well spent :-P
 
@AndrasDeak yah, I first saw 4 equations with 3 unknowns...
@Kevin Is your data such that the transformations are the same for both pairs of points?
 
Yeah.
 
oh...that actually might be universally true for any two points in Euclidean space...
 
5:58 PM
Aside: Anyone got a suggestion for a particularly useful SQL/PostgreSQL tutorial?
 
@roganjosh ok thats helpful too thanks
 
user7437554
Hello
 
user7437554
What is wrong with this code?
 
user7437554
def has_duplicates(inplist1):
    inplist2=inplist1[:]
    duplist=[]
    for element in inplist2:
		inplist2.remove(element)
		if element in inplist2:
			duplist.append(element)
		print(duplist)
	return duplist
listatr=[1,2,2,3,3,4,4,4,'palma','mallorca','palma']
 
user7437554
6:02 PM
the output is:
 
user7437554
  File "trial.py", line 14
    return duplist
                   ^
IndentationError: unindent does not match any outer indentation level
 
If you want to return after the end of the loop, then make it so the return has the same amount of indentation as the for.
If you want to return inside the loop, strongly reconsider, because an unconditional return in a loop is almost always the incorrect design
 
user7437554
don't know what happend but it's same indentation than the loop
 
mixed tabs and spaces maybe?
 
If the indentation looks OK in your IDE but magically became weird when you pasted it into the chat window, you're probably mixing tabs and spaces.
 
user7437554
6:05 PM
So what's that?
 
user7437554
isnt the same to press tab than 4 spaces?
 
It's when some lines are indented with tab characters and some lines are indented with spaces.
Some editors are configured to interpret the tab key as four space bar presses, but not all editors do this, and not all of the ones that can do this do it by default
 
recbg
 
Putting that matter aside for a moment, it's usually a bad idea to modify the length of a list while you're iterating over it, so calling inplist2.remove there may have undesirable effects
 
the whole thing should really just be return len(set(inplist1)) != len(inplist1)
 
user7437554
6:10 PM
@Kevin thanks, do you see any workaround?
 
user7437554
I haven't study set yet...
 
they're making you check for duplicates without a set? Are they mad?
 
 
user7437554
Hmm it's a book and just an exercise
 
Yep, you're definitely mixing tabs and spaces.
 
user7437554
6:12 PM
I think it's for practizing
 
I suppose it can be educational to implement something like this on your own...
 
user7437554
cool
 
user7437554
Yes, I've modified that, thanks @Kevin
 
user7437554
@Aran-Fey you recommend to read about set function?
 
user7437554
this is the solution of the book:
 
user7437554
6:14 PM
def has_duplicates(s):
    """Returns True if any element appears more than once in a sequence.

    s: string or list

    returns: bool
    """
    # make a copy of t to avoid modifying the parameter
    t = list(s)
    t.sort()

    # check for adjacent elements that are equal
    for i in range(len(t)-1):
        if t[i] == t[i+1]:
            return True
    return False
 
Seems a bit apples & oranges to your function, since this returns a boolean and yours returns a list
 
t = sorted(s)?
 
user7437554
well I just focused to get the duplicates, but you're right...
 
wim
@PM2Ring I don't think C is a bad choice as a first language to learn. Maybe not as good a choice as Python, but still a good choice.
There are many worse choices!
 
Is there any R chatroom?
 
6:17 PM
@santimirandarp Yes, knowing your data structures is a must. You don't necessarily need to know about stuff like Trees or Stacks or whatnot, but lists, dicts, and sets are essential.
 
@noob look at chat.stackoverflow.com/rooms
 
Speaking of implementing things on your own, I'm a tad disappointed nobody except for Arne tackled the "implement super yourself" challenge. Was that too difficult or was it just not interesting?
 
link?
 
I think I missed that one.
 
Weekend I think
 
6:20 PM
I've theorycrafted about implementing super() before and I decided that you would need inspect trickery to implement zero-argument super
Since IIRC the actual zero argument super implementation basically peeks at frames that it shouldn't be able to see
 
does anyone know where I can find freelance work in R, python online?
 
Hmm, can't say that I do.
 
user7437554
@Kevin How do you highlight the type of indentation? It'd be quite instructive if I forget about it
 
To view tab and space symbols in Notepad++, go to the "View" menu, then "Show Symbol", then check "Show White Space and TAB"
 
6:23 PM
Other editors and IDEs probably have this option somewhere else. I don't know anything about them.
 
May 9 at 10:23, by Aran-Fey
# Implement the `super` function in pure python! (Specifically, the
# `super(class, instance)` form.)

class my_super:
    ...  # YOUR CODE HERE
May 9 at 10:23, by Aran-Fey
here are a couple of test cases
 
wim
not really a frame hack ... but still kind of a hack
 
hmm, I guess I shouldn't have posted it that early in the morning
 
wim
@Aran-Fey I didn't bother because pastebin is blocked
 
@Aran-Fey hmm, go through mro, find first that hasattrs, return bound
BUT... be sure to go through the mro of the instance type starting from that class
 
6:25 PM
spoilers :/
 
no
just pure speculation :D
at late night
 
Ah, yes, that's it. Magical __class__ binding.
 
wim
is it cheating to use MyClass.__mro__? or you expect people to re-implement C3 linearization
 
@wim here's a dpaste for you if you're interested
 
also: multiple inheritance is still eval.
 
6:27 PM
You can use whatever you like... except super
 
So the real super doesn't have to stoop to frame peeking, but your homebrew implementation probably will since you can't ask the compiler to bind __class__ on your behalf
 
We're only implementing a third quarter of the real super's functionality - super(class, instance)
 
Ok. Two argument super shouldn't require any magycks.
 
user7437554
@Kevin oh, I'm in ubuntu
 
wim
6:39 PM
the super implementation seems insane, why they didn't just make this a keyword I don't really understand
 
On third thought, I think zero argument super is doing frame trickery, in addition to secretly binding __class__. At least, it's manipulating PyFrameObject references which I don't think is necessary if you're only trying to get variables that are properly visible in your current scope
 
wim
looks like just digging out the __class__ from the cell to me ... what's the "manipulation"?
remember the __class__ is not an attribute, it's a cell var
 
"manipulation" is the wrong word. It's not mutating anything. It's just getting the frame object of the calling context.
 
wim
well how else could it get the cell var ... if you pass it in explicitly then you don't have a 0-arg super anymore
 
Agreed.
 
6:52 PM
I kinda assumed that stuff happened at compile-time
 
Trying to track down the history of super()... Changelogs indicate that the type was originally introduced in 2.2a3. The only PEP discussing super appears to be python.org/dev/peps/pep-3135 which is specifically about zero argument super
- A new built-in type, super, has been added.  This facilitates making
  "cooperative super calls" in a multiple inheritance setting.  For an
  explanation, see python.org/2.2/descrintro.html#cooperation
Dead link, alas
 
wim
@Aran-Fey A strange assumption from the user who asked Why does assigning to the __class__ cell break super?
 
Oho. The Internet Archive forgets nothing. web.archive.org/web/20090106040720/http://www.python.org/2.2/…
 
@wim Is it? Surely assigning to __class__ could still break super even if the compiler converted super() to super(__class__, self)?
 
Here's my wild guess. super was initially not a keyword because cooperative classes were not considered the "one true way" of implementing classes, and elevating super to keyword status would tacitly endorse cooperative classes above other approaches. Eventually new-style classes became the norm, but by that time changing super to a keyword would break backwards compatibility.
 
7:02 PM
Hmm, I don't think that implementation is correct. As far as I know, the logic is a tad more complex than just checking if attr in cls.__dict__:
 
I could use some help in doing some .splits in a odf document I'm outputting. I have an arg we'll call arg4.`parser.add_argument("-a", "--arg4", type=str, action="store", dest="arg4List", default="string1,string2, string3",
help="specify list of allowable strings` then I have much further down`if args.riskFactorsList:
for line in args.arg4List:
type_list = line.split(",")
args.arg4List = type_list[args.arg4List["string1", "string2", "string3"]]`
I get TypeError: string indices must be integers
If I leave out the strings at the end, I get the same Type Error, only gives more generic error, instead of specifically calling out integers
 
Huh, it's actually right and mine's wrong. I need to add a bunch more test cases, I guess...
 
What is the value of args.arg4List["string1", "string2", "string3"]? If it's anything other than an integer, you can't use it as an index into type_list
 
wim
@Kevin that seems a good guess, and consistent with the various other warty areas of the language
 
"We didn't have the unlimited foresight to design it right the first time, and we can't completely change how it works now" describes all sorts of WTFs in our history :-D
 
7:08 PM
would there be another way to do the .split(",")? The strings should be spit out when all is said and done. In python 2, I don't even need to separate out the split, I can use it directly on my argument and say args.arg4List =args.arg4List.split(","). It seems the string module can't handle that in python 3 so trying to find a workaround
 
wim
where was the recent question that discussed this thing again?
>>> f"{*[3,1,2],}"
'(3, 1, 2)'
>>> f"{*[3,1,2]}"
# SyntaxError: can't use starred expression here
 
class X:
   def y(self):
       print(__class__)

X().y()
 
@WSLUser I'm pretty confused by what you're trying to accomplish with the line args.arg4List = type_list[args.arg4List["string1", "string2", "string3"]]. Assuming this is executing inside the for line in args.arg4List: loop, and assuming line is a string, then the code is doomed to fail. If the first iteration succeeds, then type_list[args.arg4List["string1", "string2", "string3"]] evaluates to a string, and you assign that string to args.arg4List.
Then in the second iteration you try to do args.arg4List["string1", "string2", "string3"]. But now that args.arg4List is a string, this will fail because you can't index a string with three strings.
 
class X:
   def y(self, __class__=42):
       super().y()

X().y()
 
wim
@AnttiHaapala looks like an XY problem
 
7:11 PM
lol
class X:
    pass

def z(self):
    print(super().__str__())

X.z = z

X().z()
 
It may help if you described in plain English what the code is supposed to do
 
here's how line is defined. It's basically doing some formatting: for line in text.splitlines(): if ':' in line:

firstWord, rest = list(map(str.strip, line.split(':', 1)))
firstWord = firstWord.strip().lower()
 
yea. I really do not like super at all. Even less so in Python 3
 
Basically I'm querying the strings against a database, and outputting them into a report with some other data
 
@WSLUser you do not need list there, just noise.
also you stripped firstword already
 
wim
7:14 PM
@AnttiHaapala composition over inheritance
 
there are some cases where inheritance makes sense... usually it should be just about inheriting traits.
multiple: never.
 
wim
using super for anything non-trivial makes your code like a rube goldberg machine
 
C++ is totally insane in that it allows 2 kinds of diamond inheritances.
 
Well that, with little further code is creating the field name. There will several columns each with it's own header in the odf file
 
wim
I still basically agree with super-harmful even though people seem to post Raymond's rebuttal more often
 
7:18 PM
those specific strings exist in one column but based on the data that's associated to those strings will depend what's output. All data associated to string1 will be at the top of the page, and go to string2 and then string3. Arg4 will become the name of one of the columns.
 
Every day that I don't have to use super() is a blessing
 
@wim I've never seen that one. Thanks, now I do not need to write it :P
No, I have read it because it talks about the Dylan next...
 
dunno, I do not see things that are particularly wrong about super
it is more that Python does not give you the tools to properly define contracts or type guarantees
 
@MisterMiyagi so did you read the ^article
 
7:22 PM
ok.
so which problem does it solve?
 
I used to hate super but after I realized that I'd never actually seen it cause problems in real code, I stopped caring
 
@AnttiHaapala other then endlessly and explicitly coupling code to some baseclass?
 
you've explicitly coupled the code to some baseclass anyway
by using super
 
any baseclass, not some
 
but ... it might be your sibling or nephew
 
7:26 PM
anything might be anything in python
I don't see "you could shoot yourself" as much of a negative, compared to the background noise of potential nukes lying in wait everywhere
 
wim
@AnttiHaapala and by using inheritance
 
inheritance implicitly couples the methods
 
wim
explicit is better than implicit
 
e.g. mixins work via inheritance+super, but not explicitly coupling in methods
 
wim
just calling the base classes directly is underrated
 
7:29 PM
@wim explicitly doing the wrong thing is not better than implying the correct thing
often I just want to call "that superclass"
super() let's may say that explicitly
SomeClass that also hides a few dozen lines above in the class ... statement does not convey the same
 
Every time I read this stupid sentence I want to stop reading that "super harmful" article
 
Who needs classes when you have json-y data nested six levels deep
 
> People omit calls to super(...).__init__ if the only superclass is 'object', as, after all, object.__init__ doesn't do anything! However, this is very incorrect. Doing so will cause other classes' __init__ methods to not be called.
So I'm supposed to call super().__init__ with... what arguments?
 
@Kevin stored in arbitrarily encoded bytes, I hope
 
"Arbitrary" describes many aspects of my coding style, yes
 
7:33 PM
@Aran-Fey depends - did you overwrite __new__? ;)
 
@Aran-Fey If I understand correctly: with whatever arguments that the other class requires. I think this scenario is where "cooperative" design requires the authors of each class to know about the interface of each other class, so they can accommodate one another.
 
So every class I ever write should support cooperative multiple inheritance?
 
That's the part I'm getting tripped up on. If you're writing a cooperative class, then you know what other classes are in your inheritance graph, and you know what's next in the mro. So of course you're not going to neglect to call super().__init__.
 
I think there's an easy solution to the problem: If your parent class is object (and you're not writing a cooperative class), don't call super().whatever_method.
 
I don't know when you would "speculatively" add cooperative inheritance to your class with the expectation that it will be inherited from in some far-flung time
 
7:41 PM
I'll go with "never"
Don't need it? Don't implement it
 
Contrived example. Even though A inherits from object, you still want to call super.__init__ so A's sibling gets called with the right arguments
 
speaking of which, I'll seize this opportunity to try and google what composition means exactly
 
@Kevin I think "speculative" is exactly when you should not use super - or inheritance for that matter
 
"But why on earth would you make A and B siblings instead of having a parent-child relationship when A clearly has some responsibility over B?" you ask. I don't know. Contrived examples are contrived.
 
either it is well-defined how your objects may be inherited, or not
"may be inherited from in this and that way" is a capability just like any other
 
7:46 PM
Now I'm wondering what you should do if you have a class C(A, B): and a class D(B, A):
 
On a separate topic, is there a canonical for Pandas questions for inplace=True returning None if you assign the result back? This is standard stuff, but I can't find something that doesn't just mention it in passing
 
@Kevin make sure A and B are proper mixins using kwargs
 
The closest is this I've found, but it's not really a good dupe for the whole general situation
 
From a puristic point of view not supporting cooperative inheritance may be a sin, but from a practical point of view supporting it all the time is ridiculous. Imagine if every method had *args, **kwargs and super().method(*args, **kwargs). What an absolute mess that would be. In practice, not supporting cooperative inheritance is pretty much never really a problem.
 
wim
@Aran-Fey right
 
7:49 PM
@roganjosh isn't that basically the same case as other mutating methods returning None?
 
@MisterMiyagi yeah, but in pandas it's a deliberate act when you set the argument so I guessed that it should be pandas-specific
RafaelC hammered it anyway with 2, one of which being stackoverflow.com/questions/43893457/… which is probably closer
 
how about you add an answer to the dupe-candidate?
 
wim
@Kevin and everybody has to play the same ball game. which pretty much never flies in Python.
@AndrasDeak TL;DR :
class A(B):
    ...

vs

class A:
    def __init__(self):
        self.my_b = B()
 
I'm halfway through a corresponding blog post so I understand what you're trying to tl;dr :P thanks
 
I like the decorator pattern when I need to mix and match a collection of small related behaviors in an order-preserving fashion.
 
wim
7:52 PM
@MisterMiyagi I will show you one
 
Decorators are a pattern now? I need to google this
 
wim
>>> from django.conf import settings
>>> from django.http import QueryDict
>>> settings.configure()
>>> from collections import OrderedDict
>>> class MyQueryDict(QueryDict, OrderedDict):
...     pass
...
>>> QueryDict(u'x=11&y=22&z=33').urlencode()
u'y=22&x=11&z=33'
>>> MyQueryDict(u'x=11&y=22&z=33').urlencode()
u'x=1&x=1&y=2&y=2&z=3&z=3'
 
Not to be confused with @ decorators, which is a kind of decorator pattern but does not encompass every kind of decorator pattern you can implement in Python
 
wim
^ here is the MCVE. I try to make a querydict which preserves ordering, by dependency injection. it doesn't work, it corrupts the query totally.
 
Can you pull off sealed classes in python? Then just make QueryDict that ;D
 
wim
7:54 PM
this is Python 2.7 with Django 1.11. On Python 3.5 the same thing mysteriously works correctly. Why?
If you it takes you less than an hour to figure out how super screwed up here, you are a better developer than me..
 
@Aran-Fey It's in the Gang Of Four book, so it's an Official Pattern (tm) (c)
 
I keep my hands of Py2 problems out of principle these days
 
Wow, is there anything that isn't a design pattern nowadays? "You can write classes that accept an object as an argument and then do something with it"-pattern. Wow. Amazing. What's next, a "variables pattern"? A "while loop" pattern?
 
you don't want to know
 
counter = 0
while True:
    print(counter)
    counter += 1
    break if counter >= 100
 
7:57 PM
Patterns are real in the same way that France is real. Anyone can declare territorial lines, but from space everything's a big green blob
 
^^ pattern
 
I am having my frontend is complaining and giving error "Unexpected token N in JSON" which after some investigation got to find is because there are NaNs in my json response. How do i sanitize my data that my json.dumps does not respond with NaNs, either have it replaced with "" (empty string) or 0
 
wim
same thing on Python 3.5 btw, with same django version:
 
@JoeSaad 'NaN' as a string would not invalidate JSON. How is the data passed to the front-end?
 
wim
>>> MyQueryDict(u'x=11&y=22&z=33').urlencode()
'x=11&y=22&z=33'
 
7:59 PM
my responses are coming right on postman, but when i make the frontend request it, it is giving this error Unexpected token N in JSON
 
>>> json.dumps([float('nan')])
'[NaN]'
... Huh. Is unquoted NaN even syntactically valid json, officially?
 
JSON serialization can easily fail with numpy objects, but that would normally happen during serialization, not deserialization on the front-end
 
wait wait wait
 
Hello, I have some data that when I assign it to a variable in a jupyter notebook it seems to automatically convert to an object,

train_data = [("Uber blew through $1 million a week", [(0, 4, 'ORG')]),("Android Pay expands to Canada", [(0, 11, 'PRODUCT'), (23, 30, 'GPE')])]

but when I read it from text file using

with open(path, 'r') as myfile:
  data = myfile.read()

I'm no longer to iterate over the objects

    for _, annotations in train_data:
        for ent in annotations.get('entities'):
 
break if is a thing?
 

« first day (3131 days earlier)      last day (1809 days later) »