« first day (3377 days earlier)      last day (1571 days later) » 
00:00 - 18:0018:00 - 00:00

12:34 AM
reading a kind of TL;DR tutorial, it has getters and setters ... is that really used in python?
 
only with property
 
bleh
 
 
4 hours later…
4:11 AM
 Getting `Need more than 1 value to unpack (2 expected)` for


from typing import Union, List, Dict, Tuple, Any

import mysql
from mysql.connector.cursor_cext import CMySQLCursor

TDictRow = Dict[Any, Any]

TRow = Tuple[Any]

def query(
    query: str, dictionary: bool = False
) -> Union[List[TDictRow], List[TRow]]:
    db = mysql.connector.connect(...)
    cursor: CMySQLCursor = db.cursor(dictionary=dictionary)
    cursor.execute(query)
    result = cursor.fetchall()
    cursor.close()
    return result
 
@RE60K edit and ctrl-k it
 
does this work now?
i added 4 spaces.
 
I guess. so your mappings object is returning an iterable of one element, not two (tn, rtn)
make sense? so why don't you do...
for tn_rtn in mappings:
    print(tn_rtn)
    break
so you can peek at the first thing and see what it is?
Then maybe do something apropos with it.
@RE60K did you get that?
 
nvm. I got it.
it should have been Tuple[Any, Any]
thanks @AaronHall!
 
oh are you using mypy?
how are you liking it?
 
 
1 hour later…
5:34 AM
cbg guys o/
 
 
2 hours later…
7:43 AM
Hi, Is there anyone who can help with adding legend in altair plots?
 
user10984358
you should probably just ask, when people who know come online they will answer it for you
 
8:00 AM
I have following code.
import altair as alt
import pandas as pd

source = pd.DataFrame({
'Model Algorithms':['BERT for Sequence Classification',
'Convolutional Neural Networks',
'Deep Neural Networks: GRU, LSTM',
'Linear Discriminant Analysis',
'Light GBM',
'Logistic Regression',
'Naïve Bayes Classifier',
'NB SVM Classifier',
'Random Forest Classifier',
'XGBoost'],
'Count of Notebooks': [1, 2, 14, 1, 2, 5, 1, 1, 1, 1]
})



chart1 = alt.Chart(source).mark_bar().encode(
x = 'Model Algorithms',
y = 'Count of Notebooks')
Instead of names of model algorithms, I want to indicate them as A, B, C, D, E... and then add a legend saying A- BERT for Sequence Classification, B - Convolutional Neural Networks
Is there any way to add customized legend in altair plots ?
 
8:39 AM
Does somebody want to vote to reopen stackoverflow.com/q/59721109/562769 ? I'm not sure why it was closed in the first place
 
Im not quite sure what a reopen would achieve. The question basically requires the answerer to go through the code of one to three entire packages if there isn't an obvious reason why the files are that big. The question isnt wrong per se, but clearly the answer requires too much involvement, for this site. Too broad i'd think?
 
@MartinThoma it contains multiple questions, all of which are unclear or opinion based.
 
The funny part being, maybe the files genuinely needed to be that big, or need a major refactor. Either thing would be better suited for the individual github pages of the packages or so on
 
most importantly, if you want to know what's in that package -- why don't you take a look yourself?
 
yeah, it looks like one of those questions where its value relies on some very specific people offering an answer, like the "why is curl open source?" which was only popular because the author himself answered.
 
9:15 AM
137
Q: In case you missed it: Shog9 and Robert Cartaino are no longer staff members at Stack Exchange

GhostCat salutes Monica C.Today on "In Case You Missed It"… Shog9, a veteran Stack Overflow member and long-time Community Manager for Stack Exchange, recently Tweeted that he is no longer working for the company. An announcement was posted on Meta Stack Exchange to this end, thanking Shog9 for his years of service and ...

 
So finally I figured the issue with this flask cacheing. Will soon post an answer.
 
9:54 AM
Can we name a python module something like this: "Builder@1.0.py" ?
Is there any disadvantages?
 
