« first day (3135 days earlier)      last day (1816 days later) » 
00:00 - 16:0016:00 - 23:00

12:05 AM
if I want to make a class that iterable, is there a way to do that with yield, or should I just use iter and next?
 
An iterable class?
 
Yeah, it's essentially just a light wrapper around lists
so I want to be able to iterate over objects in it (or the lists that they're holding), but there's some other stuff I want it to do so lists aren't sufficient
 
@Mark Try:
class A:
    def __init__(self, a):
        self.a = a
    def __iter__(self):
        for i in self.a:
            yield i
    def __next__(self):
        if not self.a:
            raise StopIteration
        return self.a.pop(0)
Calling:
a = A([1,2,3])
for i in a:
    print(i)
a = A([1,2,3])
print(next(a))
print(next(a))
print(next(a))
print(next(a))
rbrb
 
hm, what's the benefit of using yield here? I thought that it was normally used as an alternative to manually raising StopIteration
 
12:23 AM
@U9-Forward Isn't modifying the collection (the pop call) during iteration a bad practice? Aside from generators, most collections don't get consumed permanently like that.
 
Yeah good point, while I want to iterate over the object I don't want it to be consumed
 
@Mark yield's primary purpose is to pass control from the current method back to the caller, which is particularly useful if you want to interweave the execution of the yielding method with the caller. For example, you might only need to iterate through half the elements, allowing the iteration to stop early at the discretion of the caller. Or it can be used if loading all the elements at once is resource intensive, allowing resource usage to be spread out over individual iterations.
As a practical application, though, it's often the easiest to read and most maintainable way to generate elements one at a time.
 
12:43 AM
I've been noticing a number of questions lately about people having trouble with imports. It seems like most of them aren't really aware of where Python is importing from or how to control that (like through PYTHONPATH). e.g. stackoverflow.com/a/56177563/1394393. Is there a canonical about that? Didn't see one on the Common Questions list. There's sopython.com/canon/96/…, but I'm pretty sure that shadowing isn't the problem.
The problem is it's importing something different than they expect.
I've seen others where there was no name clash, but I don't have them handy.
 
1:24 AM
recbg
@Mark Well, to give out a generator, like all functions in itertools
@jpmc26 It doesn't seem to be inefficient... only thing is .remove won't work, only works in for i in list(l) or for i in l[:] and some others...
@jpmc26 Oof, much better explanation than me lol
@jpmc26 Exactly, once i almost named a file pandas.py lol
When importing pandas
at least i realized lol
@jpmc26 Yeah, those are usually from low rep users.
 
2:20 AM
@Aran-Fey there's also start and span... :p cc @piRSquared
 
2:42 AM
rbrb
 
 
1 hour later…
3:48 AM
@binz please review the room FAQ. You are expected to wait 48 hours before asking us to discuss a question of yours (and then, just dumping a link to the question here is hardly the best way to do it)
 
 
2 hours later…
5:22 AM
cbg
 
cbg
 
@cs95 Lol, ya always say that right after me haha
 
understandably, it was in response to you
 
@cs95 Oh, cbg to you then :-)
 
6:15 AM
@jpmc26 yeah, that's a very bad example
@Mark do you really want to implement __next__? Wouldn't that make it an iterator? I'd think you're fine with your list and you can loop over it implicitly or via iter(myobj).
With lists you can't do next([1,3,5]) and that makes sense
Or do you want fancy things during iteration?
Because then you might want an iterator class rather than a list subclass. Like enumerate that is an iterator that decorates iterables.
Either way I'd expect obj and iter(obj) to belong to different classes if the former is not an iterator
 
6:56 AM
>>> class fancylist(list):
...     def bells_and_whistles(self):
...         print('doing a thing')
...
>>> flst = fancylist([1,3])
>>> flst.append(4)
>>> flst
[1, 3, 4]
>>> [val**2 for val in flst]
[1, 9, 16]
>>> flst.bells_and_whistles()
doing a thing
^ list subclass that knows more than lists but it iterates just like lists. No extra work needed.
>>> it = iter(flst)
>>> next(it)
1
>>> next(it)
3
>>> next(it)
4
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
it needs iter to iterate over, as expected ^
 
@AndrasDeak Ugh, damn, forgot about subclasses... nice tho
rbrb
 
