« first day (2827 days earlier)      last day (2120 days later) » 
00:00 - 19:0019:00 - 00:00

12:41 AM
Rhubarb all
 
 
4 hours later…
5:09 AM
@Aran-Fey Done. But it's got an accepted answer, so
 
*shakes fist* one of these days I'll participate in your 20k-only delv-requests
 
@Aran-Fey You're getting close. OTOH, it's getting harder & harder to find questions worth answering.
It's been amusing to watch people post answers to this and then delete them shortly after when they realize they didn't read the question properly. :)
 
One of them tried and failed twice. Nice.
 
 
3 hours later…
7:52 AM
@PM2Ring whoa I found a nice solution to it, then I found out it works only in Python 3... and perhaps by accident
>>> for d1, d2 in zip(map(next, cycle([iter(data1), iter(data1)])), data2):
...     print(d1, d2)
 
I think you deserve an award for writing a piece of code that looks innocent but is actually really gross and hard to read
 
@Aran-Fey it is undocumented but it works :F
and I guess I need to write a bug report
 
Is it really? I'm pretty sure StopIteration leaking is documented somewhere
 
@Aran-Fey pretty sure stop iteration not leaking is documented somewhere?
anyway, Python 2 map doesn't work like that
 
8:08 AM
According to this PEP the behavior changed in 3.7
 
8:31 AM
@AnttiHaapala Hmmm. What Aran-Fey said. :) I'm still not clear what the OP wants to do in more general cases, so I didn't post my answer. I didn't bother using itertools, because I wanted to keep it simple, since the OP is a newbie who's still struggling with simple for loops. For that matter, using next is probably a little too advanced.
repeats = len(data_2) // len(data_1)
letters = iter(data_2)
for s1 in data_1:
    for k in range(repeats):
        s2 = next(letters)
        print(s1, s2)
 
yours doesn't do StopIteration correctly
 
Let's get rid of statements and make everything expressions: s2 = next(letters, break)
 
I'm in!
I think every programming language should learn from Scheme
 
Scheme is a lisp, right?
gimp's script-fu is mostly scheme
 
> In 1998 Sussman and Steele remarked that the minimalism of Scheme was not a conscious design goal, but rather the unintended outcome of the design process. "We were actually trying to build something complicated and discovered, serendipitously, that we had accidentally designed something that met all our goals but was much simpler than we had intended....we realized that the lambda calculus—a small, simple formalism—could serve as the core of a powerful and expressive programming language."
 
8:41 AM
@AnttiHaapala Fair enough. It's a work in progress, waiting for feedback from the OP. :)
 
@Aran-Fey OR, assignment statements: x = break
 
Now we just need to figure out when that break is actually executed.
 
With scheme you could have break be a continuation, and then you just call it :D
 
8:57 AM
cbg
 
@AndrasDeak Yes, Scheme is a lisp. I played around with gimp's script-fu a little bit, but I've never enjoyed writing in lisp dialects, with all those parentheses. FWIW, the Amiga introduced a Scheme variant for standardized installer scripts. I appreciated the concept, but hated working with the language. It was just too easy to create chaos with a misplaced parenthesis.
 
9:43 AM
yes, the practicality of Scheme is not that good :D but the power...
... if only it came with a good syntax :D
 
10:24 AM
Last week I spent 3 days implementing memoized properties with dependencies (i.e. the memo is cleared if the value of another property changes); this week I'm on a quest to implement a pipeline that processes files but only ever writes the files to disk if it's absolutely necessary. After 3 days of working on this I now have a permanent headache and no end is in sight. I'm tempted to give up and just create a temporary file for each step in the pipeline
Why is writing bad code always so much easier than writing good code?
 
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." — Phil Karlton and Leon Bambrick.
 
I got the cache coherence working in just 3 days :D
... I think. Maybe I should write more tests.
 
 
1 hour later…
11:49 AM
Hi, hello everyone !
It is possible with python pandas dataframe to fuse the content of the cells when its string, like you make with numpy matrix sum ?
sorry I found my answer bye !
 
you're welcome ;)
 
As far as I can tell, Pandas can do absolutely anything
And not even in the snarky sense of "turing-complete languages can all emulate each other, although it may be a pain in the butt"
 
>>> pd.Series(['this ', 'is ' ,'weird!']).sum()
'this is weird!'
 
It's me again ahahah ^^ lol
yes , when I create two dataframe they have all the same column etc..., the content are different
and surprise, when I make
>>> pd.DataFrame(["A"])
0
0 A
>>> pd.DataFrame(["B"])
0
0 B
>>> a = pd.DataFrame(["A"])
>>> b = pd.DataFrame(["B"])
>>> a+ b
0
0 AB
so the string inside each cells are concatenated, its also possible to have like a list ?
also set ?
like that if have have the same value like :
df1 and df2 have some cells some are different other are identical like

