« first day (3118 days earlier)      last day (1831 days later) » 
00:00 - 15:0015:00 - 23:00

12:23 AM
dear community
I have the below code for doing reservior Sampling
import random
def ReservoirSample5(s, R):
# fill the reservoir array
S=[]
for i in range(s):
S.append(R[i])

# replace elements with gradually decreasing probability
for i in range(s,len(R)):
j = random.randint(1, i) # important: inclusive range
if j <= s:
if j==10:
j=j-1
try:
print("before",S)
S[j] = R[i]
#print("j=",j,S[j])
#print("i=",i,R[i])
print("after",S)

except:
print("except")
print("j=",j)
print("i=",i)
print("except")
return S
what trouble me is it seems it is always[1,....]
when i do this test case
import numpy as np
s=100
yy = np.empty(s)
b = np.arange(1, s, 1)
ind = np.arange(len(yy))
np.put(yy, ind, b)
print(yy)
ReservoirSample5(10,yy)
It seems [1,....] the first element never got swaps out
 
 
3 hours later…
3:31 AM
After using, asType, I'm getting following error
ValueError: could not convert string to float: '864570 3'
Anyone has idea on resolving this ?
 
4:07 AM
I overcame this error by using data.notna().astype('float64')
 
4:39 AM
hi, friends
 
4:56 AM
cbg
 
5:43 AM
@wim This one:
import inspect

class Foo:
    def method(self):
        pass

print(inspect.ismethod(Foo.method))
 
Well, it's not a bound method.
 
Exactly. I'm trying to detect unbound methods.
 
...Trying to catch up what you've already discussed about this...
 
6:02 AM
hi
 
6:12 AM
@Aran-Fey So you're trying to detect in a decorator if you're in class body context or not?
 
That's one way of doing it I guess, yeah
 
Though that'll not help with class/static methods...
 
doesn't matter. classmethod/staticmethod decorators have to be applied last anyway
i.e. it's impossible to detect and what my decorator sees is definitely not a staticmethod
 
It's more of a "heuristic" approach, but I guess you could check if the current frame's parent's locals "look like" a class body context.
In other words: rather shoddy.
 
yeah, I'd rather parse the method's __qualname__
 
6:30 AM
Umm... Seems there's a trend in "finding consecutive subsequences" this morning...
 
6:51 AM
unreproducible, there's at least 3 separate bugs in there stackoverflow.com/questions/55894445/…
 
cbg
 
cbg
 
7:07 AM
@Arne Huh? I can reproduce that just fine
>>> XYPoint.__add__(32,34)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "untitled.py", line 18, in __add__
    new = XYPoint(self.x, self. y)
AttributeError: 'int' object has no attribute 'x'
 
You're right, I didn't see last_serial_no was a class attribute
that also means there is only two bugs in that question
 
7:24 AM
The missing return new and the incorrect usage of XYPoint.__add__(32,34)?
 
back to three, i missed the missing return. I meant the meaningless skip InitVar, since the __post_init__ uses self.skip, which is always 1.
Also, that blog they linked to...
 
hi, i am writing a function to convert strings to floats in for my csvs. so far i have :
 
> I suggest that the introduction of the dataclass will transform the Python language, and in fact signal a more significant change than the move from Python 2 to Python 3.
 
def string_to_float(series)
    series = series..str.replace(' ','')
    series = series..str.replace(',','')
    series = pd.to_numeric(series)
    return series
is there a better way to do this?
thank you!
 
no problem
but i don't know pandas, so that was the extend of my help =D
 
7:30 AM
haha ok thanks
 
Umm... pd.to_numeric(series.str.replace('[ ,]', ''))... will cut out one step
 
ah thank you!
 
@Arne closed, but now I think it should be closed as a dupe instead. Casted a reopen vote.
 
you found a good one?
 
nope
@Arne This one is like that, but not that great a dupe target - stackoverflow.com/questions/49645703/…
 
7:36 AM
I'm afraid that will only help you if you already understand the underlying issue
 