7 hours ago, by Mark
Yeah, it's essentially just a light wrapper around lists
OK, I thought they wanted a list subclass. Just wrapping it with composition might even be better.
hmm, maybe not
if you want to have .append and whatnot you either implement those yourself or you do subclass list after all
 
7:13 AM
From the description I really couldn't get much, and when I am asking the OP to provide an explicit output, he keeps pointing me to the question and restating what is already in there
Is the question really descriptive, and I am missing something basic here?
 
eh. i guess time to find out.
the OP should have provided how exactly he's getting the dict in the question itself if not anything else
 
yes he just posted a function, that's it, no sample ip and op. no where he is calling it from etc
 
They might just mean "content" or "exposed interface"
 
regardless, your answer is fine.
they mentioned what they mean in response to one of the comments on the answer.
and i just checked, the dict does have the dunder name as key.
 
@DeveshKumarSingh so close as unclear
 
7:21 AM
well, its not that its unclear. its just that it takes reading through 10 additional comments just to finally get what the op is trying to say. they should be asked to edit that info into the question really
Though to be fair, i wouldn't usually answer until im sure what the op is asking. If i cant get it sorted in comments, i dont write up an answer
 
@ParitoshSingh imo it's unclear
 
The question looks perfectly clear to me. They're looking for a function so that func(vars(a_module)) == a_module
 
Just marked it unclear, I thought given the name of a module, getting the module is straightforward, hence I mentioned the solution I had, since I have used it before.
But maybe it needs to be read by someone who has slightly more in-depth knowledge of python
 
nah, its not a question of depth so much so as one of communication. the onus of this one is on the OP, not you.
 
Is there a better chat to ask about Regex?
 
7:27 AM
@Aran-Fey Then why do they talk about globals()?
 
Because globals() == vars(current_module)
 
well..
feels to me like one of those questions where OP has dwelled on their problem for so long that they can't imagine how their choice of words might be confusing to people who are reading about it right now
or in other words, I was very confused by it, and still don't see how Davesh's answer isn't good enough
 
If you are given a name of a module in a dictionary, you either do my way or sys.modules both of which assume the module is installed in the python interpreter
where the code runs, is that an incorrect assumption?
 
The OP did say they think importlib is overkill and they'd use sys.modules[d['__name__']] instead, so maybe that's why they haven't accepted the answer
 
> With importlib, if the module is not in sys.modules, it maybe would import it again [...]
Is that correct? I thought modules are singletons?
 
7:36 AM
sys.modules lists modules in cwd too ?
 
They're not singletons, they're just cached in sys.modules if you import them with the import statement. If you import a module with the importlib machinery (or you instantiate a new module object), that's not the case
 
aye. like really, if his comments were in the question, this would all be much simpler to deal with.
 
yes that's what I was trying to explain to him lol, but he's not budging, so I have given up for now, I thought given his 28k+ rep he will understand what I am asking him :)
 
well, okay, so that's the thing though. he does tell you what he wants eventually, and it doesnt exactly match with what you're giving him
having said that, your answer should be very useful to him regardless
i dont quite understand why he wants the "picture perfect answer" if he has already solved his use case using yours.
 
okay yes that's correct too, maybe you can add an answer based on your understanding, so that I also learn something new :)
 
7:41 AM
especially if the "picture perfect answer" does not have the picture perfect question to go with it right now. anyways, i digress.
nah, dont feel like it, your answer + the op's comments are an answer in and of itself.
rbrb
 
I have a Regex related question, feel free to direct me elsewhere :). So im coming across this number '1.500,00' as a string which I need to convert to a float. The thousand separator is blocking this. The closest regex rule i can get is '\.\d{3}' which matches '.500' but I just need the dot only if it occurs in front of 3 digits.
 
use capturing groups. brackets around the portion you want
 
so you want to use regex to remove the thousand separator(s)?
 
having said that.. uh
your goal, usually you don't need to convert everything entirely in regex
 
In [92]: float('1.500,00'.replace(',',''))
Out[92]: 1.5
 
7:51 AM
just capture the number properly
 
does that works @mtbrands ?
 
Sadly it doesnt because theres also cases where for smaller numbers the . is used as the decimal separator
With brackets I can get the groups but I dont know how to select a certain group
 