df1
0
0 A
1 A

df2
0
0 A
1 B
df1 + df2 (some function or method) do :

0
0 set(['A'])
1 set(['A','B'])
 
@YoanBouzin I have no idea what "possible to have like a list? also set?" means
adding those dataframes hapens element-wise
 
12:05 PM
I just tried:
>>> {df1, df2}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Programming\Python 3.6\lib\site-packages\pandas\core\generic.py", line 1045, in __hash__
    ' hashed'.format(self.__class__.__name__))
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
And it amuses me that the error message has "thus" in it. Very high class, pandas
 
I think they are looking for sets inside the DF, not putting DFs into a set
 
oh OK, the last part of the question demonstrates the expected behaviour
that's not something you should do with pandas anyway :P
 
@AndrasDeak my goal is too fused two dataframe, all the cells (mean row - column intersection) will be fused together, its work with string because my upper example shoow concatenated string
I just try :
df1 + ',' + df2
and it show concatenated string with the comma between, so maybe after I can make some operation in each cell with apply ?
 
(df1+df2).applymap(set) gives you a df of sets, but it probably only does what you want when all the elements in the original data frames are strings of length one
I'm surprised I haven't been able to find an equivalent to multi-iterator map() even after five minutes of googling
 
@Kevin aaah good to know this applymap ;)
 
12:12 PM
Like, if these were lists, it would be easy
>>> x = ["A", "A"]
>>> y = ["A", "B"]
>>> list(map(lambda *args: set(args), x, y))
[{'A'}, {'B', 'A'}]
>>> list(map(lambda *args: list(args), x, y))
[['A', 'A'], ['A', 'B']]
(not necessarily the most Pythonic approach, but you get my point)
 
so yes the string will be not always equal to 1 so apply to a function after the concatenation with a distinguishable text separator like comma, hyphen , ore any symbol, it will be better if after apply to a custom function, that split the string, convert to a set and return the value ?
 
@hpaulj - regarding my deleted question earlier today - stackoverflow.com/questions/51318922/… it turns out others have discovered this problem elsewhere too - github.com/matplotlib/matplotlib/issues/9720
 
@YoanBouzin I bet that would work, but I bet it would be slower than an approach that doesn't pass a lambda to applymap
... Assuming one exists
 
Out of curiosity, do you intend to keep working with this DF after combining the values?
It's usually not a good idea to have data structures within cells
 
the fact I work in familly tree data, assuming two poeple have make a tree for the same guy , but the informations given can differ a bit, each familly tree are in a DataFrame.

If I want to merge the data , I can Have a long dataframe with lot of column, but if I have like 100 Tree for the same guy (because lot of cousins lol) , il will be a huge dataframe, so,

My goal is to have all of it in one, keeping the diffrent data if the string are different
 
12:19 PM
I'm getting the feeling that this is one of those things that they make intentionally hard to do because it's not a good idea to do it
 
*it will
 
Skimming the pandas documentation, I get the strong vibe that Series objects (and by extension, DataFrames) should ideally contain only scalar values
Numbers: good. Lists and sets: bad. Strings: tap dancing on thin ice
> The best way to think about the pandas data structures is as flexible containers for lower dimensional data. For example, DataFrame is a container for Series, and Series is a container for scalars.
 
You're just going to get lumbered with longer syntax and a mental burden of understanding pandas without real benefit
But it's not exactly banned to do it anyway and maybe it's a useful interim step in what you're trying to do, IDK
We're in a post-BDFL anarchy. Put dataframes in dataframes
 
Pandas is only fun if you can use the super optimized code paths that blaze through a million elements with half a millisecond worth of C. If you're passing a string concatenating lambda to applymap, you're probably not getting that
 
Anywho, early dart on Fridays. rbrb
 
