« first day (3050 days earlier)      last day (2122 days later) » 

anybody else read the time stamps like in spongebob?
which timestamps?
"n hours later..."
00:37
'3 hours later...'
 
1 hour later…
01:59
@Code-Apprentice sure I will.
 
4 hours later…
05:48
-1
Q: How to map a dataframe df (having two columns) with another dataframe df1(having three columns) and update it

hukkemaaruhave a df1 with values 0 1 0 abcdef | unknown 1 uvwxyz | unknown 2 cricket ball | unknown 3 tennis racket | unknown And df2 with values 0 0 1 0 abc | def | password 1 cricket| ball | password1 2 tennis | racket | ...

can anyone help me with this
Can anyone help me on this.
>>> hex_data = "8100060000000680"
>>>
>>> print binascii.unhexlify(hex_data)
ü  Ç

The above output is in not readable format.So how to make it as readable ?
06:14
@AbdulvakafK I'm pretty sure that data isn't text.
>>> import binascii, chardet
>>> s = binascii.unhexlify('8100060000000680')
>>> s
b'\x81\x00\x06\x00\x00\x00\x06\x80'
>>> chardet.detect(s)
{'encoding': None, 'confidence': 0.0, 'language': None}
Thanks. But I just wanna know what is the difference between
print S and simply S.
If I do print s then console output is unable to read. And If I simply do 's' and press enter then I am getting the readable o/p on console.
@hukkemaaru Please read the room rules, specifically "Asking a Question".
Sure. Wont repeat that again.
print(s) outputs str(s) while s (in the interactive console) outputs repr(s)
In other news: cbg.
06:26
cbg
The weather has gone crazy. +2 or so a day before, -20 today, +2 again on Saturday.
 
2 hours later…
08:01
cbg
08:19
Cbg
cbg
 
2 hours later…
@hukkemaaru one of my greatest failures
(not really, I have worse)
@AndrasDeak I feel like a good third of all the questions that flow into the pandas tag could be closed with reasons like this. It feels like a losing battles sometimes.
Yup
Still worth fighting
quite so. It's fun not having to answer as much, I get to do other helpful things on the site
 
1 hour later…
11:14
recbg
Hi guys,
I've been searching for this and I see that this question is quite popular, but is there a way to load and use objects of a DLL created by .NET in Python?
For example, I have a .NET DLL that controls a light source, can I use it someway? (not only by static classes)
I think ctypes can do that
11:45
and do you think it's possible to create and use objects?
not sure what you mean. As far as I know, dlls contain only functions, not objects
you can instantiate objects of the classes that the DLL exposes and use their methods
this is what I'm trying to get
my uninformed guess is that yes, that should be possible :p
12:02
@miguelmpn Of course. The ctypes docs explain how to do that, and you can see an example of using a DLL in my answer here.
the only thing I know about DLLs is "those things you have to copy around if something doesn't work in windows"
Note that ctypes is intended for interfacing with libraries written in C. It doesn't understand fancy OOP objects.
I'm not so sure that .NET dll's are ctypes-friendly.
You may need a .NET-aware version of Python (IronPython). You might also try a pythonesque language called 'boo', which could import .NET dlls directly (can also compile .dlls and .exes that will run with .NET) (boo-language.github.io)
great info
@AndrasDeak Briefly, a library is a collection of functions & associated structures. It's kind of like a program without a main() function entrypoint. So any program can open a library & call its functions without the need of compiling the functions into the caller.
12:13
Also, if you are messing around with .NET dlls, look into the ilmerge utility, which can package up needed DLLs into a single .EXE
@PM2Ring thanks
If just written in C, a Windows DLL is like a Linux .so, and ctypes can import and use their contents. But .NET DLLs are a different kettle of fish entirely.
@miguelmpn So if you can find a plain DLL that has the functions you need, rather than a .NET DLL, you can just use ctypes like in my example. Otherwise, you'll need to follow PaulMcG's suggestions.
@PaulMcG does that also imply that only .NET DLLs may contain classes as miguelmpn wants?
Yes, especially since his original question mentioned that it is a ".NET DLL" that he is trying to access. But yes, generally DLLs or .so's contain only non-class functions, or export non-class entry points might be a better way to say it. Even with C++, you can export C entry points. This is a common method for exposing OOP code via static entry points.
^^ done using extern C { ... } in the C code. Note that this is done at compile time.
.NET DLLs (re-skimming the ilmerge docs, I see they prefer the term "assemblies") contain classes, complete with the magic registry keys needed to identify them in .NET world.
rbrb need to head off to the office/grindstone...
12:57
still trying. tried regex-es to map them tried this import re