@ is not a valid identifier
 
yeah, you won't be able to import it without some importlib or __import__ shenanigans
 
@MisterMiyagi Because it comes under special character?
 
it's an operator
same for . as well, come to think of it
 
@Aran-Fey Oh okay
 
9:56 AM
more specifically, it's because it falls outside the characters that are allowed for variables in python
 
>>> import Builder@1.0
  File "<stdin>", line 1
    import Builder@1.0
                  ^
SyntaxError: invalid syntax
 
@MisterMiyagi Is there anyway then to put a version value as part of module name itself?
 
you can go for Builder_1_0.py
 
Just use the variable name guidelines for module names as well, so just alpha numeric and underscores. I will admit i've actually never tried underscores in module names
 
@Aran-Fey Thanks for live demo
Thanks Melon MisterMyagi, Aran and Paritosh kun
 
9:58 AM
but consider that if you use versioned names, you effectively hard-code versions in your application.
Which usually isn't the point of versioning.
 
By versioning, I meant to have multiple version of same file which will handle the case of deprecation in future?
Or is it not the correct way?
Let's say I have version 1 of Builder module which will get deprecated after certain point of time, and we will introduce another Builder with version 2. However we don't want to have impact on previous usages so the first version will survive as a legacy module.
So for this very purpose, How should I name this module if not the way I just showed?
 
do you want someone to have to rewrite all their imports and variable accesses if they wish to upgrade?
 
depends on if there is some public module that hides the versioning.
E.g. pickle supporting, erm, more than 4 versions right now.
 
@ParitoshSingh May be? I mean depends if needed
 
it's not immediately clear who is "consuming" your Builder modules, is it people outside your organization for example, or people who you're perfectly capable of telling to adjust the internal codes
 
10:05 AM
@ParitoshSingh not outside but within team
@MisterMiyagi Oh! How does it work for them? Do they name the module in certain fashion?
 
10:19 AM
Basically you have a public module that accesses all the private, versioned code. For the private code, you can use whatever ugly method is necessary.
 
Melon
For now I'll just drop the idea, looks like a big headache :D
Is it okay to quote a part of the answer posted for another question in my answer because that part is answer to my question ?
The example is different though, but the solution and explanation is same.
Or may be I should ask that answer poster person to post another answer on my question and he can just replace the example part with my example code?
This is the answer btw: stackoverflow.com/a/20041823/1944896, the answer to my question should be clipped from subheading "Running code outside of a request"
@MarkHildreth Cabbage o/
 
11:00 AM
@MartinThoma too broad
 
 
1 hour later…
12:14 PM
@AndrasDeak Any suggestion here ^ ?
Have invited the user too.
 
Quoting answers from other questions is fine if you give attribution (link back). Of course if the questions are close enough it's also an option to close as dupe.
 
It's not close enough.
It's just one of the answer covers the solution for my question.
 
I think it's alright to quote them
 
Melon Andras! Since I invited the person in our room-6. Shall I wait for his response?
before self-answering
 
yeah, that seems reasonable
(especially since they are still very active)
 
12:23 PM
Yeah right! That was the very reason why I have invited them in chatroom.
 
@do_twice
def return_greeting(name):
    print("Creating greeting")
    return f"Hi {name}"
does anyone understand the f in that return?
 
@Permian f-strings introduced in python 3.6
 
@AndrasDeak i have never heard of them
 
Now you have. Go google.
 
12:24 PM
damn i am out of date a bit
 
A wild @Катерина appeared!
Hope you are aware of the game Pokemon Go!
 
I'm pretty sure it's not just Go
 
I mean "wild X appeared" is probably present in all the pokemon games
I've never played any of them, but this had been a meme long before Go was a thing
 
12:42 PM
I see
Anyone have worked with Flask Streaming APIs? I got a suggestion from my TL, that instead of cacheing data I should use streaming.
 
@ParitoshSingh it's possible, and a few packages do it. but I avoid it because there are some contexts where they will be turned into dashes, so for me it's alphanum only
 