12:31 PM
ammmh I see, so , my data are stored in dataframe, (they're from a HTML table converted to Dataframe, from an requested URL by requests) maybe I can do some operation in the data and after use panda with these fast method
 
DSM
Friday decided-to-work-from-home cabbage for all.
@Kevin: you're basically right. Strings are treated as scalars in this context because they have to be, but lists cause problems. There are supported methods which can generate them like .str.split(), but basically everything's better if you use expand=True which just makes more series rather than cramming a list into an element.
 
Contributed a bit to an open-source project yesterday. If by "contribute" I mean "infiltrated the dev chat room, said 'hey, the spline reticulator is giving me widgets, not sprockets, could the problem be in ThingFactoryMakerBean?', and the core dev saying 'yeah probably, most likely you need to add a conditional at ThingFactoryMakerBean:preInitializeReticulator:2342, you wanna make a pull request?'"
Followed by two hours of him guiding me through the build process for the project, so I could make a change that would have taken him fifteen seconds to do directly.
 
DSM
He's probably thinking of the future PRs maybe he can get you to do. :-)
 
Quite possibly. Right now my PRs-to-bug-reports ratio is 1:3 so I'm generating more heat than light so far
I'm much better at complaining than fixing things so that might hold steady for the foreseeable future
 
1:00 PM
I've yet to have an actual code PR merged into numpy...
 
@AndrasDeak me neither... but I haven't tried
 
1:23 PM
\o cbg
 
Message from core dev: "your PR correctly returns widgets or sprockets depending on the appropriate scenario, but then you unconditionally galvanize() the result. Sprockets are already pre-galvanized, so this is pointless for them". Oops.
 
Terminology question: What do you call the "return value" of a context manager? I.e. how would you refer to the x in with foo as x:?
 
I always thought as them as pointer..... such as file pointer, but I guess that's not really accurate either :\
 
It's also optional. Maye enter-val?
 
The documentation seems to almost go out of its way to not give a name to the thing returned by __enter__
The PEP admits to this ambiguity:
> The code in the body of the with statement and the variable name (or names) after the as keyword don't really have special terms at this point in time. The general terms "statement body" and "target list" can be used, prefixing with "with" or "with statement" if the terms would otherwise be unclear.
so "target list" if multiple names are bound by the with statement. I guess just "target" if only one name is bound?
 
1:31 PM
Hmm, not sure if people would understand that. Maybe I should just rephrase my docstring to something along the lines of "the context manager yields a Bar object"
 
Have you considered "context object"?
 
I have a piece of code which runs other pieces of code through something like the following
 
The trick is distinguishing between "the thing returned by __enter__" and "the thing that __enter__ is a method of"
In some cases, like with open(filename) as file:, they're the same object. But it is not always so
 
"the thing that __enter__ is a method of" is a context manager by definition, I think
 
Yeah, the term is formally defined in the PEP a paragraph or two above the bit I quoted
> This PEP proposes that the protocol consisting of the __enter__() and __exit__() methods be known as the "context management protocol", and that objects that implement that protocol be known as "context managers".
 
1:35 PM
I have a piece of code which runs other pieces of code through something like the following: cmd = cmd.split()

proc = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True), now what I'm looking to do is properly capture instances where the code that is being called encounters either an error or a sys.exit line and raise an exception or something but I'm not sure how to go about this, does anyone have any suggestions?
 
So any term you coin to refer to "the thing returned by enter", should try to not be similar to "context manager", to reduce confusion
 
Hence my proposal to refer to the object returned by __enter__ as context object, if that makes sense
 
morning cbg
 
morning bud :D how goes it up river
 
@cd123 Well, you could check the returncode attribute of your Popen object after it terminates. Most well-behaved programs return a nonzero value if an error occurred.
 
1:38 PM
@vaultah Hmm, I rather like that. How about "context value" though, is that better or worse?
 
@MooingRawr yoooo....hockey got cancelled last night....sad
compressor broke....the heat killed the hockey
Canadian problems are Canadian
 
@Kevin Does this also account for sys.exit lines?
 
wait your hockey league is all year ?
I was about to say, our hockey rinks are generally closed for the summer, cant sustain the heat.
the good news is that we just turn it into a lacrosse/ball hockey rink, at least that's what the rink near my place does.
 
@cd123 It's impossible to detect whether the process exited because of a sys.exit() call or not.
 
@cd123 I'm pretty sure it does. But in general, you should try to avoid using subprocess to call one Python script from another one. It's better to use import, in which case you can easily catch exceptions thrown by the imported script with a simple try-except
 
1:42 PM
@MooingRawr most arenas do get converted to ball hockey....but we have a few that stay open because there are summer leagues and camps.
I also learned the one near my house gets shut down completely, because I went to get my skates sharpened and they were closed....
 
To rephrase, you can tell what number was in sys.exit's first argument by inspecting the returncode attribute, but you can't tell if the program terminated because of sys.exit or for some other reason
 
@Kevin Whilst having the differentiation between sys.exit and any other error would be useful if it's not possible unless I use import or something then I can live with that. If the returncode attribute can act as a test for program termination then I can use that for now until I further my understanding.
 