yeah, that's why trying for a better target. The answer explains it okay, but the question isn't primed for that.
 
canonical proposal, "why calling methods as classmethods will usually not work"
anyone wants to write it?
 
perhaps this one (not for canonical) stackoverflow.com/questions/40530786/…
 
that one is good, I'll vote to reopen+dupe too
 
In a sense, methods, routines, subroutines, classmethods, functions, et cetera are all equivalently wrappers for executable code fragments (ie, subprograms in the same file) ... hope that's not wrong to say.
 
7:41 AM
impressive googling =0
 
@Arne actually, I used SO search :)
 
given my past experiences with it, that just makes it more impressive
 
I know :-p
there's also a luck factor most times
 
8:01 AM
@PM2Ring also looks like a bit of controversy regarding PSE elections: meta.stackexchange.com/questions/327495/…
 
@shad0w_wa1k3r reopening so you can reclose is pointless
 
that's not true at all. what do we have close reasons for if they don't matter?
 
@tripleee I disagree. It requires more effort, true, but I made a mistake while closing, so it's usually much nicer to have the question redirect to a better question than just hang as closed, specially when it's not that broad / silly.
And usually (I recall a similar discussion, maybe long time ago, in this room) the person advocating for such a thing takes up responsibility for the effort of carrying it out successfully, so no harm done.
Finally found at least 1 meta post regarding this - meta.stackexchange.com/questions/270513/…
 
8:31 AM
@JonClements Indeed! We have 2 mod slots open, and now only 3 candidates. One of those candidates is virtually unknown: they have almost no activity on Physics meta and have only made like 5 posts in the last 3 years. And they didn't bother to fill in the mod candidate questionaire.
A lot of people are disgruntled about what happened with Kyle, the front-runner who got disqualified because of a suspension in the last 12 months. He was suspended for 24 hours because of how he responded to a comment requesting he re-word one of his answers to make it less ambiguous.
His reply was along the lines of "if someone can't understand what I'm saying, their reading comprehension is shit". So he didn't actually direct bad language or insults at a specific individual, but it was considered unfriendly to any future readers who don't understand his answer correctly.
 
Yeah... awkward... I had a quick look... one of 'em is definitely new with no participation and one even mentions they're not going to be able to spend much time doing it anyway... can imagine lots of people aren't happy... (no one ever is when stuff like that happens...)
 
@tripleee That depends. Opening a bad question to close with a different reason is usually a waste of time & votes. If the stated close reason doesn't quite fit, post a comment.
But dupe questions aren't intrinsically bad. If it's a very common dupe, it's probably no big deal: just let it die & get roomba'd. But if it might be a useful signpost, then it deserves to be closed as a dupe, rather than being branded as a bad question.
@JonClements We're holding the election because a mod (Manishearth) who has been mostly absent for quite a while finally decided to resign. So the mods have been handling his workload for quite a while anyway. So hopefully the 2 new guys will make some difference. Manishearth was also a mod on Chemistry, so they're also holding an election, but it looks like they're better organised than Physics.
 
8:48 AM
things have a way of working out in the end... sure it'll be fine... probably a bit more meta drama no doubt but...
 
@PM2Ring was that recent? Perhaps to intentionally disqualify them?
@PM2Ring I didn't know Manish did physics
@JonClements eh, people will manage so "it'll be fine" but this is really bad
 
@AndrasDeak He's been AWOL for quite a while...
 
cbg
 
@PM2Ring you think that... but maybe it's just a problem with the space-time continuum there end and they've only been away from their desk 5 minutes relative to them :)
 
@AndrasDeak No, it happened well before Manish announced his retirement. Kyle is a nice guy, but he can be a bit brusque, especially when he's on the defensive. IMHO, his communication skills are pretty good, but he's not always as clear as he may think he is. ;) But his physics knowledge is very good, and he doesn't post stuff he's not sure about, unlike some people who can pad their answers with unsubstantiated waffling.
 
8:59 AM
I see
 