Lulz
Hey @TheLittleNaruto
 
My current implementation is, I load list of documents at one go and divide them in different pages where each page will contain say 25 documents
 
@TheLittleNaruto They're fairly different things - what exactly are you trying to do?
 
Let's say I have 100 records which will make total 4 pages with 25 documents each
Every page will act as a key and the data will be the value set to it
This is one time job for a certain data. Next time, client request for a page specific data I get it from the cache and give it back to the client
So Logic goes like:
-> Request received
-> generate pages and associated data and put it to cache (if not present already else skip to next step)
-> return the data to the client as per page request
@JonClements
 
12:55 PM
Which sounds reasonable... not sure of the reasoning of suggesting streaming in that case...
 
This is current implementation
 
Sure... I don't get what use streaming would be though...
 
@JonClements Where should we use streaming one? Like it is suggested in document that if we want to send an enormous amount of data to the client on the fly, then streaming is your only friend
Isn't it my case same?
I am doing pagination thing because of the data being enormous
 
It depends... how big are the responses... streaming can be a lot of work for no gain...
 
@JonClements Also notice that we will be using a lot of memory for cacheing...
Right now it's not that big, but 10k like documents max
 
12:59 PM
what is a "lot of memory"...?
 
I mean memory used for cacheing. over the time it'll keep increasing, right?
 
raw_data['ALTURA'] = np.nan if raw_data[raw_data.ALTURA == 0.00] else (99)
raw_data
 
@TheLittleNaruto not really... you should ideally have a reasonable time to live for cached entries so non-recently accessed stuff drops off leaving more space for newer stuff
 
@ruben.lfdz "use any() or all()"...?
 
1:04 PM
can anyone tell me what am I doing wrong in here: thanks raw_data['ALTURA'] = np.nan if raw_data[raw_data.ALTURA == 0.00] else (99)
raw_data
@AndrasDeak where exactly?
 
@ruben.lfdz You're not giving us an MCVE, for one.
 
@JonClements Yeah right! So cache-pagination way is better?
 
@ruben.lfdz I would expect that expression to give you an error
 
@AndrasDeak sorry I'm new using this and python
 
something like raw_data['ALTURA'] = np.where(raw_data['ALTURA'] == 0, np.nan, 99) might work, I don't know if there's a more idiomatic pandas solution. But I see multiple pitfalls here
 
1:06 PM
From what you've described - as far as I can tell - yes... @TheLittleNaruto - just sounds like you might want to look at a reasonable time to live for the cache if you haven't already...
 
@ruben.lfdz then I suggest that you first read a python tutorial then a pandas tutorial
 
@JonClements You got it right. Thanks Melon so much.
 
@AndrasDeak thanks a lot that helped me ! and instead of returning 99 what value can I use to leave it as it is? raw_data['ALTURA'] = np.where(raw_data['ALTURA'] == 0, np.nan, 99)
 
Rhubarb o/
 
@TheLittleNaruto Probably worth checking with your TL though... maybe they have something specific in mind when they mentioned streaming...
 