Keep in mind that sys.exit(0) means that the program ended successfully, so even if you come up with some way to detect exit() calls, it may not make sense to consider an exit call an error in all cases
Even though it's technically terminating the program by raising an uncaught SystemExit exception. Not all exceptions are errors :-)
 
@cd123 sys.exit is not an error. What you're looking for is the returncode; 0 means a successful exit and everything else means the process terminated because of an error
 
Mm hmm, it's not productive to mentally categorize possible termination events as "program ended successfully | sys.exit was called | an exception was thrown" because those aren't mutually exclusive. The only categorization representative of reality is "program returned 0, signaling a success | program did not return 0, signaling an error"
 
1:56 PM
>>> os.system('python -c ""')
0
>>> os.system('python -c "import sys; sys.exit()"')
0
>>> os.system('python -c "raise ZeroDivisionError"')
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ZeroDivisionError
1
>>> os.system('python -c "import sys; sys.exit(1)"')
1
^ the first two are "normal" exits, the other two are errors
 
All that said, perhaps you could distinguish between "error because exit() returned a nonzero value" and "error because an exception was raised and not caught" by inspecting the contents of stderr, since exit() doesn't print a stack trace... I don't think it's a good idea, however. A program could easily fool any stack trace detection algorithm by printing a string that looks like a stack trace, then exiting with sys.exit
 
2:12 PM
@Kevin So to handle this kind of stuff better in the future what is the general approach, using a combination of try and except with importing or something else?
 
Yeah, import with try/exept
You can even catch SystemExit exceptions, although I struggle to think of a good reason for doing so
 
@Kevin Ok thank you for the information. Something extra that I can improve my code with is always appreciated.
 
friday cabbage
 
Happy birthday to King Friday the Thirteenth, of Mr Rogers Neighborhood
In lieu of gifts, please be the person Mr Rogers knows you're capable of being
 
2:36 PM
@Aran-Fey to me, only objects of "primitive"/built-in types have values :P
 
Curious. You don't consider an object a value?
Since everything's an object in python, I think of "object" and "value" as one and the same thing
 
I think of it like this: there are variables, which have two components, name and value. All values are objects, but not all objects are values.
In particular, objects with a refcount of zero, I would not consider a value
In practice this means that 99.999% of the objects you interact with are also values
 
@Aran-Fey I guess I think of values as very simple objects (numbers, bools, strings, etc)
i.e., all values are objects, but the term I'd use for simple objects is "value"
 
Pretty fascinating how everyone has their own mental model of these things
 
Perhaps "non-collection objects representable as literals" matches vaultah's categorization
 
DSM
2:46 PM
@vaultah: huh. I don't have that association with values in Python at all. I just think of "value" as the rhs of a (name, object) binding.
 
[fist bump]
 
for k, v in d.iteritems():
    for x in v:
        {define 8 functions}
        {use 1 of them}
actual code I just came across
 
Objects, values and types is probably relevant here.
 
who would do such a thing? the core maintainer of a 5k+ starred project on github
 
An object has a value, but it is not a value
 
2:49 PM
@Kevin yeah, that's close
 
DSM
Oh, hey, piRS. Question I hit today: is there a slick way to turn an {(index, column): value} dict into a frame?
 
@DSM is that a single keyed dict?
 
@Kevin I disagree. I say objects have values and are values, both at the same time.
One being the "C-level" value, the other being the "python-level" value (i.e. the object itself)
 
The documentation is inconsistent in its usage of the term "value" in a way that implies that "value" can mean both "an object" or "the non-id, non-type part of an object". For example, Expression Statements says "procedures return the value None". This implies that the None object can also be considered a value.
 
@DSM IIUC:
d = {
    ('x', 'a'): 3,
    ('x', 'b'): 1,
    ('y', 'a'): 4,
    ('y', 'b'): 1,
}

pd.Series(d).unstack()
   a  b
x  3  1
y  4  1
 
2:55 PM
procedures certainly do not return "every part of the NoneType singleton instance object except for its id and type"
 
DSM
@piRSquared: tx-- for some reason I was stuck in the dataframe world and didn't think of using a series as an intermediary.
 
One section below that, assignment statements say something similar about binding names to values.
 
To summarize: It doesn't really matter, as long as your mental model works for you :D
 
Perhaps context is important here. If you're working with Python code, you can say that an object is a value. If you're working with the C infrastructure that makes up Python, you should think of PyObject instances as objects, and all of its fields (except ob_refcnt and *ob_type) as the value of that object
 
DSM
The downside of working from home on a Friday is that I don't get to eat the free pizza provided for lunch, which I'd forgotten until right now. :-/
 