here the dot is a decimal separator? your number isn't 1.5 ?
 
capture the entire number, using regex if you like, but build your logic for number conversion without regex. that's my recommendation anyways
 
what will it translate to then
 
7:53 AM
it should become 1500,00
@ParitoshSingh ill have a look
 
damn, where did you get the string from!
 
its like 3 things at max to code for, if even that. just a dot, comma, and currency signs
 
@DeveshKumarSingh this is common in some European languages - dot is the thousands separator, comma is the decimal sign
 
heck, im willing to bet someone has already done the hard work for you
 
aah I never knew, what language if you could give me an example
 
7:54 AM
@DeveshKumarSingh Scandinavian languages at least, I think German too though they have a different convention in Switzerland IIRC
 
it should also support having . as the decimal sign
 
that's not hard to google either; en.wikipedia.org/wiki/Decimal_separator
@mtbrands no, you can't have it both ways, you need to tell the computer which is which because this is inherently ambiguous without context
 
@mtbrands try things out, see if you can find a prebuilt solution. if not, build your own. One thing is for sure though, if you are having mixed styles of writing, there's always a chance of wrong parsing
 
Thats why i made a rule which specifies to only match it if its before 3 digits, which is a thousan
 
that's much easier without regex though :)
 
7:58 AM
you can't know if that's a thousands separator or a float with exactly three decimal places
 
get the number, check the 2nd last or 3rd last symbols.
 
add in Indian conventions where numbers are grouped by two digits instead of three
 
hey, where did all my money disappear?
i swear i had two more zeros!
to be fair though, indian system does not have to write 2 digit separators until after thousand.
so depending on how its written, you can still be fine
 
@ParitoshSingh if it's in comments and not in the question it's unclear. Simple as that.
 
@AndrasDeak i see. if that's the criteria, then yeah, i agree
 
8:01 AM
Hi @Aran-Fey thanks for answering that question. So if I guess correctly
sys.modules is a better way to find the module name rather than importlib.import_module
 
ok i really need to head off. grr, chat
rbrb
 
Since the OP is specifically only looking for modules that have already been imported, yes, sys.modules is better than importlib.import_module
 
so sys.modules cahes the modules already imported
and importlib.import_module explicitly imports them
well, that what's it also says in the docs. docs.python.org/3/library/…
 
someone can help me with spark/hadoop here ?
 
@mtbrands Do you need to handle data from multiple locales? In the U.S., the . is the decimal separator and the , is the thousands separator. The example number you gave would be nonsensical in that locale. But in Canada and Germany and lots of other places, that number would be equal to 1500 because they reverse the symbols.
If so, regex isn't the way to go; you would want a library that can handle any locale. And I'd generally prefer to have the capability than be shot in the foot later by having hard coded processing on a particular locale.
 
8:30 AM
@wim The section was dropped in October 2017, see github.com/pypa/wheel/blob/… for the old revision.
@wim: how many versions rtd hosts is configurable.
 
 
2 hours later…
10:43 AM
can I question about django here?
 
sure
 
Any idea to execute function in django model annotate() ?
 
10:59 AM
My preference is to use a guillotine.
puts on serious face
Depends on what you want to do with the annotate() function. Normally, I'd only really use them with an aggregation where I want to give it a nice readable name
I find the "cheat sheet" on docs.djangoproject.com/en/2.2/topics/db/aggregation to be pretty clear
@AnttiHaapala It's almost like you've never had a conversation with me before
 
11:30 AM
does anyone know what happened to the HAMT proposed as part of PEP 550?
it's in the CPython master, but I have found no references in the docs
I have need for an efficient immutable/persistent dict
 
the fact that it's accessible as from _testcapi import hamt suggests that they really don't want anyone to rely on it
 
any idea for alternatives?
the frozendict package is incompatible with Py3.8 and seems to be abandoned
 
I tried to find it online, but couldn't find why. Why does set sometimes seem to order elements in a sorted order
In [18]: set([1,6,3])
Out[18]: {1, 3, 6}

In [19]: set([1,6,3, 8])
Out[19]: {1, 3, 6, 8}
 
ipython pretty printing
 
the order in a set is arbitrary, not random
meaning that "sorted" is valid as well
 