1:12 PM
raw_data['ALTURA'] = np.where(raw_data['ALTURA'] == 0, np.nan, (number already in the cell )
 
I'm doing END_OF_SEQUENCE = object() so I can use it as a sentinel object later, for example if item is END_OF_SEQUENCE: break. This works, but when I print my sequence, it displays as [23,42,99,<object object at 0x00E356C0>]. I could do something like END_OF_SEQUENCE = "$" instead, but there is some risk that the sequence will contain actual dollar signs.
Is there any way to get a unique copy of a string, which won't be used later by the interning engine?
 
>>> df
   a
0 -1
1  2
2 -3
3  4
4  5
>>> inds = df.a > 0
>>> df.a[inds] = np.nan
>>> df
     a
0 -1.0
1  NaN
2 -3.0
3  NaN
4  NaN
@ruben.lfdz one way ^
 
is it really that bad it print as that @Kevin - any issues with creating an instance of an object that just has its own unique __repr__ ?
 
but checking floats for exact equality is unreliable if your numbers are the result of some arithmetic stackoverflow.com/questions/588004/…
@Kevin what Jon said
 
Writing a custom Sentinel class would be four entire lines longer than just doing END_OF_SEQUENCE = unique_copy("$")
 
1:15 PM
any decent unique string-like will have a unique repr by default
 
@AndrasDeak ok thanks
 
@Kevin use a null byte. What could possibly go wrong?
 
use the sequence itself as a sentinel
 
@Kevin maybe something like: EOS = type('EOS', (str,), {})('<EOS>')
 
This is how I solved it, thanks a lot for your help v = raw_data['ALTURA']
raw_data['ALTURA'] = np.where(raw_data['ALTURA'] == 0, np.nan, v)
raw_data
 
1:21 PM
So why did you ask?
I mean np.where is usually slow, indexing is fast
 
@TheLittleNaruto We are trying out streaming in our REST API for calls that return many records and don't want to hassle with paginating. If you search the room archive, we had some discussion on it recently. Note that you also have to write special stream-aware code on the client - important special note: in that special client code, be sure to specify a chunk_size or else requests will use a useless default of 1. My tests showed that 32 was an adequate size, but I use 1024.
 
@AndrasDeak this is what I can uderstand so far about python. as indexing is a bit complex at the moment. Thanks I appreciate it anyway.
 
"slow and working today" is often a win over "lightning fast and working next week"
Oh, and cbg
 
I think I'll go with "keep the current design and accept that your diagnostic prints will be a little weird looking", with an option to define a proper Sentinel class later if I ever need to display the sequence for non-debug purposes
 
1:46 PM
@Kevin You no like my type? :p
 
if this were a web server he could say "we don't serve your type here"
 
Three argument type is not to be used by mortals such as myself
 
but... you are not mortal... you are Kevin! :)
 
1:58 PM
I'm still mortal. It's true that I can't be killed except in a sword duel with a Fields medalist during a waxing crescent moon, but that's a far cry from immortality.
"Code as if the next person who maintains your project is a psychopath who knows where you live" still applies to me. A sufficiently determined psychopath could easily find the one ancient tome describing my weakness, win a Fields medal, and become an olympic level sword fighter.
 
2:11 PM
Ahh well... when you put it in such realistic terms - I feel foolish for my suggestion! :)
 
My attempts to ensure my longevity by destroying the International Mathematical Union, the Moon, or the concept of swords, are still ongoing
 
Hi
Has anyone used the websockets lib? I am trying to use it for the client but having difficulty.
 
I used it exactly once.
 
I'd like to set it up like events (does this exist in python). So an on_message function, etc.
Does anyone have a better lib if this one isn't great?
 
event-based frameworks exist in Python, yes. For example, tkinter handles user input this way. I don't know whether websockets provides a convenient event-based framework.
 
2:21 PM
morning cabbages all
 
Worst-case scenario: you write your own event framework with a custom loop that checks for incoming data and calls the proper callbacks
 
hmm
thanks
looks good
 
@JBis you might also want to look at autobahn
The kind of model you mentioned is kind of demonstrated at: autobahn.readthedocs.io/en/latest/websocket/programming.html
 
what framework does everyone know use with python?
 
@Permian it'd depend on what they're doing...
 
2:33 PM
@JonClements large scale web apps
 
If you're asking "is there some library that every Python developer has used at least once?", no, because there are plenty of Python developers that have never used any library. In particular, the developers that learned the language in the last 24 hours.
 
ie mean
is it django or flask?
 
Neither Django nor Flask are used by "everyone"
I don't use either one because I don't do web development in Python.
 
or pyramid or bottle or cherrypy or falcon... depends what they're building and other things
 
@JonClements do you have any examples?
 
2:34 PM
If you're asking "what is the most popular Python web framework?", I don't know.
 
@JonClements awesome! thanks
 
@Permian I s'pose you could look at pypistats.org for download counts... but that's not going to translate into what people are using what for what level of stuff...
 
@JonClements how could i find out>
?
 