3:02 PM
Obnoxious overkill
index, columns, values = zip(*((x, y, z) for (x, y), z in d.items()))

i, r = pd.factorize(index)
j, c = pd.factorize(columns)
n, m = r.size, c.size
b = np.zeros((n, m), np.int64)
b[i, j] = values

pd.DataFrame(b, r, c)
 
In the spirit of high-level languages, the vast majority of the time you shouldn't give a dang about how an object's data is actually represented in memory, so you ought to pretend the second definition doesn't even exist
Maybe 1 and True have the same value at the CPython level, but you don't care, all you need to know is that 1 == True and 1 is not True
 
To paraphrase Thomas Jefferson "All men are created equal, but not necessarily the same"
 
@DSM .... We use to have free Timmies on Friday, not anymore... :( I wish my company provided free lunch.
On the plus side you don't have to deal with Friday commute.
 
Then how "free" is that lunch if you are required to drive to get it?
 
DSM
We only get lunch provided one day a week, and then only in Building #1 (where I'm temporarily situated). I can't complain, though.
 
3:10 PM
@piRSquared Who says you need to leave the office on Thrusday >-o don't need to commute if you never left :D
 
Way to think outside the box (read: outside societal norms)
 
There are four people within my immediate social circle that all have jobs that provide free alcohol. It boggles my mind.
 
DSM
Kevin! Friend! We don't hang out enough.
 
3 of them follow a policy of "not during work hours... Ok, maybe on Friday afternoons" which is tacitly endorsed by their superiors, and 1 has a policy of "here, fill up your trunk, you will need it on your journey"
Only the latter friend is in a position to actually share, so it's not the cornucopia that you might imagine
 
wim
It boggles my mind to think of a tech company that doesn't provide lunch / free alcohol
You can not recruit the best people in tech if you don't offer these perks, you will immediately lose them to the googles and facebooks
 
3:24 PM
Well, somebody's got to hire the people not in the 95th percentile. And those people don't provide free lunch.
Citation: am mediocre employee
 
DSM
Free alcohol is an extraordinarily rare perk up here in a professional context.
Most large firms would consider it an HR nightmare waiting to happen.
 
wim
what do you consider a "large" firm, out of curiosity?
we have boxes of beer literally piling around because people are not drinking them fast enough
 
HugeCo is, eponymously, huge. But I don't know if I'd call it a tech company.
 
DSM
I dunno, 1K+? Large enough that you don't even recognize anybody. And NumberFirm is more a number company than a tech company, even though we have many techs.
@Kevin: well, not every technology is computer technology. ;-)
 
wim
perhaps it's a tech industry thing. do you have bicycles hung up on the walls?
 
3:32 PM
Ok, then we are in the business of things that were at one point invented.
These walls are exclusively for dilbert comics, corporate messages about synergizing excellence, and "hang in there!" posters
 
i am using python ConfigParser to read a config and using its set function to update values for keys. This works fine but it removes comments in the cfg file which are important and should not be removed
 
@DSM did you solve your test issue?
 
pastebin.com/tbL6iNb2 this works fine for non commented config files
 
DSM
@Ffisegydd: I did. My "aaaarrgghh" was an aargh of sudden realization.
 
What was the reason?
 
DSM
3:46 PM
My test scripts are designed to run in our test environment (makes sense, you don't want an untested process potentially breaking your production database). The test database is supposed to be kept in sync with the production database, though, as otherwise what good are the tests? One particular table we needed only works in production, though, and so the default for library use -- such as when the code is imported in non-test mode points at the production database.
So literally it all came down to a U being picked up from the environment when it should have been P.
If the database had been refreshed like it's supposed to be, none of this would have happened.
 
I hope you've learned your lesson: tests can't fail if you don't write tests.
 
Hello! can anyone help me with logging or Journal type of functions in Python? I have created a function and that output goes directly into the sql query that i have created in the script with the help of a placeholder there. But what if the sql returns a blank query? how can i create an exception for such kind of error and also log in to my journal file or somethin
 
DSM
Part of the reason I'm working from home today is that I was in such a bad mood yesterday afterwards that I didn't sleep well.
 
did you want to talk about it ?
 
DSM
I did not, in fact. ;-)
 
3:51 PM
And yet I brought up painful memories anyway, because curiosity killed the Canadian.
It finally rained \o/
 
4:17 PM
There goes another question that would have been fun if anyone could agree on what the requirements actually were -_-
 
DSM
?
 
My interpretation is that 010101010101 satisfies the requirements given, because no digit appears three times in a row; yet none of the existing answers (at the time of my comment spree) would ever generate such a value
Also any answer using random seems to ignore the "rainbow table" tag, which implies that OP wants all elements of the set, possibly in lexicographic order
 