@PM2Ring he very quickly merged a PR to Chat Exchange for me a couple weeks back but now I have no sign of life on a followup I have pending
 
I have a tiny issue, how do I fix the error in this cell. I think it's because axes3d is not used in the code and it is required somewhere for the output to display. colab.research.google.com/drive/…
 
@tripleee IIRC, another mod contacted Manish to find out if he was going to resume mod duties, after a couple of queries about his absence in Physics chat & meta. So he was only around for a short timeframe, while he was sorting that out.
 
Manish Earth (Mu guy) has been on SO/SE a very long time. He's legend.
 
@MisterGeeky Sure, but he's been too busy with other stuff for quite a while, so he simply doesn't have time for SE these days.
 
9:12 AM
@PM2Ring It can get bit burdensome to juggle life, the universe and everything along with an endless stream of q&a and chat threads. I don't think Manish is at fault for his lack of time to be on here. Probably still dong something epic.
 
@MisterGeeky Of course. But he did cop a little bit of criticism for not letting people know sooner that his absence wasn't just a short-term thing.
 
Mhh, I can understand that. Still no one would label him negligent.
At some point in time, he must have moderated really well to keep these ships floating.
 
Ugh, it's always upsetting when a code works in a simple example, but not in a project...
and frustrating
 
So true @U9-Forward
 
@tripleee I thought he stopped working on ChatEx so that's already an achievement
 
9:26 AM
Do I have to initialize a variable outside a function to modify it inside the function? I mean, I want to create a global variable if it hasn't been created previously.
 
@MisterGeeky Exactly, i am having that now...
 
@U9-Forward where are you stuck?
 
@akinuri you very often don't want to create a global variable even when you think you do
 
and when you do you can create it inside a function
 
@MisterGeeky I am building a PyQt software with some data stuff using pandas, and i have a code using iloc which does some index order changes, but strangely not doing it in the project
@akinuri I really agree with tripleee as well as Andras
 
9:28 AM
if var in globals():
# something
else:
# global var doesn't exists; create it
# how?
I'm using a global variable to communicate between modules. I'm a Python newbie. Globals seemed like a way to do that.
 
@akinuri that you don't need
don't you want to end up with the new value of the global name either way?
 
@MisterGeeky Ran my code again, nothing different
 
Can I post multiline code here? I want to share a small sample.
 
@akinuri please see the pinned message
 
9:33 AM
also, if it's more than ~10 lines it's probably better to be linked from a code paste service
 
@akinuri use google colab or paste.rs/web
 
def str_quote(s, quote="\""):
    if "STR_QUOTE_CHAR" in globals():
        print("exists in global")
        quote = STR_QUOTE_CHAR
    else:
        print("scanning stack")
        STR_QUOTE_CHAR = find_in_stack("STR_QUOTE_CHAR") or quote
        quote = STR_QUOTE_CHAR
    return quote + s + quote;
 
@AndrasDeak why jupyternbviewer not the golden standard
 
@akinuri Much better
 
@MisterGeeky "the golden standard"^[citation needed] ^[for what?]
 
9:34 AM
Another starred message by Aran-Fey
 
@U9-Forward you love being redundant, don't you?
 
@AndrasDeak code-sharing, correction and collaboration
 
After I retrieve a global variable from the stack (another frame), I want to store it in the sub module, so I dont't have to keep iterating the stack.
 