Incidentally, there are other kinds of frameworks than just web frameworks, so when you ask "what framework does...", the reader won't necessarily assume that you mean web frameworks specifically
 
@Kevin i dont know what the differences could be...
 
2:38 PM
If you're saying "I can't imagine what a framework would do if it's not a web framework", check out en.wikipedia.org/wiki/Software_framework#Examples. If you're saying "I don't know what the differences are between django or flask or pyramid or bottle or cherrypy or falcon", I don't know either.
 
Always interesting when people contact me regarding doing their assignment... I say no but it's always interesting to see what kind of assignments are being handed out these days... dw3i9sxi97owk.cloudfront.net/uploads/jobAttachments/… doesn't look particularly complicated - guy must be a right slacker or something...
 
why when I put the last argument within the function it doesn't work ..................................... ........... def extraer_altura(raw_data):
raw_data['ALTURA'].fillna("0000", inplace=True)
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.replace(",",".").replace("'",".").replace('\u200b',''))
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.replace("[1]","0").replace('’','.'))
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.strip())
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: float(x[0:4]))
 
anyone familiar with sklearn? Do I need to preprocess categorical data or can I send it directly, when using a random forest?
i.e. do I have to convert the category strings into category numbers, or can I send in the strings as features themselves? Couldn't find a document that discusses this
 
whereas if I put it in a new input cell it does....................................................................................................... raw_data['ALTURA'] = np.where(raw_data['ALTURA'] == 0, np.nan, raw_data['ALTURA'])
 
@ruben.lfdz Hmm. I'm interested in investigating, but I'll need an MCVE.
Keeping in mind that:
Dec 30 '19 at 13:53, by Kevin
The gold standard for numpy/pandas MCVEs is to have zero dependencies on any data files whatsoever - instead, the data should be embedded into the program as a list-of-lists, or a multiline string that you parse somehow
 
2:52 PM
@ruben.lfdz Can you please format your code properly? It is very hard to read, yet also enough to be hard to ignore as well.
please see the code formatting guide
 
Yeah, putting fifty dots between your problem description and the code is not the best way to display your code.
Better to have one message for the problem description, and one message (with code block formatting) for the code
I usually let unformatted code slide if there is exactly one possible way to indent it into a functional program, but as long as we're on the topic...
 
#why when I put the last argument within the function it doesn't work                                                                                                    def extraer_altura(raw_data):
raw_data['ALTURA'].fillna("0000", inplace=True)
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.replace(",",".").replace("'",".").replace('\u200b',''))
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.replace("[1]","0").replace('’','.'))
raw_data['ALTURA'] = raw_data['ALTURA'].apply(lambda x: x.strip())
 
Ok, progress is being made. But there's no indentation here and even with indentation it's not an MCVE, because I can't copy/paste/run it with no modifications or other extra work on my part.
 
sorry I'm new to this. Thanks for your help in advance
 
@ruben.lfdz being new is fine. But you were already told where to learn about posting code to chat. Take your time to learn.
then again I also suggested reading a few tutorials before writing code, so we're in for some interesting misunderstandings I expect
 
3:02 PM
@ruben.lfdz just to note - a lot of that is fairly verbose... you can use the .str accessor on Series objects and keep chaining those if you need to... so your first line would just instead of .apply(...) be .str.translate(str.maketrans(",'’", "...", '\u200b')) or similar
 
ok Thanks a lot. I'll have a read
 
3:25 PM
I changed my mind from last week, you can write a recursive descent parser for arbitrary arithmetic using only one token of lookahead. You just have to construct your language in ways that don't make a lot of semantic sense. For example, consider Python's grammar rule, xor_expr: and_expr ('^' and_expr)*. This rule indicates that, in an XOR expression, the "^" and the right operand are optional. 23 is technically an XOR expression.
Granted, in ast.dump(ast.parse("23")), there's no BinOp node with operator BitXor, but we've already established that CPython takes creative liberties when it comes to actually parsing the language
 