XYZ = XYZ.dropna()
d = dict(zip(XYZ[0].str.lower(), XYZ[1]))
for k, v in d.items():
ABC.loc[ABC[0].str.contains(re.escape(k), case=False, na=False), 1] = v
13:09
You can use Ctrl + k to format code, so that it is easier to read
Every time I want to play with a DataFrame post, I have to look up that magical method that can parse nicely-printed data back into a real object. What was it again? read_table? Something like that.
still trying. tried regex-es to map them tried this

import re
df2 = df2.dropna()
d = dict(zip(df2[0].str.lower(), df2[1]))
for k, v in d.items():
df1.loc[df1[0].str.contains(re.escape(k), case=False, na=False), 1] = v


https://stackoverflow.com/questions/54799998/how-to-map-a-dataframe-df-having-two-columns-with-another-dataframe-df1having
Note that Ctrl-K (Mac: Cmd-K) works on the whole post, so you can't mix plain text and indented code.
@Kevin Shame, just think that you could do the magical bit yourself ;)
Unpopular opinion: I'm ambivalent about whether code is properly formatted in chat if it's missing only a single indent.
@Simon I literally do not know how to make a non-blank dataframe.
13:20
FWIW you can use a dict of lists to fill it columnwise
@Kevin Is ambivalence an opinion?
Kind of a Schrödinger's Opinion.
A friend of my wife's had a nice expression: "I'm plus-minus on that." And she wasn't even a math major.
I don't really know but in stackoverflow.com/questions/54808161/… can't a npy file just be closed and opened several times (numpy.load())? Wouldn't that count as autoreloading
@Simon yes, or even rewound an read again without closing
14:19
Except if a new file was created, rather than the old file being truncated and rewritten, the rewind would surely just take you back to the beginning of the old content, in a file no longer linked to the directory structure - in Unix systems, anyway. I have no idea what would happen under Windows.
Such issues can be maddeningly invisible.
So it would work in some situations
@Simon Maybe the OP on this question was really asking how to get the extension to re-read the file?
Hmm, is there an option for pandas.read_table to ignore the row numbers? For example, the 0 1 2 and 3 in the first dataframe of How to map a dataframe df (having two columns) with another dataframe df1(having three columns) and update it are not actually part of the data
"Just delete them manually from your file before parsing it," you say. Yes that's possible, but it's not terribly convenient if I need to parse a thousand rows.
“Thanks for the help, folks.” – I am apparently considered plural now.
14:33
I was about to say "forget it, I'll just create the dataframe from a dict of lists" but now I see that df2 has two columns with identical names, and dicts can't have duplicate keys, so that won't work either
Plan C: wait for OP to provide an MCVE. I like this plan because I don't have to do anything.
\o cbg
14:51
cbg
15:04
I just got upvoted on a 2.5 year old question. So I take a look, the question and answers are kind of ridiculous. So I answer it myself. I still feel funny though answering my own question 2.5 years later.
@piRSquared upvotes are a nice mechanism to review old questions/answers that are getting traffic
Just yesterday I got an upvote on this question, and on re-reading it I noticed that it was pretty much obsoleted by official docu by now.
At some point I should attempt to review my questions and answers in a more systematic way
> Top Posts (5,569)
might take a while =D
(-: yeah
15:30
I'm not sure if this is the right place to ask, but what might be the cause of periodic drops in CPU utilization [1] of a python process(es) ? Thanks in advance!

[1]: https://github.com/shivansh/parallel-video-streaming/tree/master/benchmarks/10-client-plots

Context: https://shivansh.github.io/posts/2019-01-09-Revisiting-networks-project/
I'm inclined to blame any and all CPU percentage weirdness on the OS
As long as there is more than one process running on my computer (and there almost always is), I don't expect my process to get consistent cpu usage
@Kevin I also had this thought because this exact behavior was replicated for different applications, just wanted to confirm if maybe there was something concerning python.
Theory 2: maybe not all drops in CPU% are caused by the OS pausing the process to give attention to other processes. Maybe a process running uninterrupted at full speed might vary its CPU% depending on what operations it is carrying out.
Modern CPUs can execute multiple instructions at once thanks to the instruction pipeline. Maybe CPU% is highest when the pipeline is optimally executing many instructions at once. Maybe CPU% drops when the pipeline gets clogged, for example when evaluating a branch whose outcome can't be predicted.
In any case I'm not inclined to blame Python specifically
16:06
CPU usage % is periodic in 2*pi so it's only expected to see jumps at 6.28 %
@AndrasDeak Interesting! Are you aware of any references concerning this ?
sorry, it was a lame joke about angles in radians
Do I understand correctly that you have 6-7% CPU use?
Then I wouldn't try to deduce too deep conclusions from that. Small numbers fluctuate, and in an OS with multiple processes you can't know what's going on.
If it were a change from 99% to 70% we could argue that it's about python
I wonder how much CPU usage a process would have if you designed it specifically to have maximum pipeline usage. Just a million lines of assembly that increment six independent registers over and over.
16:13
which is more or less what Kevin has already said, but the fact that we're talking about a change from 7% to 6.9% suggests that I'd just ignore it
16:30
This is very bad form right?
def bla():
    print(param)

if __name__ == '__main__':
    param = 5
    bla()
I don't understand how I keep finding terrible things and lack of basic programming guidelines in nvidia research code, like a lot. I mean I get it, it's research code and you have time pressure etc, but this kind of coding just looks like you are trying to make your life more difficult...
I don't know about very bad. And in general, one would pass the param as an argument to bla() instead of accessing it globally. But sometimes param is a config that is global to your script. While still not great, I'd say this is fairly common.
Creating constant values at the file level scope is not necessarily bad. Conditionally creating constant values at the file level scope and using them in other scopes that don't guarantee that the condition passed is bad.
In other words, I would have given it a pass if param = 5 came before the if.
What about param = int(sys.argv[1]?
16:36
I'm inclined to still consider that a constant even though it's not being assigned a literal value, since sys.argv almost never changes during the lifetime of your program
So my standards for param = 5 applies equally to param = int(sys.argv[1])
... Although perhaps it's not such a great idea to access sys.argv unless you're sure that your module is the main one.
Let's revisit another day - currently in the middle of some office stuff
Or maybe you are saying "what if param only contains a sensible value if this module is the main one? For instance, if it represents a command line argument. Then it wouldn't make sense to define it outside of the if". In that case, I'd be inclined to pass the value as an argument to bla. If this is impossible for some reason, I would go out of my way to signal that the function should not be called by other modules. Name it _bla() or something.
Dumb idea: make it 100% inaccessible to other modules by adding an else: del bla
16:53
man there are so many global statements in this code, which are totally unnecessary and make it hard to extend it.
Ok luckily the code is not too big, so not hard but tedious.
is the use of global objects maybe more computationally efficient?
on the contrary
global namespace lookup is slower than local (though I don't know how much work it is to pass a few more parameters)
Oh and why does python have static methods anyways? I heard it is to group them, but is this not what modules are for?
I use static methods to associate them with the name space of the class
because now I have to do from module.file import class and then class.static_method() instead just from module.file import method would be nicer to me, any pros and cons?
@Hakaishin method = class.static_method
17:00
I can imagine scenarios where a constant needs to be calculated via a very slow calculation, and the easiest way to make sure it gets calculated exactly once is to make it a global
You usually don't want to use static methods, but sometimes you do hence the option. If you don't feel the need for a static method don't create one. If you have to use it just use it.
Perhaps decorating the very slow calculation with lru_cache would be better than using an explicit global
@AndrasDeak I mean I get that, but since it is more effort to write one and to use one I wonder why people do it. I guess there is some benefit, otherwise why would it even be in the language
you might find this surprising but people differ in what they find natural and convenient
Sometimes the effort is justified by the what some consider more intuitive organization
17:09
Re: static methods. As an example, dict.fromkeys is a static method. Sure, it would be fewer keystrokes to define it as just fromkeys with no dict. required, but you gain conceptual clarity by making it obvious that the result is going to be a dictionary
I see
@Kevin fromkeys is a class method
Oh heck, is it? I can never tell those apart.
Hi guys Im new to this chat; How to type in python code?
Well, anyway. I might argue that my reasoning applies equally to staticmethods and classmethods (modulo their behavior when inheritance is involved)
@SharathZotis If you're asking "how do I get code to appear nicely formatted in here?", consult sopython.com/wiki/…
Short answer: ctrl-k or click the "fixed font" button
17:13
         def segment(text):
            # Return a list of words that is the best segmentation of text.
            if not text:
                return []
            candidates = ([first] + segment(rem) for first, rem in splits(text, max_length))
            return max(candidates, key=score)
Thanks @Kevin
I have this function that segments a string, and I am returning the top scoring segmentation which I have a helper function score. I am wondering how to return the top k segmentations
Anyone have any ideas?
Lazy solution: use a list comp instead of a genexp when creating candidates, then candidates.sort(key=score), then return candidates[-k:]. But this is somewhat inefficient for large texts.
No point in sorting the whole list if you only want the top k values. heapq.nlargest does a better job, although I don't know off the top of my head what the implementation would look like.
Indeed, I was just thinking that there are sorts optimized for limited subsets, e.g. N largest / N smallest. (Still evaluates all source elements, but only tracks the interesting ones.)
list comp will probably work but will not save as much space as genexp
is there a way to do with genexp?
the heapq approach works with a genexp I believe
oh I see, I will try it
Also since I am using segment recursively, is there a good way to handle this
since I don't want to just change return statement to
return heapq.nlargest(2, candidates, key=score)
17:36
I think I would need to know more about the problem domain to suggest optimizations more complicated than "try heapq". What is this, NLP? I'm not well-versed in that area.
Yeah its NLP, I am not the best with python, and when it comes to generators etc. I am way out of my domain
Hmm if you change segment so it returns a list then I guess you'd need to also change the generator to candidates = ([first] + segmentation for first, rem in splits(text, max_length) for segmentation in segment(rem))
Hopefully incorporating an additional for like that doesn't make performance much worse for smallish values of k
17:50
cbg
18:08
Is there a nicer way to format a long conditional eg myflag is x or myflag is y or or myflag is True or myflag is False?
I would use myflag in list_of_flags, but including True/False in such a list doesn't exclude 1/0.
Do you really distinguish between 1 and True for a flag?
Insert typical disclaimer here about using is only when you're really sure you need it. That said, perhaps any(myflag is x for x in list_of_flags)
Half-serious suggestion: id(myflag) in list_of_flag_ids
what if 260 is a valid flag value?
Then throw out the code and start over with a non-is based solution
if you ask me flags should have a single well-defined type
18:11
Agreed
hm, what happens if 260 is a valid flag value?
>>> x = 260

>>> id(260) in [id(x)]
False
260 doesn't get interned by CPython because it's large-ish, so multiple instances of 260 may have different ids.
I should've probably said "what if you're using pypy?" instead
18:13
a == 260 and b == 260 does not imply that a is b
I just want to pass on True/False/None return values to a higher scope. If a function happens to return a list or string when used elsewhere, that's fine, but I don't want this conditional to be triggered by that.
NB this probably will never be an issue for me in this case, it's more of a "how would I do that if I needed to".
I don't understand your use case
I trust all of the room regulars to exercise good judgment when deciding whether to do something slightly wacky like this
The only code with zero WTFs is an empty file
I'm not so sure about that...
if the file is called main.py then not even that
I cast my strongest spell, Protection From Well Actually
18:17
uhm, actually
;)
Since I used a level five spell slot, it also catches synonyms
It's not that complicated. I
I didn't say it's complicated :P
To be clear, "exercising good judgment" isn't a euphemism for "always deciding not to do the wacky thing". Sometimes the wacky thing truly is justifiable.
Sorry - I got off task editing. Basically I have a couple of nested menus launching functions that elsewhere might get called and return data, but I want to use returns of True/None to return to a higher menu/return to the current menu.
I could just be breaking the loop to return to the current menu on None
ie
if flag is True:
return
break
...but explicit is better than explicit, right? And I thought, what if I wanted to compare to many values in a list, but not have 1or 0 compare to True/False, only if 1 or 0 were explicitly in my list.
18:31
I might be inclined to define goHigherSignal = object() at a sufficiently visible scope and return that instead of None/False when I want to go to a higher menu
I don't understand where the possible flag values are coming from.
Nothing should compare equal to goHigherSignal other than itself, so now you can do a regular in check without worrying about false positives from loosely typed bool-vs-int equality checks
If flag values are Enums, then 'is' would be fine. Methods that return True or (something other than False, or raise an exception) are a code smell to me.
This is also sounding kind of Chain Of Responsibility-ish, so you might look to that pattern for some design principles and implementation hints.
Lazy C approach: return only positive integers during normal execution, return negative one when something unusual happens
18:55
Well my initial goal was to unify my menu code, so I could pass a list of input option/function tuples, run a chosen function, return to higher scope/menu if desired. To generalise to use for any menu, I decided to include the quit application/go back functionality as functions that return True, (rather than testing for specific inputs eg 'q'-quit, '9'-go back to main menu) with functions returning None (vast majority directly called from a menu) simply breaking loop, returning to current menu.
19:19
This is what I've got so far: https://paste.ofcode.org/g2YxvHZVZTPiSjCEA6KagD
I think you're right about dividing responsibility. But I can wrap business logic functions in calling functions which run from menus, and provide the flags that way. That's already what I do with a couple of functions. I just observed that I've got pretty much the same logic/pattern in menus, and will likely have a couple more to build, so might as well reuse some logic.
19:37
The last time I wrote a nested menu system, each menu had a "return to previous menu" option which appeared after all other options. Rather than defining the return-to-previous option in the structure of my menus, my code merely automatically added it to each menu prompt, and had special casing to detect it.
This made for a pretty straightforward implementation, since each "real" menu item function had no way to change the navigation of the menu. I lost some flexibility -- I couldn't make "return to previous" the third option of five, for instance -- but for me that was very much a YAGNI situation
Another reddit-ism: In response to suggestion to change mode_of_numbers.update({number: ddd}) to mode_of_numbers[number] = ddd, the poster replied, "I thought update was prettier."
Well, he's not wrong
I feel like there should be an idiom for "congratulating yourself on improving something to the level of minimum acceptability"
"You really weeded your cabbages there"
Oops, I misread the quote. I thought he meant "I think updating my code from mode_of_numbers.update({number: ddd}) to mode_of_numbers[number] = ddd makes it look prettier"
When really it means "I think using the method update() is prettier than indexed assignment"
The former is cabbage weeding, the latter is just silly
which is funny because in Paul's post, the former is the update method, while the latter is the "cabbage wedding" so to speak
and so reconciling the words "former" and "latter" is giving me a mild headache right now.
following the latter to the letter and heading out to buy a hoe
Cognitohazard detected. Warning: do not read the previous ten messages.
19:47
"Game? Noooo!"
hahaha
that got a chuckle out of me
@Kevin That's fair - and the only case I'd really foreseeably need anything different is the quit_app where I want to be able to use 'q'/'Q' to quit, rather than '0'. But the question and possibility of adding additional functionality (however inadvisable), lead me to my question about 0/1 and True/False and the 'in' syntax.
"But what If I am gonna need it?" is an avenue of thought that I spend quite a lot of time in. It's occasionally fun and instructive, but rarely productive.
Paradoxically, before you ask "am I really going to need this?", you must first ask "am I really going to need to ask myself 'am I really going to need this?'?"
20:18
I'm going to need a tortoise, a bow, and an arrow with a suction cup on the end to solve this one
Hey guys, I'm stuck in a problem which I have almost solved. It's a basic Hangman program which is passing all tests except one.
whats the problem
Yes, I'm typing it out, just a moment. Here's the code for your reference: pastebin.com/te3MUcVE
Here's the problem: suppose computer randomly selects a single letter say, 'y'.
to be continued....please wait....
Which as you see in my hangman(secretWord) function, I'm explicitly passing this letter for testing purpose.
Desired output is:
Welcome to the game Hangman!
I am thinking of a word that is 1 letters long
-----------
You have 8 guesses left
Available Letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: x
Oops! That letter is not in my word: _
-----------
You have 7 guesses left
Available Letters: abcdefghijklmnopqrstuvwyz
Please guess a letter: z
Oops! That letter is not in my word: _
-----------
You have 6 guesses left
Available Letters: abcdefghijklmnopqrstuvwy
Please guess a letter: x
Oops! You've already guessed that letter: _
But the output I'm getting is:
Welcome to the game, Hangman!
I am thinking of a word that is 1 letters long.
-------------
You have 8 guesses left
Available Letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: x
Oops! That letter is not in my word: _
-------------
You have 7 guesses left
Available Letters: abcdefghijklmnopqrstuvwyz
Please guess a letter: z
Oops! That letter is not in my word: _
-------------
You have 6 guesses left
Available Letters: abcdefghijklmnopqrstuvwy
Please guess a letter: x
Ok, so you wanna keep track of already guessed letters.
No No...please wait
If you compare, when the user incorrectly enters "x" the second time, you will see the difference in output.
21:04
the "oops that letter is not in my word"
When the user enters the "x" the second time it must output:
Oops! You've already guessed that letter: _
Yes, I understand.
But it outputs: Oops! That letter is not in my word: _
I tried troubleshooting it for hours but I'm not getting it how that's possible when it's passing all tests (considering by default that the letter to be guessed is within 8 character length)
Well I mean the "You've already guessed that letter" message is locked behind a elif guessed_letter in secretWord:, so...
Well, if it's failing with this one example, then it should be added to your tests
:)
Ok so check out your if statements at the bottom, walk through each one. What happens if guessed_letter is not in the word, and not in the letters guessed yet?
what happens at each line, 137, 138, 151, 152, and 156?
21:11
Please gimme a moment, I'm going through the code once more based on your suggestions.
Okay, well after you're comfortable with the fact that the letter gets added, then go through the if statements one more time if guessed_letter is not in the secret word, but is in the letters guessed already. Like go through each if statement and see if that ends up where you expect it.
maybe an easier way to say it is "what statements have to be satisfied in order to get the "you've already guessed that letter" message?"
Ok, so, not a python specific question, but I feel like any of the SO chatrooms are an equal bet:

Let's say I'm refactoring code, and splitting one file into multiple files (so each class is in its own file). Then, in one of the classes, I make a minor change. When I push this to my branch and make a PR, the diff will be fairly huge (deleting files, adding a bunch of files)—but in reality, the only thing I really changed was the minor change in one of the files
Is there a way to link the diff between the section of code that I changed (when it was one big file) and the changed code in the smaller, split-apart file?
(It'd make my PRs seem less... daunting)
21:28
@AmagicalFishy I would simply suggest splitting this into two branches, one that refactors with the split, and then one that makes the small modification..
The original branch that makes the big split will still be a big commit but easy to review if there's no changes. But if you include some minor changes, then it's hard to review.
oh, cool. and just in the pr message i'd just say something like "these files didn't change, they've just been split up"
yeah. But it's also not really necessary (at least for Python) to have separate files for every class...just makes it harder to navigate the source. Now every single class needs to be imported, instead of from core import Class1, Class2, Class3, it's now from core.class1 import Class1, from core.class2 import Class2, and so on..
but I mean in general its fine if they all don't really share a common enough theme to group them together..
oh. i know it's not necessary—but i feel like it's a lot nicer in the case of a DJango project
and i guess if you like to do that its up to you :)
to have all the forms in one app to be in their own 'forms' folder
21:32
ya, not gonna tell you how you should structure your project :). but ya i'd make two separate PRs, just makes it easier for reviewers. Would be nice to be able to visually see that there's no diffs between each file and the file they came from, though..
wim
wim
@Kevin except PEP8 is like "no newline at EOF, WTF"
im having a brain fart on git merge conflict, when source vs target.
is source the code i have and target is the branch coming in ?
or did i have it backwards..
Nvm confirmed target = the code has been worked on, and source = the merging into code
21:55
@AlexanderReynolds I got it! It should have just been: "elif guessed_letter in lettersGuessed"
Thanks a lot, and @Aran-Fey too.
You are great.
22:34
hey guys, is an if statement styled like list comprehension faster or slower then the standard way of writing an if statement
huh?
ignoring for a moment that I have no idea what you're asking: if you're optimizing if statements you're doing it wrong
22:54
it was just kind of a random thought that popped into my head, i guess more accurately im trying to picture what exactly the difference is between something like:
if x.true_attribute:
    do_something(x)