@AndrasDeak :(
Haha
 
kind of a tangential idea and maybe unpopular here, but why don't you store it in a file?
 
9:36 AM
cbg
 
cbg, nice day today
 
nice, glad to hear! not sure if i can say the same here, but eh, could be worse ^^
 
@akinuri Is this stack you're scanning created in the module that contains the str_quote function?
 
def find_in_stack(glob_var):
    # get stack
    stack = inspect.stack()
    # prioritize last -> search from last to first
    stack.reverse()
    for frame_info in stack:
        # get global variables
        frame_globals = dict(inspect.getmembers(frame_info[0]))["f_globals"]
        # check if var exists in current frame; if not, check next one
        if glob_var in frame_globals and frame_globals[glob_var] is not None:
            # return the global variable
            return frame_globals[glob_var]
 
@akinuri Didn't you learn how to format code here?
 
9:41 AM
Text and code don't mix -.-
 
Oh thanks, but please remove the previous text
Ugh, my code still doesn't work
 
If I must declare the global variable first (can't create it inside a function), I need to modify the str_quote() and the find_in_stack() methods accordingly.
 
one thing i will say, theres almost always a way to explicitly pass things where you'd have used a global. Why does the current function not have this global as a parameter that it needs?
 
So I decided to go with:
 
@akinuri Ok, I think I get it. I wouldn't initialise STR_QUOTE_CHAR inside str_quote.
 
9:46 AM
STR_QUOTE_CHAR = None

def str_quote(s, quote="\""):
    global STR_QUOTE_CHAR
    if "STR_QUOTE_CHAR" in globals() and STR_QUOTE_CHAR is not None:
        print("exists in global")
        quote = STR_QUOTE_CHAR
    else:
        print("scanning stack")
        STR_QUOTE_CHAR = find_in_stack("STR_QUOTE_CHAR") or quote
        quote = STR_QUOTE_CHAR
    return quote + s + quote;
 
@U9-Forward I know you're just trying to be helpful, but when there are ROs active in the room please let them attend to RO duties.
 
would it not make more sense to
def str_quote(s, quote=STR_QUOTE_CHAR):
 
@PM2Ring Sorry...
 
and then if it's None fall back to '"'
but I don't really pretend to understand what this code is actually supposed to do
 
^ this is the part that makes me hesitate to suggest things
i just dont quite get why the lower stacks dont have this variable passed. is that an option?
 
9:52 AM
@akinuri You can just do STR_QUOTE_CHAR = find_in_stack("STR_QUOTE_CHAR") or '"' in the global context (that is, outside any function). Either at the top of the module, after the imports, where global assignments often go, or just before the str_quote function definition, if it's the only function using STR_QUOTE_CHAR.
 
Well, I can explain, but I don't know where to start :) I've previously prepared an image to explain what's really going on (was planing to post a question, then started tinkering with frames). Let me post the image.
 
pet peeve of the day: drinking coffee to stay awake but it actually makes you drowsier
 
eat an apple
 
@cs95 than don't drink coffee :-)
 
it works better than coffee. (if its an option)
 
9:55 AM
@tripleee No, because STR_QUOTE_CHAR doesn't exist yet, at function definition time. But I must admit I don't quite know what akinuri's code is doing either.
 
Do what Paritosh says :-)
 
@U9-Forward ooh good idea
 
Haha
 
:>
 
9:56 AM
star import. breaks down crying
 
@cs95 Try antimatter coffee. That should have the opposite effect.
 
@ParitoshSingh meh. For your own module with __all__ it's fine
 
crying intensifies
 
helpers_string.py and node.py won't be modified. So I wanted to declare global variables in the main script. To access that I had to iterate the stack
 
@PM2Ring it's defined as a global just above
 
9:57 AM
AFK. Gonna eat.
 
@PM2Ring where do I get that? LHC?
prolly be an expensive cup of coffee :D
 
@cs95 just buy some off of amazon. i hear they have everything.
 
I sense an XY problem but I don't know what X has to be
 
XY problems, XY problems everywhere
 
@cs95 Why is it always us blokes that get blamed!? :p
 
9:59 AM
@cs95 Eeek, really late in LA
 
@JonClements blamed for? :)
 
@cs95 Maybe. But it might take them a few decades to make a visible quantity. :) Actually, making even the simplest antimatter atoms is really hard. I doubt we'll be able to make antimatter organic molecules for a century or more.
 
@akinuri Is modifying helpers string not allowed?
 
@cs95 Well... I hear a lot about XY problems...
 
hehe
took me a while
 
10:01 AM
@akinuri Btw, there is a Salad Language, not afk, but Rhubarb (rbrb)
 
its optional.
 