the AST isn't the same as the parser. if your xor_expr rule decides to emit a pink unicorn node, jolly good.
 
3:40 PM
Here is a smallish prototype working on the same principle.
Which effectively parses the grammar:
lang            := add_or_sub
add_or_sub      := mul_or_div (('+' | '-') add_or_sub)?
mul_or_div      := atom (('*' | '/') mul_or_div)?
atom            := '(' add_or_sub ')' | INT_LITERAL
 
@MisterMiyagi "pink unicorn node" should definitely be a thing :)
 
Despite the rule indicating that add_or_sub can be either mul_or_div or mul_or_div ('+'|'-') add_or_sub, the function parse_add_or_sub only ever returns nodes with three parameters
A "strict" parser would take "23" and return langNode(add_or_subNode(mul_or_divNode(atomNode('42')))), but this one just returns IntNode(42)
 
@JonClements PEP-129412: the 🦄 operator!
 
3:56 PM
Ugh.. I'd add it as CEP12 on sopython.com/wiki/Cabbage_Enhancement_Proposals but alas... there's that pesky CEP5
 
4:10 PM
can someone explain the answer to this:

list(range(1,9,2))
 
the answer to what question?
 
@Kevin Does '?' mean "0 or 1" or "0 or many"?
 
0 or 1.
I could have written my parsing functions to parse 0 or many, but it would have been more work, so meh
 