11:41 AM
>>> set([1,5,3])
set([1, 3, 5])
 
plus, the hash of small integers is the integers value itself
 
>>> {2,6,4,1,-3}
{1, 2, 4, 6, -3}
@DeveshKumarSingh dogs have four legs so all animals have four legs
 
so is it just the way the number are hashed
and sometimes they hash up in a way they appear sorted
 
str([(val, hash(val)) for val in range(-5, 5)])
[(-5, -5), (-4, -4), (-3, -3), (-2, -2), (-1, -2), (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
 
>>> hash(10e7) == 10e7
True
even for a bigger number
 
11:46 AM
even for a float
but note that hash(-1) != -1
 
>>> hash(10.5) == 10.5
False
 
And none of this should really concern you; sets have no inherent order, period.
 
so such a behavior is coincidence, or due to how the integers are hashed, nothing else
 
coincidence or implementation detail or some other fluff (such as ipython)
 
so similar to the idea of using == and not is operator for say integer comparison, you should always remember that sets are unordered
 
11:51 AM
indeed
and even in python 3.8 where dicts preserve insertion order sets are unordered
 
and any odd behaviour we encounter otherwise is just a coincidence or an implementation detail, got it
And now I understand ipython fluff too
In [10]: set([1,6,3, 8])
Out[10]: {1, 3, 6, 8}

In [11]: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> set([1,6,3, 8])
{8, 1, 3, 6}
 
Hi
 
Ahoy
 
Andras I guess you know the unit nat? I just learned about it today. I get it, but I wonder what are the practical implications why one would use a nat instead of a bit?
 
Why would I know? Never heard of it.
 
11:56 AM
network address translation ?
 
oh ok. dunno thought you might know
 
@DeveshKumarSingh of course it's a reasonable question to ask why and how the order that you see is chosen (i.e. to dig into the implementation), but you should not confuse this with the idiomatic use of the language. It shouldn't affect the code your write.
 
it's basically the same as a bit, but with 1/e probabilites of an event happening.
 
I measure entropy in joules/kelvin
 
I sadly have actually no idea what entropy exactly is. But it sounds weird to me to measure it in joules/kelvin^^
 
11:58 AM
@AndrasDeak makes sense, a good idea to stick with the idiomatic use, only use whatever is meant to be used for a certain thing, == for comparison, and sorted for list sorting
 
@Hakaishin The classical (thermodynamical) interpretation is that entropy is the extensive quantity that is canonically conjugate to temperature. This by definition implies that it has joule/kelvin units, same as how pressure is conjugate to volume, making it joule/m^3 ;)
 
I think of it in terms of the measure of randomness of a system
 
that's what we usually say but that is a surprisingly empty phrase
 
haha that's how I feel about that phrase^^
 
(edit: question was what extensive quantities are :P) something like volume and number of particles, something that scales "like the volume" when you scale your system (as in tiling multiple copies)
 
12:03 PM
Does anyone know where I can find the requests.post docs? I need to know what exactly requests.post(json=some_dict) does >.<
 
I see. Sometimes it's weird that certain natural words combinations have actual very precise defintions. Especially strange if you dont know them
 
Intensive quantities are like temperature and pressure, they typically average across subsystems, and if you take a system twice as large they'll stay they same. Extensive quantities are like mass and volume. And they come in conjugate pairs, temperature <-> entropy, pressure <-> volume, chemical potential (don't ask) <-> particle count
 
@DeveshKumarSingh The json parameter doesn't seem to be documented at all there, as far as I can tell...
 
Help on function post in module requests.api:

post(url, data=None, json=None, **kwargs)
    Sends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
 
12:07 PM
ah, I found what I was looking for here
 
>>> requests.__version__
'2.18.4'
I got that from >>> help(requests.post)
Seems like instead of data=json.dumps(payload) we can do json=payload
so it's just syntactic sugar :)
 
when you say they come in pairs, does that mean there is a bijective function between the two? Like this much pressure will occupy this much volume for a given gas?
 
it's the opposite. P is inversely proportional to V
 
@DeveshKumarSingh no
 
12:10 PM
But the ideal gas law says PV=nRT
 
the ideal gas law yes, thermodynamics as a whole no
 