@tripleee Oh, ok. But that just sets it to None, which is pretty useless.
 
unless you're a salad bowl
@PM2Ring The amount of energy you'd need to create enough antimatter to be of any use would probably have to come from a Dyson Sphere!
 
pet peeve for the day for me: i am frustrated with my 169 lines long code with PyQt and Pandas, because my final step of code isn't working, instead not even modifying a bit of the data, i expect it to change the row order, only doing in example!
 
@U9-Forward very much optional. Quit harassing users with salad.
 
10:04 AM
Morning cbg
 
@U9-Forward and you've complained enough about that.
 
(that's not a pet peeve, btw) a pet peeve is something that bugs you on a periodic basis
 
And that too ^
 
and bugs in code bug everyone, so, not a peeve ;)
 
@AndrasDeak Got to learn what is a pet peeve
 
10:06 AM
Great
 
Well, let me ask someone:
 
Also, pet peeves are normally about stuff that other people or things do, not problems of your own making.
 
Let's say i have a dataframe:
(pandas)
>>> df = pd.DataFrame({'a':[1,2,1,2,1,2,1,2], 'b':'foo'})
>>> df
   a    b
0  1  foo
1  2  foo
2  1  foo
3  2  foo
4  1  foo
5  2  foo
6  1  foo
7  2  foo
>>>
I would like to convert it into:
 
don't leave us hanging
 
   a    b
0  1  foo
2  1  foo
1  2  foo
3  2  foo
4  1  foo
6  1  foo
5  2  foo
7  2  foo
So change the order of the rows
 
10:09 AM
@akinuri This definitely sounds like an XY problem. Normal Python code that imports stuff doesn't need to use inspect to make it all work properly.
 
I know i can use a hack:
>>> df.iloc[[x for i in range(0, len(df), 4) for x in [i, i+2, i+1, i+3]]]
   a    b
0  1  foo
2  1  foo
1  2  foo
3  2  foo
4  1  foo
6  1  foo
5  2  foo
7  2  foo
>>>
But any other options, since that doesn't work in my project :(
 
productivity should never be measured in lines of code
4
 
@cs95 finished my question...
@cs95 What do you mean?
 
Step 1: define new row order. Step 2: figure out how to reorder
Now you have both in one step so we can't know which part "doesn't work"
 
Let me try
 
10:12 AM
i will admit, you use the @ symbol a lot. Like, a lot. It sends a ping to the people tagged.
 
it means what it means
 
lol
 
Perhaps try to cut back on some of those @ if the message you're replying to is directly above yours.
 
done one
Done two
 
glad I'm not the only one being annoyed
 
10:16 AM
Im biting my tongue hard.. something something pet peeve. ;)
 
you can tell someone to stop doing something annoying without making it obvious it annoys you
 
@AndrasDeak Damn...
 
FWIW it's not that hard to annoy me
4
 
we know ;)
@U9-Forward I think you should clarify how the order is to be changed and what the method behind it would be. It isn't very obvious from your "hack"
 
Someone help me figure out contextvars please... How do I need to change gen so that this prints 1 2 1 2 instead of 1 2 2 2?
 
10:21 AM
I want a set of rows like:
 
oh wow, apparently dpaste is blocked for me
 
first row
third row
second row
fourth row
fifth row
seventh row
sixth row
eight row
And so on...
 
Clear as mud
 
1 3 2 4. Proceed with next set of 4.
 
10:23 AM
@ParitoshSingh Exactly, you're better than me in explaing
 
Reorder in batches of 4
 
@AndrasDeak Exactly
 
thanks. (though again disclaimer, i probably wont be able to help. :( but curious.)
 
In numpy I'd be tempted to reshape-reorder-reshape
 
10:25 AM
I want a better way which reorders every set of four rows
 
Some people just can't help being annoying, eg Hrundi V. Bakshi. But they may still be likeable if they're funny, and not too annoying. ;)
 
oh, i have python 3.6 o.o apparently contextvars came out in 3.7
one day im going to fix all my libraries and get a stable 3.7 environment that doesn't self downgrade
probably when python 4 gets released...
 