start counting at 1
end counting at 9 (but don't include 9)
count in steps of 2

So: 1, 3, 5, 7, ---9---
 
list of range 1 to 9 with step 2?
 
4:11 PM
The evaluator doesn't care either way
 
so if it was list(range(1,10,3)) the result would be 1,4,7?
 
Multiple consecutive uses of the same operator are still matched by the grammar, in either case. "1+1+1+1+1+1+1+1" is legal, for instance
 
Those look to me like right-associative operators. Are you sure your evaluations are giving the right values?
 
@drleechy that's right
 
I just have to recurse way deeper, the way I'm doing it
 
4:13 PM
3-2+4
 
okay thank you guys
silly question i know!
 
If evaluated right-associative, do you get -3? or do you get the correct answer of 5?
 
Let's see. I get -3.
 
Yeah, not what you want. In pyparsing I have to do add_or_sub := mul_or_div (('+' | '-') mul_or_div)* but then I have to deal with the repeated operators in my evaluator.
 
I can reverse the associativity by rearranging the tree during the parse_add_or_sub call, but that's rather inelegant
 
4:17 PM
Pretty sure Guido mentions this in his PEG parser posts too
 
I think that's what I do in KevinScript, actually. But inelegant code is specifically allowed in that code base.
 
if s1 = [1,2,3,4]
s2 = s1[:]

what is the result of s1 is s2?
 
why?
 
If you type this in to the Python interpreter, what do you get?
 
4:19 PM
Can room6 stop being the worst python interpreter in existence, please?
 
sorry. I'll stop
 
Slicing a list creates a new list which is referentially unique, even if its contents are identical to the original
 
@inspectorG4dget Or go to private chat if you enjoy this
 
@Aran-Fey Quick, someone start using 2.x!
 
@PaulMcG I'm only able to chime in because I'm waiting for a script to finish
 
4:21 PM
<Room Owner mode> If the question you mean to ask is "code X produces the output Y. Why?", please ask it in that format instead of "You: what is the output of code X? / Answerer: the output is Y. / You: Why?"
Presumably you have an interpreter in front of you so you already know what output your code is producing. Double your question efficiency by only asking questions that you don't know the answer to yet
 
Also, the interpreter has a nice feature to access the doc strings of the core Python objects and methods. Try help(range) for notes on what the args mean and how they are used.
 
Also acceptable is "When I execute code X, I get output Y. Is that result specific to my session / version / machine? Are there circumstances where it outputs something other than Y?"
Just in case you were wondering if s1[:] always returns a referentially unique result, or if it just happened to return it this time
 
under what circumstances would python appear to do something different for the same code?... except I guess when random is involved
 
random is a big one, yeah. And anything where the result is implementation dependent or just not specified in the docs
Example: does print(object()) always print exactly <object object at 0x015055F0>? Answer: no, the number is usually different because the documentation doesn't give any guarantee about where objects are allocated in memory.
 
Hmm, TIL PEP8 explicitly suggests writing return None where it would otherwise be implicit eg def f(x): if x >10: return 'huge' should have an explicit return None
 
4:32 PM
I don't mind doing return None to ensure that all possible branches in my function have an explicit return statement. I won't do it if my function always returns None, though.
It is written: explicit is better than implicit.
 
This is fair. I feel it makes that example look much more verbose. Kinda like I'd omit the implicit else in that example too.
 
oh I love plopping if <cond>: continue/return and exluding the implicit else. I guess that makes me a monster
 
In practice I don't have many explicit return Nones, because I don't usually use None to signal an error value or whatever. If one branch of my function returns a string, then it is likely that every other branch will return a string too.
def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        raise ValueError("Can't foo negative values")
@inspectorG4dget I do if cond: return a lot, too. But PEP8 permits this, as long as all your other returns are also argumentless.
 
@inspectorG4dget Not to me. Although I'll occasionally write # else if it looks clearer that way.
def f(x: int) -> Optional[str]:
    if x > 10:
        return 'huge'

# This feels particularly verbose when you consider the same information is conveyed by the typehint:
def f(x: int) -> Optional[str]:
    if x > 10:
        return 'huge'
    else:
        return None
 
It's proportionately less verbose in larger functions
Here, it's a difference of 50% of the function body. For a twenty line function, it's only 10%.
 
4:44 PM
@Kevin I should have clarified: I rarely do argumentless returns, but I do a lot of early returns. I think PEP8 has a darttboard with my face on it?
 
I guess the typehint could be considered to only explicitly convey the possibility of the function returning None, rather than the case it returns None. More complex functions (which I try not to write...) might have an explicit return None but never just a bare return.
I only found this out because mypy complained, lol
rbrb
 
I also like early returns, so if I did write a noneful f(x), I'd do it like:
def foo(x):
    if x < 0:
        return None
    return math.sqrt(x)
I don't think PEP8 has any opinion about whether that's better or worse than the other form
 
def foo(x):
    if x<0: return
    return math.sqrt(x)
how much does PEP8 hate me for that?
 
It doesn't like that. It would prefer that return to be a return None.
"If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None"
 
also one-line ifs are bad
 
4:55 PM
I largely agree, but is that PEP8's opinion, or the community's opinion?
 
PEP 8
Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

Rather not:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
 
Ah. "Compound statements (multiple statements on the same line) are generally discouraged." Ok then.
"generally discouraged" being a peg or two above "never do this"
 
"rather not" is better than "no" so it's -0
glad we agree :P
 
I'm bad, I used compound statements today :-I
        l,r = evaluate(args[0]), evaluate(args[1])
        if op == "+": return l+r
        elif op == "-": return l-r
        elif op == "*": return l*r
        elif op == "/": return l/r
Heresy detected
 
at least it was a peg or two above "never do this" ;)
 
4:58 PM
and here I thought "compound statements" were statement that contained other statements, like if or while or class
 
(also, if it helps, i find your version fairly readable honestly)
 
@Kevin If this were a real language you could do l eval(op) r ;)
 
I was also considering the sin of extra whitespace so return l+r would align with its counterparts
I love aligning things and no PEP is powerful enough to stop me
 
I sometimes do that too. But I'd have used operator for your switch I think
 
Yeah, I probably could have had a dict of operator.whatever instances. It was only a toy example, so I didn't apply maximum rigor
 