Anyone familiar with flask/web development that knows what a "HTML site" is in this question?
The OP keeps seeming to refer to something that exists outside of flask in the comments and question, but I genuinely don't know what it could be
Now I'm confused about whether it's me that's confused or the OP. Confusing.
 
4:34 PM
from what my understanding, OP wants to put his flask's app inside his preexisting website that was build on html5 or something
 
Oh well, I threw my hat into the ill-defined ring. Not for the possibility of points, but for the faint glimmer of a possibility of the other answerers thinking "I may have read this question incorrectly"
 
Thanks. The part that's confusing me is the only mention of HTML repeatedly and not some other framework or sever or anything
 
yeah i dont understand the question 100% but that's my guess.
 
The closest I can think of (and they do say they're a beginner) that they are just opening a HTML file in their browser
 
Questions that ask about Pyhton scripts can't be trusted to use accurate terminology
 
4:38 PM
That much is obvious; I'm resolutely on the side of Phyton after the split
 
im reading about Neural network learning, the math behind it is kinda confusing. I guess I need to go brush off my math textbook and what not.
 
What type of NN? Starting with a standard back propagation network?
 
cbg
 
cbg
@roganjosh it's a book I picked up "Neural Network and Deep Learning"
not sure if I should follow it but it's a decent read except for the math bits lol
 
print(re.search(r'[0-9]', '$100'))          # '0' in '$100' or '1' in '$100' or '2' in '$100' or ....
print(re.search(r'[0-9]+', '$100'))         # Meaning... permutation1(say '0') of digits(0 to 9) in '$100' or permu2(say '200') of digits(0 to 9) in '$100' or ....
 
4:44 PM
I ended up never submitting my thesis but IIRC I managed to boil the steps down in a way I didn't find clear in the books I was reading. I'll take a look at what I wrote when I get home and share with you if I think I did a decent job
 
Is this the right interpretation of r'[0-9]+'?
 
I don't know what permu2 means. The right interpretation is "one or more digits in a row"
 
permutation2
 
Try harder. Or even better: read what Kevin wrote last and run with it.
 
I think the idea is correct, but "permutation" definitely isn't the right word to use. "combination" is more accurate.
 
4:57 PM
Please don't make it worse :P
starting to figure out the correct terminology will lead us all down an overexchange-shaped rabbit hole
What matters is the actual behaviour which Kevin's message unambiguously expresses.
 
Ok, change of topic: I suspect there's an easier way to write this code that returns a context manager that opens a file, but I can't see it.
... # a bunch of code
@contextlib.contextmanager
def _open_file(path, mode):
    with path.open(mode) as fileobj:
        yield fileobj
return _open_file(pathlib.Path(file_), mode)
Any ideas?
 
what more dos it do compared to open?
oh, is this a one-line context-managed open thingy?
 
That's one of many if-branches in my function. The function always returns a context manager, that's why I have that convoluted setup.
 
ah
probably way over my head anyway
 
Basically I want to be able to do with my_function() as fileobj:
 
5:05 PM
that's what I figured, thanks
 
I've got brain fog today, but I suspect that my_function may be used as if it were a context manager, as long as it returns a file object.
If so, you could just do return path.open(mode), no decorator required, no yield required
I just tried writing a function def f(): return open("test.py"), and after executing with f() as file: pass, when I inspect the file object, it's closed. So that means it must have called __exit__ properly... Right?
 
and would the decorater handle enter/exit?
 
Hmm, that'd open the file immediately. I guess that's fine. I don't have a real reason to postpone the file opening until the with block is entered.
 
ah, I see, in with open() as ... the open is called anyway and there's no magic
 
I'd be inclined to run my idea through some tests to ensure that it behaves properly in the case of exceptions and such. But it's food coma O' clock on a Friday, so I am unable to help write those tests.
 
5:11 PM
No tests required I think. It's a good solution, thanks
 
wim
open() opens the file immediately, __enter__ does nothing (just returns self)
 
yeah, but my original code doesn't open the file until the __enter__ is called
 
wim
pathlib.Path already provides an open method, by the way, also read_bytes and read_text methods for one-liners.
so it's not clear to me what feature you're trying to add ...
 
Not sure why you're comparing it to pathlib.Path. All I want is a function that returns a context manager that yields a file
pathlib.Path isn't a context manager, is it?
 
wim
it's not a context manager but it provides managed read methods
it is a context manager, actually
too much github
 
5:21 PM
Ctrl+F yields 0 results for "context" in the pathlib docs
 
wim
It defines __enter__ and __exit__, and is therefore a context manager.
 
What do they do though?
 
wim
allows you to do with path.open() as p:
 
@jpp I took the liberty of extending the question myself :P
 
wim
also, reading the source, it looks like it is re-entrant
 
5:24 PM
@wim That can't be right. Path.open doesn't return a Path, so its __enter__ and __exit__ aren't relevant there.
 
wim
hmm, you're right there
 
The question is, what does with Path('foo/bar') as x: do?
 
it's an early form of an assignment expression
 
:/
 
wim
It looks like __enter__ does nothing except ensures you're not entering an already closed context
and __exit__ marks the context as closed, with some state that must be used elsewhere
I wish I had a better answer for you, but I never came across the need to use those features yet
could be a good question on main. "why is pathlib.Path a context manager?".
 
5:36 PM
I think I'll keep my curiosity in check until they officially document that
 
Maybe there's some utility in having a context manager that exists only to ensure you don't re-enter a block while that same block is executing higher in the call stack. When you absolutely positively want to not recurse.
Why such a feature would exist in pathlib, I haven't a clue
Plenty of questions have crossed the front page that would have benefitted from being provably not recursive. Although 99% of them were written by people who have never heard of context managers.
By the time they're good enough to use it, they're good enough to not need it
 
5:48 PM
How can I tell python I want to use the same variable twice in a string, the below generates an error unless I repeat the variable twice after the modulo because python is expecting two different variables
  print('The variable assigned to bucket was %s, and assigned like so "%s"' %bucket)
 
don't use percent formatting, but I don't think you can
you can use {0} twice in a format string
>>> bucket = '42'
>>> print('The variable assigned to bucket was {0}, and assigned like so "{0}"'.format(bucket))
The variable assigned to bucket was 42, and assigned like so "42"
percent formatting is ancient; format strings or f-strings are way newer
 
buckets are the meaning of life?
 
(also it's not a modulo, it's a percent sign)
 
Thanks Andras
 
no problem
 
5:51 PM
oh i read here: "To this purpose the modulo operator "%" is overloaded by the string class to perform string formatting. "
it was modulo
 
that's plain wrong
 
oh ok thanks
 
% has multiple meanings depending on context
hmmm, hold on, that may technically be right...I never thought of that
 
so does @ but that didn't stop them from calling it __matmul__ ;-)
 
that makes it even creepier
Yeah, I was wrong, sorry. Also, ew.
 
5:54 PM
Yeah, I'm not crazy about the choice of dunder names, either
 
     f"You are {age} years old"
 
Patiently awaiting the day that intrinsic operators are implemented via @override("%") decorators
 
@Gary those are f-strings, starting from python 3.6
 
but i can't get this to work, how would you write a full statement with that?
 
f strings are super rad, let's use lots of them
 
5:55 PM
and I don't think you can reuse variables with them
 
(if our version supports them)
 
ah ok great thanks both
i'll look into them
 
they really are neat, but not always convenient
 
I mean, f"{x} {x}" is valid. I don't think there's any way to repeat the variable without repeating the name, if that's what you mean.
 
Except when that rad-ness generated a question yesterday where an OP was trying to change a parameterized SQL query to purely f strings :)
 