aah i just remember ideal gas law, what holds true in thermodynamics then? Van der Waals equation?
 
@Hakaishin no, it means that thermodynamic potentials depend on corresponding intensive*extensive products, for instance the internal energy is E(S,V,N) = T*S - p*V + mu*N. For the internal energy the extensive parameters are the "good variables", and the intensive parameters can be computed as derivatives of the energy, for instance T = dE/dS
@DeveshKumarSingh that's just another model
the first law of thermodynamics (one form at least) says dE = T dS - p dV + mu dN, where again you have these intensive*extensive pairs in the differential
 
I never read thermodynamics in this detail , by any chance are you a physicist :)
 
Yes, he is
 
12:16 PM
perfect person to answer that question^^
 
Also, ask him anything, he for sure has an answer
 
@DeveshKumarSingh indeed
it also explains why I know more about thermodynamics than the implementation of set objects in cpython
(then again there are plenty of physicists who are proper domain experts in programming)
 
Nice! the way you use those terms, you did seem a physicist, may I ask what field specifically? Also are into academic research, or a corporate job, I guess academic research
and feel free to ignore these questions if you want @AndrasDeak :)
 
Yes, I'm a researcher, my broader field is computational solid state physics
@lmao 1. I can answer on my own, you can see I'm here. 2. allow me the option to not answer if I don't want to
 
oh okk
 
12:21 PM
great, and hence the use of programming in your research! nice :)
 
Yeah, though the bulk of my work uses fortran
 
I cant believe that. I wonder when people will stop using fortran. How would you say is the split for physics experiments between fortran and c/c++? 50/50?
 
@AndrasDeak Apologies...
 
@Hakaishin I don't know anything about physics experiments. And how much do you know about fortran?
@lmao no worries
 
Great, and is it purely experimental, or part theoretical part experimental physcis
 
12:24 PM
100% theory
 
not much, besides that everybody who I heard talk about it talked badly about it, only counting people who had a course in it or worked with it
 
Nice, I never could wrap my head around math equations, and the equations in theoretical physics are one notch higher
 
@lmao, your name makes me laugh when you're in a discussion in this channel
It makes it seem everyone is laughing sarcastically at each other
 
@Hakaishin If you talk to non-physicists or people who were taught badly, it's understandable. Fortran can be written as a perfectly fine language (at least for scientific programming) as of the fortran 90 standard, and when used properly it doesn't deserve the crap it's usually given. More importantly, it has native complex arrays of arbitrary dimension. That would be a deal breaker if I were to try what we do in C*.
 
Thanks, for having a laugh :)
I do remember your 'Angrily waves placard, injuring innocent bystander', funniest thing I saw here, lol
 
12:27 PM
Appreciated!
 
:P
 
fortran is very widely used in science
it has practically unbeaten performance for numerical computations
 
I was never taught fortran, not in my bachelors in computer science. nor in my masters :)
They only stick with C/C++/Java/Python, unless you take courses where you need to learn Fortran to do your assignments
 
how to use argparse.parse_known_args to only parse arguments that start with --foo- and parse all of them with their name-values :d
 
@DeveshKumarSingh well, there are tons of languages out there which are useful but not commonly taught
mostly because they are only useful in a niche
even if that niche is rather large by sheer usage/impact
@AnttiHaapala why not parse all of them an keep only those with --foo-?
 
12:41 PM
I guess there is none
@MisterMiyagi no, I want to parse only --foo-bar=baz to {bar:baz}
 
"Language X is taught in schools" is an orthogonal quality to "Language X is a good language"
 
English is taught in schools
 
@AnttiHaapala is there a side-effect to parsing the others?
 
@Kevin and orthogonal means that python is taught in schools does not mean it is bad.
unlike english
@MisterMiyagi whatever.
 
I guess the languages taught are the ones more used in common industries. And again we do have courses where you are taught a general construct of a language so that you can pick up a new one by relating it to some other language
 
12:44 PM
as long as we are doing sweeping generalizations, assuming that "X is used for Y" can be translated to "X has quality Z" is a fallacy
 
Mm hmm. CS courses might choose a language based on how well it can be related to other languages
 
unless Y and Z are obviously related
 
Python, Java, and C++ all go in the "OO plus some fun bits" hat and you pick one at random
 