@AndrasDeak you mean like this? df.reindex(df.index.values.reshape(-1, 4)[:, [0, 2, 1, 3]].reshape(-1))
If that flops because len(df) % 4 != 0, then you can try zipping slices. df.reindex(list(chain(*zip(idx[::4], idx[2::4], idx[1::4], idx[3::4])))) Although not nearly as pretty
Where idx = df.index
 
Thanks, lemme try
@cs95 dammit, i think there is an issue of my assigning, it still doesn't work.
 
alrighty
 
10:33 AM
any mistakes here:
self.df2.loc[:-4] = self.df2.loc[:-4].reindex(self.df2.loc[:-4].index.values.reshape(-1, 4)[:, [0, 2, 1, 3]].reshape(-1))
 
Try adding a .values at the end of RHS (or .to_numpy() if on 0.24) to avoid index alignment
 
@Mookayama Sorry, it's impossible to read that unindented code properly. But you shouldn't silence exceptions like that by using a bare except:. Instead, use named exceptions.
 
@cs95 after paren?
 
yes
 
Still not...
Anything wrong with .loc[:-4]?
 
10:36 AM
out of suggestions without any further context, I'm afraid
 
how do your indexes look?
 
rbrb
 
@ParitoshSingh As usual, (e.g. 0 1 2 and so on..)
wait a second, why when i print it it gives an empty df?
This seems wierd
YES!!! i solved it
After all a subtle mistake, need iloc instead of loc.
rbrb
 
@cs95 yeah
 
Solved it though
real rbrb
 
10:52 AM
cbg
Cute language ?(
:)*
 
11:04 AM
I'm starting to think contextvars can't handle generators... even the various Contexts in the decimal module don't work with them
 
:(
Oh, that's also from Nathaniel Smith. He's a very smart and active scipy dude.
 
11:26 AM
To make the following work, I changed it again:
print(str_quote("test1"))      # "test1"
STR_QUOTE_CHAR = "'"
print(str_quote("test2"))      # 'test2'
STR_QUOTE_CHAR = "^"
print(str_quote("test3", "|")) # |test3|
print(str_quote("test4"))      # ^test4^
into this:
def str_quote(s, quote=None):
    global STR_QUOTE_CHAR
    if quote is not None:
        return quote + s + quote
    else:
        quote = find_in_stack("STR_QUOTE_CHAR") or "\""
        return quote + s + quote;
Forgot to omit global STR_QUOTE_CHAR
 
So every str_quote() call iterates the stack. Is that overkill? o.O
 
cbg
@akinuri I'd say 1 stack iteration is already too much
 
@AndrasDeak Haha. Idk, maybe I dump the STR_QUOTE_CHAR thing later. Kind of experimenting right now
 
How about a global config dict in that module? Dicts are mutable so you can just change it?
Why do you even have to iterate the stack? Can't you just know where the global must be coming from?!
 
11:31 AM
Both my main script scan.py and a module that's imported to scan.py imports helpers_string.py in which the str_quote() resides.
So it's dynamic. I just prioritize the last frame on the stack
 
How does that relate to iterating the stack in helpers_string.py?
why not always look it up in scan.py?
Don't you have one source of truth?
 
If I decide to add STR_QUOTE_CHAR into node.py, helpers_string should be able to detect it.
 
but why would you add it there...?
that's probably your problem
How about something like a config.py or just keeping a config dict in one given module?
 
node.py is a class module. I have FileNode and FolderNode in it. These nodes have .dump method.
 
class module...?
 
11:35 AM
It prints the output of the contents of a directory in a pretty format.
You know what, nvm :) I already strayed away from the actual problem
 
$ cat config.py
STR_WHATEVER = "@"

$ cat foo.py
import config

def frobnicate():
    print(f'Data before: {config.STR_WHATEVER}')
    config.STR_WHATEVER = "!"
    print(f'Data after: {config.STR_WHATEVER}')