5:57 PM
@roganjosh one can even stab themselves in the foot with a shiv carved from a childproof plastic spoon
 
As time goes on, "will newbies use this feature improperly?" gets lower and lower on my list of reasons to not use a feature
 
something something 572
 
Oh, the SQL injection comment is getting boring for me to make these days
I think I understand why SQL questions get so few views tbh
 
Some users ask "How do I turn "[1,2,3]" into [1,2,3]? I tried s.replace('"', ''), but it didn't work". If regular old strings are misunderstood, then there's no helping them
 
@roganjosh have you seen laurent22.github.io/so-injections?
@Kevin I imagine that would even work in JS ;)
 
6:00 PM
Well that at least requires ast.literal_eval. People wanting to remove " from strings is another issue
I hadn't seen that, Andras, but that's terrifying
 
"How do I parse the contents of a string into its corresponding literal?" is fine. "how do I get rid of the quote marks on this thing?" is not so fine.
 
The SQL questions are usually something else. It's interesting how people read the material and think that string formatting will be easier, only to contort their code into something that is either completely broken or illegible and vulnerable. It's like they actively defy documentation.
 
what the engine does is mystifying and shrouded by clouds; a good old string you put together is tangible
 
A completely subjective view, but this affects SQL way more than python, and python is a growing starter-language. In newbie Python questions, I can kinda catch their train of thought. SQL, it's active defiance.
 
More evidence that numpy has a function for everything
 