as far as I can tell, the most frequent reason to choose a language for teaching is "the tutor likes it"
 
except C++ and Java have no fun bits
 
12:46 PM
Java bytecode is fun
 
I also learned Coq in my masters which is used to prove correctness of programs lol
 
C++ is a huge language so there's got to be some fun in there, under a rock maybe
 
Finding UB, the scavenger hunt
 
there was a time when the local technical university forced everyone to learn Scheme before they could do anything else and I'm not sure I disagree with the motivations, though it still seems like a pretty crazy idea
 
@AnttiHaapala seems like you can do something with NameSpace to achieve what you want: docs.python.org/3/library/…
What's UB btw?
 
12:51 PM
My guess is "undefined behavior"
Overflowing a signed integer in C++ could theoretically make confetti and balloons shoot out of your monitor, so we can't say C++ isn't fun in all cases
 
IIRC, Fortran has very little undefined behaviour, except for integer overflow.
 
I wonder if there are any languages with no undefined behavior. Not counting esolangs whose instruction set fits on a post it note
brainf*** has like six operators so it's hard to sneak a segfault in there
 
Python has no UB, since it's defined by whatever CPython does. ;)
 
Because C has no undefined behaviour?
 
Tempted to trawl through the CPython source to find a comment like //not sure what this does but it seems to work??? which would qualify as UB in my book
 
1:01 PM
Whereas it's possible to write a valid C program that produces different behaviour on different architectures, or even when compiled by different conpilers. Or different settings of the same compiler.
 
isn't UB explicitly defined to include "does whatever the compiler feels like"?
 
Are cheat codes in games the result of UB?
 
which is a bit more than just "we did not think about this"
 
Or they are deliberately put there?
 
BTW, I guess languages like Haskell and friends have no UB
 
1:03 PM
You might argue that the item duplication trick from Pokemon Red is a result of UB, since it happens because junk data is left in a table where it shouldn't have been. But entering rosebud in the Sims 1 console window to get more money isn't UB because the devs intentionally put that command in.
 
Morning all o/ got that silly Lidar working
They had an issue in their API that was storing things in the wrong index of the list >.<
 
cheat codes essentially allows you to skip normal progression of things! like unlocking a weapon you would unlock only if you reach a certain stage
 
The extra lives code in Contra is not UB. The wrongwarp exploit in Ocarina of Time is possibly UB.
 
@DeveshKumarSingh Hell no. C has quite a bit of UB. But C took the radical approach of being explicit about accepting UB, rather than trying to get rid of it or ignore it.
 
@Kevin There are many in IGI as well.
 
1:06 PM
... International Gemological Institute?
 
it's a video game project igi
 
I am going in !
 
yeah, pretty old game
 
@DeveshKumarSingh Yes!
@DeveshKumarSingh With countless faults, never played anything like that, lol
 
On this topic, I recently enjoyed this video, which describes how you can walk through the entire memory space of Super Mario Land 2 with a simple glitch:
The world record for the game is accomplished by breaking the block that effectively corresponds to the "won the game? Y/N" boolean
 
1:12 PM
@MisterMiyagi Certainly! UB isn't random unpredictable stuff. It's grey areas in the language definition where compiler writers are free to choose whatever behaviour makes sense for their target OS & hardware.
 
I'm really stretching the definition of UB in my Pokemon and OOT examples since the assembly code is doing exactly what it was designed to do. The fact that the fallible human engineers designed it to do something dumb is a separate matter
 
@biggi_ awesome, good job
 
Maybe if there was a glitch that happened because there's a register that may only be written to during VBLANK and the code writes to it outside of VBLANK, that would be more UBish
 
so converting a list to a set to a list again, and it ending up being sorted is not UB in python
e.g
>>> list(set([1,5,3]))
[1, 3, 5]
and just how the way cpython behaves
 
@PM2Ring you can try assigning to a constant in a subroutine and get compiler-dependent results with old-style code
 
1:20 PM
and old style code is which python version if I may ask
 
Fortran 77
There were multiple signs that I wasn't talking about python
 
Not directly related to the issue of the orderedness of sets during list conversion, I notice that the stdtypes reference says "the output of the list.sort() method is undefined for lists of sets."
 
"Constant", "subroutine", "compiler" and the message I was replying to...
 