5:23 PM
Here is a recursive descent parser for arithmetic with proper associativity. As I feared, it requires me to keep an explicit stack of values which I combine into an AST long after I've consumed the equivalent tokens
Taking a page out of PaulMcG's book by doing add_or_sub := mul_or_div (('+' | '-') mul_or_div)*
No change required for the evaluator since I didn't bother to make an add_or_subNode that can have more than two operands
That means my tree is unnecessarily deep for programs like 1+1+1+(... 100 more of these...)+1, when in principle it could be a single node with 104 leaf nodes. But CPython also makes an unnecessarily deep tree for that program, so I'm in good company.
I'm not sure it's possible for me to write a recursive descent parser that doesn't use an explicit stack and returns something other than the rightmost derivation of the parse tree
 
@Kevin That's actually exactly what it does in the PEP8 example, it rewrites the if to have it return None instead of the implicit. In my particular case today, that'ld involve somehow figuring out whether there will be a Pythagorean triple summing to a given number, returning None if not, otherwise returning the triple.
 
Comedy option: before tokenizing the string, reverse it. Then feed it to a parser that matches backwards programs. Voila, a leftmost derivation.
 
@inspectorG4dget Mypy probably won't complain, which was my initial issue ;)
 
use black, it will complain
 
mypy is not a linter, is it?
 
5:34 PM
type checker
 
@Kevin Works for all palindromic ints
 
or at least not a general-purpose one if we include any kind of static analysis linting
flake8 would be more appropriate for this, right?
 
Hmm, I wonder how many code linters are smart enough to not mark this as "needs explicit none":
def foo():
    for i in itertools.count():
        if f(i):
            return i
I expect most linters can't solve the halting problem in the general case, but maybe some have a good idea of when itertools.count terminates (ie never)
 
unless it's another itertools or someone's monkeypatched it
 
Users that monkeypatch count have voided the warranty and must accept the possibility that their linter will hand them nonsense
 
5:38 PM
Hi all,
need advise on how to iterate over grouped dataframe.
I have divided a df into n df which is based on a unique values in a column, Now I want to iterate over the sub dataframes but unsure how to use the naming convention to automate without manually entering the df name.
 
just iterate over the groupby object? That should work just fine
If not, can you prepare a small example as an mcve?
 
@Stramzik Is this question related to stackoverflow.com/questions/59736809/… ?
 
@PaulMcG yes
 
You've already gotten 2 answers there, why are you asking here?
 
i have updated the sample df
 
5:43 PM
@Kevin Mypy doesn't have an issue, at least when defining def f(x): pass...
 
Interesting. I kind of expected the answer to be "none; all linters consider this a violation"
 
We generally prefer for questions to have a couple of days for the community at-large to answer them before raising them here - there are some room rules around here somewhere...
 
The answers tell me how to group, but i'm confused on how to iterate over the subdataframe. If I used a groupby object how do I iterate over the rows?
 
the same way you iterate over a dataframe
(which, by the way, is a horrid thing to do. don't iterate over dataframes)
So, each group has a key and a dataframe. Just iterate inside the loop.
 
<RO Hat> Yes, we usually like to have a waiting period for question solicitation. I'll give a one-time dispensation here since we're already talking about it. </RO Hat>
 
5:55 PM
@Kevin ...unless you give it a typehint for a return, then it registers an error, either with -> int: or -> Optional[int]:
 
also the pandas tag is missing in the question
 
Does df.groupby work the same as itertools.groupby? I have used itertools.groupby before, but not the pandas one. And does df.groupby require the df to be sorted first, the way that itertools.groupby does?
 
@PaulMcG No
it doesnt need to be sorted
 
@PaulMcG no, but at the same time, itertools groupby doesnt require the df to be sorted either :P depends on what you want to do
 
:)
 
5:56 PM
More specifically, df groupby will make 1 group for 1 key, and not care if the key appeared sporadically/disjointed or not, unlike itertools groupby.
 
Whereas itertools.groupby only knows how to group contiguous elements - so to group by a value, the entries with those values need to be contiguous, which is most easily/commonly done by sorting, but not the only way...
 
Aye. So far, there's been a total of exactly one instance where i had a dataframe that needed the itertools groupby, and where the dataframe groupby did not give me what i needed.
 
00:00 - 18:0018:00 - 00:00

« first day (3377 days earlier)      last day (1571 days later) »