6:12 PM
^ is actually really useful in numpy
And I'd say mainstream. I use it all the time.
You wanna look at some of Divakar's answers :)
 
OP asked "what is the fastest..." and by that metric I'm almost certainly going to lose, but I guess I can hold out hope he'll reply to the other guy "built-in modules only, please :3"
 
choices is also fairly new
 
Users that don't tag their question with a specific version should be prepared to break into the BDFL's personal treasury in order to access the only copy of the nightly build that supports the feature I'm telling them to use
 
A Google search leading to a question answered by Divakar is a roller coaster of emotions. I know it answers my question if only I can work out what the hell is happening and then how to adapt it to my problem.
 
Ooh, I thought I had an edge because I gave a working example, but now the other guy has one too. With screenshots. I'm doomed ;_;
 
6:18 PM
   print('The variable assigned to bucket was %s, and assigned like so "%s"' %(bucket, bucket))
when we use something like the above, are we passing a tuple to python, is (bucket, bucket) a tuple ; or is this acting more like a method when we pass two variables into a method like, print(a,b) for example
 
(bucket, bucket) is indeed a tuple
While we're here, have a comparison of the various string formatting approaches
>>> print('The variable assigned to bucket was %s, and assigned like so "%s"' %(bucket, bucket))
The variable assigned to bucket was 23, and assigned like so "23"
>>> print('The variable assigned to bucket was {0}, and assigned like so "{0}"'.format(bucket))
The variable assigned to bucket was 23, and assigned like so "23"
>>> print(f'The variable assigned to bucket was {bucket}, and assigned like so "{bucket}"')
The variable assigned to bucket was 23, and assigned like so "23"
 
lunchtime cabbage
 
that's really useful thanks kevin
 
We can confirm that the right-hand argument to the % operator is considered a tuple by using a variable in its place:
>>> t = (42, 23)
>>> type(t)
<class 'tuple'>
>>> "I had %d coconuts, but now I only have %d." % t
'I had 42 coconuts, but now I only have 23.'
 
great
 
6:23 PM
In comparison, trying this experiment on a function will show that replacing max(42, 23) with max t` does not work
>>> max t
  File "<stdin>", line 1
    max t
        ^
SyntaxError: invalid syntax
So we can conclude that the percent syntax is qualitatively different from function calling syntax
 
that makes sense and useful to be able to know how to test it in the language, i just discovered also if you omit the index's from { } , when using the format method, with more than one variable you get an error "tuple index out of range". But if you are only using a single variable, and using it once in a string with the format method, you can omit the index like so print("Hello {}".format(name))
 
Yeah, in the absence of numbers, string.format will just insert the arguments in the order you supplied them
>>> "I had {} coconuts, but now I only have {}".format(42, 23)
'I had 42 coconuts, but now I only have 23'
You can have more than a single variable, as long as the number of arguments matches the number of curly bracket pairs
 
ah i see, great, i guess if you have more than perhaps 2, it makes sense to include the indices just for readability if you need to cross reference a variable from the tuple to the string while reading the code
*indexes
 
Sure, and you can use keyword arguments to be even more explicit
>>> "I had {x} coconuts, but now I only have {y}".format(x=42, y=23)
'I had 42 coconuts, but now I only have 23'
Although at that point you may as well use f strings and save yourself a half dozen characters
 
that's useful to know, also of course i just realised .format(x,y) ; (x,y) isn't a tuple is it, it's passing two variables into a method ; unlike the modulo string syntax
 
6:35 PM
.format() is a perfectly ordinary method call, yep
 
definitely
 
wim
>>> '%(k)s %(k)s' % {'k': 'val'}
'val val'
key/val formatting is not new feature to str.format
 
useful to know also thanks wim
 
6:49 PM
I just read the Guido is retiring from BDFL message, his tone sounds quite low in that message, like he's not in a very happy place at the moment
 
CBG
 
I don't imagine it's an easy job
 
It ain't easy being Bee Dee... Eff Ell.
 
yes true!
 
I think it's just part of humanity. You'll get consensus on important issues and it's easy enough to unite people under a banner. Eventually, the important issues dry up and you get down to matter-of-taste issues and things are no-longer fun or interesting after that point.
 
6:57 PM
yes I guess when a group of experts have differing opinions on the right course of action, and the numbers are fairly equal on both sides, either action is likely to be just fine.
 
DSM
Well, maybe not just fine, but a reasonable choice given the information available. :-)
I guess it's time for KevinScript to take up the slack!
 
00:00 - 19:0019:00 - 00:00

« first day (2827 days earlier)      last day (2120 days later) »