$ cat bar.py
import config

def reticulate():
    print(f'Data before: {config.STR_WHATEVER}')
    config.STR_WHATEVER = "?"
    print(f'Data after: {config.STR_WHATEVER}')

$ python3.7
>>> import foo
>>> foo.frobnicate()
Data before: @
Data after: !
>>> import bar
>>> bar.reticulate()
Data before: !
Every module refers to a single source of information. I'm not saying this is a good pattern (I'm not sure either way), but at least it's less insane.
 
It's a singleton pattern, and the world currently is of the opinion that it's kinda bad.
 
I'm not surprised, thanks
 
@AndrasDeak Hahaha (at insane). You're right. I was increasing the source of information and then looking for ways to access them.
 
Which still leaves enough space to be a good thing to do, given that other patterns might be a lot worse.
 
11:47 AM
Modules are singletons, amirite?
 
Usually. I think there was an example for some third-party module that did some black magic...
 
Btw, I've came across posts that talk about import * being bad, but is it always? For example, in my case, I do from helpers_string import *. There are, currently, 4 functions in it, and I use all of them.
 
@akinuri it's only OK if you have an __all__ in your file
otherwise you'd be importing every global name, including modules imported in that file
 
it's ok if people who read your code can reasonably be expected to know what's being imported
 
Hmm. Don't have it. Let me look it up :)
 
11:49 AM
or if nobody needs to know
 
And not that "people who read your code" includes "you 6 months from now". An important scenario often neglected.
 
@AndrasDeak Haha. In my current position, I'm the only one who's going to read it again in 6 months, but I get your point :)
 
that's exactly my point...
 
@akinuri If star imports were always bad, the language wouldn't support them. But they usually should not be used in normal modules. They have 3 legitimate uses.
1. For quick experiments in the interactive interpreter. 2. For use in a __init__.py file to unify names imported from multiple modules. 3. When using a module like ctypes, which defines a bunch of distinctive names that shouldn't clash with other names, and which get used with such frequency that it'd be very annoying to have to use fully-qualified names all the time.
Eg, in rehash.py it would be pointless clutter to write ctypes.c_long, ctypes.c_uint, etc.
 
12:10 PM
well one could arguably still do a named from import
and there's a missing import os :P
from ctypes import Structure,c_long,c_uint,c_ubyte,cdll,byref,c_int,pointer
:D
 
sounds.. fun :P
 
Anyone know offhand whether Python's Windows installer requires an internet connection? I could find out myself but it would take a couple minutes.
python.org/downloads/release/python-373 says: 'There are now "web-based" installers for Windows platforms; the installer will download the needed software components at installation time.' Not sure whether this is referring specifically to the executable available in the "Download for Windows" dropdown
Rather like Amtrak installing signs saying "there are now trains that can travel at 320 km/h" when they know full well that they're not talking about themselves
 
12:25 PM
@Kevin look at the download links down the page
"Executable installer" vs "web-based"
You can get both
 
Hmm, true. Darn these crazy eyes of mine.
 
@AndrasDeak That's reasonable. But almost everyone who uses ctypes just does the star import. ;) I guess that's not a great justification though, considering how much code does star imports with Tkinter.
 
m8_
Morning! Quick pandas/groupby question...I have a dataframe of Names and Scores (pastebin.com/TJ0f1bFa). I have grouped the Names by Score but I want to determine if the difference between all scores in each group is less than or equal a certain max number, say 5.
 
@PM2Ring I was just looking at a highly voted Tkinter post the other day thinking "I should edit the star import out of this". I don't much like that some new users' first exposure to the module system is from tkinter import *
First I must consult the bones to determine whether I'll get yelled at for editing the code of an answer from eight years ago
 
12:50 PM
fwiw anaconda install doesnt need internet
 
@Kevin Funny, I don't recall seeing that question when I was learning how to do Scrollbars. At least, I didn't vote on either the question or answer. It's unusual to see a star import from Bryan, but I guess he just copied it from the OP. And it is a rather old question.
 