and
do_something(x) if x.true_attribute
The latter is perl
technically with an else that's valid python too though
no difference (if you add an else None)
other than never do the latter
but you shouldn't do the latter because it's not exactly Python Pythonic.
22:57
why (as in why is it not Python (or did you mean Pythonic))
yeah, I was pondering what to replace it with, I guess Pythonic also won't do.
do_something sounds like something with a side-effect
only do the latter if you want to keep the return value of do_something(x), which is not what your former is doing
ok, so do_something still executes in the case of this if statement (is it right to call it a ternary operator?)
it's called a conditional expression (emphasis on the expression)
but if you call it a ternary most people will probably understand
23:02
so if you did some kind of assignment, for example, before the conditional expression, it wouldn't do that, but other side effects of running the function for do_something would occur
at the risk of repeating myself: huh?
You said "keep the return value", so I'm trying to make sense of what you mean by that
# yes:
val = 3 if cond else 4
# no:
mash_potatoes() if cond else {}.update({})
# also yes:
veggies = get_mashed_potatoes() if they_are_potatoes else get_steamed_broccoli()
oh ok, that makes sense
this also helps explain why you cant do the if without an else in this particular case
@BikramjeetSingh Cheers!
23:33
Anyone have a good dupe recommendation for a user expecting a.pop() to return the modified list instead of the popped element? stackoverflow.com/questions/54817677/…
wim
wim
+1 for potato themed example
note to self: potatoes

« first day (3050 days earlier)      last day (2122 days later) »