So we can't take "Python has no UB" completely seriously since the documentation contradicts this
 
Semantically undefined is a bit different in my head
 
1:23 PM
We also can't take it completely seriously because there was a winky emoticon
 
"Compiler can't decide" vs "no sense trying to decide"
 
I suspect the subtext is "Timsort does all sorts of wacky things on lists of objects with only partial ordering, and it would take a dozen pages to describe its behavior exactly, so we'll call it 'undefined' even though the result is entirely deterministic"
 
@Kevin Ah, ok. Fair point.
 
We need an acronym for "behavior that would be well defined if we bothered to define it"
 
Yup
MehB
 
1:31 PM
I wonder if you can construct a type with deterministic partial ordering such that sorted(my_list_of_things) != sorted(sorted(my_list_of_things)
I'm going to guess... Yes
(What exactly I mean by "deterministic" in this context is BTWBWDIWBTDI)
 
@Kevin Probably not, since TimSort is guaranteed to be stable.
 
Ok, so double-sorting will only be different from single-sorting if your comparator does something wacky like return random.choice((True, False))
 
1:47 PM
@Kevin if you take UB in the C sense, I don't think Python has it
I've never encountered time travelling...
 
@Kevin Indeed.
 
1:58 PM
Thinking about it some more, you can get non-idempotent sorted() even with deterministic code:
class Thing:
    def __init__(self, x):
        self.x = x
    def __repr__(self):
        return f"Thing({self.x})"
    def __lt__(self, other):
        return True

seq = [Thing("A"), Thing("B")]
print(sorted(seq))              #result: [Thing(B), Thing(A)]
print(sorted(sorted(seq)))      #result: [Thing(A), Thing(B)]
Thing does not implement partial ordering so this does not satisfy the conditions of my original thought experiment. Still interesting though.
We can also determine from this result that TimSort does not first check to see that seq[0] < seq[1] and return the list unmodified if it already looks sorted
 
a type that satisfies a > b and b > a seems pretty wacky to me
 
Yes, so we can't hold a grudge against TimSort for doing wacky things with our wacky type
It is written: garbage in, garbage out
 
interestingly enough, it does the same if __lt__ returns False
 
@Kevin OTOH, TimSort does utilize any sorted subsequences it finds, since it's a hybrid merge sort.
 
I can imagine a non-wacky type that implements __lt__ in a way that violates partial ordering for a good reason. For example, if you were writing a rock-paper-scissors game, then rock < paper < scissors < rock.
It's hard to imagine a justification for a two-item cycle, though. I struggle to think of a practical application of a > b and b > a
 
2:16 PM
Here's a wildcard class named Any, that returns True for equality tests, but it doesn't define the other comparison methods. stackoverflow.com/a/29867270/4014959
 
I've used that same design pattern in an answer too. Great minds etc
 
I suppose you could define a general cyclic comparison. For a given modulus m, (a-b)%m <= (b-a)%m or something like that.
 
2:37 PM
is there an easy way to get an inspect.Signature from **kwargs?
I would like to emulate a class where arguments to __init__ require methods to take the same arguments
 
2:55 PM
If I ever write wiki software, I will make it erase all instances of "it should be noted that" in articles, except when viewed by the editor that wrote it
it should be noted that "it should be noted that" is completely superfluous in 99% of cases
 
It should be noted that Kevin Kevinsson believes it should be noted that "it should be noted that" is completely superfluous in 99% of cases. [Citation needed]
 
^ noted
 
Fixed that for ya
Hmm lately I have disagreed with the image inliner's choice of default zoom. 828 pixels isn't all that wide, surely.
 
3:39 PM
is there is any way to check the file type, As I am writing functions to read json, txt, CSV file?
My concern is most of the code is the same except reading a part,
can we write only 1 function to read all above mention files and return there data?
 
@AmanJaiswal You can separate the file type from a file name with os.path.splitext. It's certainly possible to write one function that can parse json and csv and "txt" (the third one being the most difficult since there's no formal specification), although it may end up being a bit long
If you're asking "is it possible to determine the type of a file just by looking at the file's contents?", you can make an educated guess but you can never be 100% sure
 
00:00 - 16:0016:00 - 23:00

« first day (3135 days earlier)      last day (1816 days later) »