Can you set a filter ON by default in Flask Admin? Other than redirecting with the filter parameters in the url?
 
@Kevin I bet if you edited it Bryan wouldn't revert it. :) I often add a paragraph to my Tkinter answers, explaining the evils of star imports. Or just a comment on the question, with a link to one of my answers with that explanation. It doesn't do anything to stem the tide of newbie questions that do from tkinter import *, but hopefully it has some influence on people who read those pages...
 
1:32 PM
cabbage
 
My suspicion is that the import * habit gets started when newbies copy-paste from highly upvoted posts that use it. They've got to learn it from somewhere.
 
At risk of throwing a message into the void... Thinking about you @DSM. Hope you're doing alright.
 
So apparently my client doesn't have python.exe installed, and the installer fails with some arcane "security policy violation" error message. Maybe I should just give up and write a batch file... The grass on the other side of this fence is looking greener all the time
 
It rustles my jimmies that the tkinter documentation is like this little neglected enclave
 
1:47 PM
where cannibals live
we could send missionaries to show them the light but they'd just get eaten
 
@piRSquared Last I heard he's shaking things up at NumberFirm with the same vigor as always
 
good
 
2:04 PM
@Kevin Does anybody actually use those docs? I'd expect them to use effbot, &/or the stuff on the New Mexico Tech site.
 
2:18 PM
I use variable unpacking a lot because I think it's cool. I know it makes the code denser and more difficult to read. People often ask "Hey what's that * mean?"... and I don't feel guilty. I sometimes use dunder methods directly... tiny amounts of guilt enter my heart as I know that is less than best practice to introduce a dependency on a "private" method. Despite my crass coding behavior, I'd never NEVER from module import * /shakeshead
 
one of these things is not like the others
 
I almost didn't include case 3 above, because I don't like to encourage inappropriate star imports, but I do think it's justifiable for modules like ctypes. And of course, every Python script has an implicit star import of builtins. ;)
 
Yeah... there's a couple of modules where everything's mostly constants/distinctly named things that aren't likely to clash with anything
 
It's a dodgy business to try to make green beans aware of tools but advise against using certain tools unless it is "appropriate".
 
2:33 PM
"Here's a regex, kiddo. Snort it responsibly."
 
regex is a poly-edged sword
 
Just playing devil's advocate for a moment, I guess you could say that with many of the Tkinter names it's fairly obvious that they refer to GUI stuff, eg the widget classes. However, it makes the code easier to read when you can easily distinguish between the library's GUI elements and those defined by the script. And a Tkinter star import dumps 130 names into your namespace, which is downright messy.
But whereas one star import can be tolerable, doing 2 or more is a recipe for chaos and name collisions.
 
@PM2Ring by "devil's advocate" you mean "angel's advocate"? Because it sounds like you're making sense.
 
i suppose the devil is in the eye of the beholder
 
Only the 1st sentence in that message is the devil's advocate stuff. The rest is anti-star import.
 
2:47 PM
To me, i see * imports as being fine for a sort of "low level" to high level import. Atleast thats how i choose to justify * import of ctypes. Given the names would have no chance of collision, or very little, It can be okay to import stuff you'd never overwrite that is commonly used.
i had not considered the case of star imports inside an init file, but that can make sense
other than that though, and especially when making your own packages, i'd see star imports as a headache for anyone* dealing with it 6 months down the line, including yourself
just spend that little bit of extra time writing module_name.some_name and save everyone a world of hurt later on as things get used elsewhere, and built upon.
 
@ParitoshSingh It's pretty standard if you define stuff in 2 or more files, but you want it to behave as if they were all defined in a single file.
 
yeah, seems super useful in my current "self project" that im taking up already.
i imagine its the defacto go-to for a module with a "sub-module" type of segregation. the submodule can have multiple files, but for anyone sitting on a higher level, its all a single package
 
Yup
 
cool, makes sense
 
API implemented in submodules
 
00:00 - 15:0015:00 - 23:00

« first day (3118 days earlier)      last day (1831 days later) »