« first day (2476 days earlier)      last day (2471 days later) » 

4:00 PM
@EthanFurman downvoted and flagged for being misleading
 
But it also takes quite some foresight to write your code in a way that makes sure it can be modularized
 
My conception of what is the most common use case may be colored by what my most common use case is, here
 
I can imagine that sys.exit could be more sophisticated on some exotic operating systems
 
I don't make CLI tools very often.
 
I make CLI tools all the time.
 
4:01 PM
after all its one more level of abstraction
 
I write scripts that are executed from the command line but they're not so robust as to earn the name "tool"
 
Every other Python script I write these days (as in not designed for SO use) uses argparse, so I would say they are proper CLI tools :P
@marxin Not sure what you mean with that. sys.exit essentially tells the interpreter to shut down, no?
 
@EthanFurman Um, ARJMP edited the answer so it does return 3, making your comment on the answer obsolete. OTOH, it's certainly sub-optimal to call getattr when the object supports indexing.
 
@poke imagine you have a operating system where shutting down a terminal requires doing something more
 
Not shutting down a terminal, the Python process
 
4:05 PM
whatever
 
And no, I cannot imagine that.
^^"
 
I can
 
@poke to be fair, a stack-based VM is Simple™ and a register-based VM is tricksy
If you're writing a terminal-interactive process (control codes and/or curses) then shutting down would need to so fancier stuff. Ideally, whatever library you're using to help with that would take care of it for you.
 
Python does have an onexit handler module but I've been pretending that it doesn't exist for the purposes of the conversation
 
and possibily onexit handler does try catch on SystemExit exception ;p
that would be funny
 
4:11 PM
the default one catches SystemExit and calls sys.exit.
That would be funny.
 
stack would not be happy though
 
A stack overflow exception is also a way to terminate an application.
 
it would be like drinking salted water to quench thirst
 
Or burning down the fuel to stop the fire
 
Hey, "fighting fire with fire" is a thing, no?
 
4:17 PM
So is terminating applications with a stack overflow exception...........
 
Park rangers will occasionally burn down a fifty foot wide stripe of the forest so that natural wildfires can't jump from one side to another. Seems like a good career if you're into arson.
 
I think I read that one on this site where they share odd IT experiences (forgot its name)
> This class of programs includes many student programming exercises and some simple applets and utilities […]
And people wonder why students are incapable of writing good programs…
 
yes, that was it
I think
 
4:20 PM
@Kevin During the Gulf War, and I assume it's a standard method, oil well fires were put out by detonating an explosive at the well head.
 
@KevinMGranger yeah, few years later another engineer "hmm we can increase the range 3x times if we just replace an engine to a better one"
 
So this morning we had a super() call out side of a method for a class. I was wondering if this, even though it's a terrible coding practice, would be the reason why you would call super() outside of the method : pastebin.com/PhUCsx6q The only thing I could think of is if you want to call a method explicitly on reference to the super class. (why not put it in init? not sure why you wouldn't maybe you only want it ran explicitly not on every object
creations or something along those lines).
 
@MooingRawr super() isn't causing that print, that's just a side effect of the definition of the class.
 
Oh...
 
Class definition bodies are executed at the module level.
 
4:26 PM
Right... I forgot about that
 
I'm getting TypeError: must be type, not classobj from that snippet
 
Sigh back to wondering why someone would call super() outside of it ...
@Kevin Python 3.5.2 is where I tested but either way David is correct....
 
I suspect there are valid use cases for calling super at the class scope, but I don't think there are valid use cases for calling super and then not calling a method of the resulting proxy object
 
Maybe one day we will find out ... I don't think it's a good enough question to ask on the main site lol...
hopefully that person would respond to your comment.
 
I commented on the original post asking for an explanation. The author was last active yesterday so I'm hopeful I'll get a response soonish.
 
4:30 PM
maybe something like this?
however difficult to imagine why would someone do it
 
Hmm, does zero argument super even work at the class scope? I get a RuntimeError when I try.
 
There are reasons to call 1-argument super outside a method - in fact, it's the only place I can think of where you'd call 1-argument super - but the call in that answer looks pointless.
 
class X:
    @classmethod
    def blah(cls):
        print("Hello, world")

class Y(X):
    super().blah()

# Traceback (most recent call last):
  # File "test.py", line 6, in <module>
    # class Y(X):
  # File "test.py", line 7, in Y
    # super().blah()
# RuntimeError: super(): no arguments
Ah
I know that Python 3 does some sneaky introspection to determine the context that super is called in, but I thought that the magic worked as long as you were inside a class, even if you weren't inside a method of that class
 
Nope. The classslot it checks doesn't exist until the class is defined, I think.
 
Hmm, that is a reasonable explanation
I was confused by this paragraph in the docs:
> Also note that, aside from the zero argument form, super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.
I read "the zero argument form only works inside a class definition" as "the zero argument form works everywhere inside a class definition" but I don't think that's the correct interpretation
 
4:39 PM
I read that as you did too....
 
"aside from the zero argument form, super() is not limited to use inside methods" can be read to imply "the zero argument form is limited to use inside methods"
 
That would be a much clearer way to word it. Send a patch!
 
I read it as "the zero argument form can be used outside methods"
Man at least Python's docs are clearer than c#. I can't stand reading Mircrosoft's docs :\
rbrb lunch time :D
 
Well I think the paragraph conveys its intended information (i.e. "super can be called outside of class definitions") and it creates confusion in an adjacent idea space as a side effect
 
@PM2Ring Cool. Deleted my comment and removed my down-vote. Thanks for the help.
 
4:42 PM
Changing it to be clearer on the side point may muddle the main point. This is all subjective ofc
 
any idea what wrong in ValueError: time data '18-APR-2017 09:18:17' does not match format '%d-%b-%Y %H%M%S' (match) it should match I think
 
@pythonRcpp not really
 
strftime.org already tried
 
try this %d-%b-%Y %H:%M:%S
 
ohh..no i was missing : ... pheww. thanks @marxin
 
4:47 PM
@pythonRcpp np
 
DSM
An important skill in debugging is to find the minimum failing case-- it's a lot easier to spot minor errors when they're (relatively) big.
 
@Kevin I would read the former to mean the latter
I mean, that's exactly how I'd understand that
 
yeah
recbg
 
TFW you find a script called check_rouge_apache.php
 
5:11 PM
TFW TFW....TF....W
 
WTF?
 
TFW You WTF a TFW
 
We also need a FWT
 
"TFW WTF" FTW!
 
what would be a good FWT
 
5:13 PM
> FWT is short for "Fucking Waste of Time", often used by gamers for unimportant things, other people do. (urbandictionary)
works for me
now let’s put it all in one sentence
 
Watch yo profamity
 
TFW you realize looking up these abbreviations is a FWT. WTF… >_< But hey, Urbandictionary FTW.
@KevinMGranger Not mine, it’s a quotation!
 
wait...we need all permutations
:D
 
two more TWF and WFT
TWF = that was funny
 
Working From... Thome
 
5:18 PM
Tomb
Working from tomb
and C# strikes again
 
well fancy that
 
I was thinking of that but i doubt there'd be a good wifi signal through all that stone
 
hehe
working from there
where?
there
 
@idjaw We have a set of derangements:
WTF
TFW
FWT
 
My math is too rusty for this
such that no element appears in its original position
hmm.
So, WTF, WFT would not be a derangement, but it would be a permutation?
 
5:27 PM
Looks right to me.
 
@DSM one of the things I'm learning, is trying to spot an error or bug (side effect not wanted) before I compile code....
 
I've found that the best way to have bug free code is not to be really good at debugging, but to not write bugs in the first place.
3
Maybe that sounds kind of flippant but I'm being sincere
 
The Unix solution to any problem is doing the simplest thing. The simplest way to fix a problem is to not have it in the first place.
> GDB is deterrence strategy debugger. With GDB programmer is just more careful while coding so that use of GDB is not necessary.
 
When there's more than one way to implement something, it's possible that the different approaches will have differing "surface area" onto which bugs can attach themselves
 
@Kevin I wish to get on your level or as the kids these days would call it 'gitgud'
 
5:31 PM
There is an art to choosing the approach with the smallest surface area.
@MooingRawr I just talk a good game.
 
I talk a pessimistic honest game. Sometimes this hurts me more than anything :\
 
When I have a million stars on Github, only then will I allow people to be jealous of me.
 
@Kevin I think the best way to have bug free code is to simply not write code.
 
:-)
 
That seems to be the de-facto way to avoid bugs in KevinScript at least
 
5:42 PM
B-)
 
… and I think that guy really knows how it works.
heading home, rhubarb
 
5:55 PM
Void conversations are the best
 
hey, i am pretty new to python and i am trying to move some heavy tasks over to python from PHP.
Now i am writing an "importer" to an update que, but i can't get the List thing to work, anyone able to help me out?
Code: https://gist.github.com/Hareland/ef3f60e7eeffb77c7678504761ec2819
Python V: 2.7.1
my problem is on L#24+
 
I haven't got experience with mysql but the line cursow.execute(sql2,(item.id)) looks suspicious to me
is the second argument supposed to be a tuple? Because it's not a tuple right now. Try cursow.execute(sql2,(item.id,))
 
Yeah, the data i get in for item in results is json i think
ill try sec
 
wat
Pay no mind.... https://t.co/mnIPHJXE1h
 
DSM
I'm not sure "cursow" is right either..
 
6:06 PM
>>> x = (1)
>>> y = (1,)
>>> type(x)
<class 'int'>
>>> type(y)
<class 'tuple'>
As a simpler example.
 
i fixed that one, it came when putting up the gist x)
 
@idjaw it's a mapping that wraps the real dict. created anew each access
 
lol, when I was younger I couldn't pronounce "r" sounds properly
"cursow" sounds like something I would have said
 
sh-3.2# python que_importer.py
Traceback (most recent call last):
  File "que_importer.py", line 26, in <module>
    cursor.execute(sql2,(item.id,))
AttributeError: 'dict' object has no attribute 'id'
 
item["id"], perhaps?
 
6:07 PM
@KevinMGranger so there is something called when dict is accessed?
 
DSM
If it's a dictionary, then we'd use the item["id"].. aargh, Kevin'd by the OG!
 
that's the part i'm not connecting
 
Or "cuwsow" actually
 
I wonder if it's possible to get data from one table into another without having to do any inbetweening with Python
 
sh-3.2# python que_importer.py
{u'updated': datetime.datetime(2017, 6, 15, 16, 32, 45), u'added': datetime.datetime(2017, 6, 15, 16, 31, 58), u'description': u'Demo', u'buy_limit': 1, u'members': 1, u'type': u'Demo', u'id': 1, u'name': u'Demo'}
Traceback (most recent call last):
  File "que_importer.py", line 26, in <module>
    cursor.execute(sql2,(item["id"],))
  File "/Library/Python/2.7/site-packages/pymysql/cursors.py", line 164, in execute
    query = self.mogrify(query, args)
  File "/Library/Python/2.7/site-packages/pymysql/cursors.py", line 143, in mogrify
the one above is just for myself (the json)
 
6:08 PM
In [4]: a.__class__.__dict__ is a.__class__.__dict__
Out[4]: False

In [5]: a.__class__.__dict__ == a.__class__.__dict__
Out[5]: True
It's a mappingproxy, not a dict
 
I was thinking about that @Kevin but i can't do any sanity checks the same way then
 
right! ok ok....because at the call of __dict__ it will call a new dict.
is it as simple as this
>>> a = dict()
>>> b = dict()
>>> a is b
False
?
 
Not quite, because in this case modifying the class dict will affect both (I think?)
 
@KristianHareland Fair enough
 
Oh nevermind @KevinMGranger. My lack of understanding is due to the fact of not properly understanding mappingproxy
just found this
 
6:13 PM
"I am newbie in Python" I never would've guessed...
 
wow....there isn't a strong canon/protected "why does python return none"
to simply explain the default behaviour of a function without a return statement
 
@KristianHareland Curious. Your query only has one placeholder, so passing a single parameter should be enough to complete string formatting.
 
this is the closest I can find.
Do you think it's a good dupe candidate?
 
Alright, you mean the second executor ?
 
Yeah.
 
6:15 PM
Alright, thanks :)
 
oh nvm.....duped with this
 
So it's surprising to me that you're getting an error.
 
the wording should be fixed I think
Instead of Random 'None' output from basic Python function what do you think of Python function returns None without return statement
 
@KristianHareland Oh, maybe it's not recognizing "?" as a placeholder value. I think some libraries use a different syntax for that.
 
Yep i also figured that one now haha
i tried %
 
6:17 PM
What happens if you do sql2 = "INSERT INTO guide_price_que (item) VALUES (%s)" instead?
 
@idjaw It's mentioned pretty early in the tutorial section Defining Functions, so people who don't know that lack minimal understanding haven't done sufficient research.
 
I think sometimes you need to use % when doing wildcards, no?
Or maybe that's just sqlite, can't remember
 
@PM2Ring fair enough.
 
Obligatory notice: whenever possible, avoid using the "%" operator when creating sql query strings.
It creates a security hole big enough to drive a truck through
 
6:20 PM
It works !
 
Dang my internet connection is on the fritz
 
Yes, i come from PDO @ PHP
 
@idjaw Still, it's nice to have a canonical for stuff like that, rather than just downvoting. And both the questions you linked have good info.
 
so i am used to ? operator for sanetizing
 
kevin.exe is spawning additional instances
 
I thought you were just warning us thoroughly about the evil "%".
 
The very best time for your connection to fail is when you're about to tell someone that they are about to try something that will shoot them in the foot
 
or he's an AI trying to cover his tracks
 
@PM2Ring Maybe I should dupe the ones I linked to the protected one?
do you think they are similar enough to merit a connection a la dupe hammer?
 
what do you all use to make gui's in python? just trying to get an idea of what's out there and what people mostly use
 
6:22 PM
@Marcus he grows stronger with each star.
 
this chat does supply an indefinite amount of training material, hmmm.
 
dyb
Hi folks, i found a partial solution to my problem in this thread: stackoverflow.com/questions/11328940/… but i don't know how to apply this when i have a list of lists and i want to check against first element of each list.
 
@Kevin, if i want to use the same database connection, is there some way i can just include it ?
 
dyb
The solution i liked was: [i for e in bad for i in my_list if e in i]
 
Ie, by making a class or function by any kind ?
is it as easy as import file.py ?
 
6:26 PM
 
What does that say? Is it about my momma?? it better not be about my momma!
 
@Marcus Haha yeah, that image is so relatable and/or relevant to the discussion
 
curses
 
@idjaw The protected one is good, and I vaguely remember when Antti was cleaning it up to make it Python 3 compatible. But I kinda like the "Python — return, return None, and no return at all" one better as a canonical / tutorial, and I don't think either one needs to be dupe-closed.
 
@idjaw I'm sure your momma is a nice caring lady. No one would dares to talk about her, and I'm not saying that because of your lego hammer :D
 
6:28 PM
@KristianHareland Not completely sure what you're asking, there.
 
I have my connector (Database credentials etc) can i somehow include it instead of maintaining say 20 files with same credentials ?
 
@dyb what's your issue ? and can u provide an example of input and output ?
 
If you mean "is it possible to create that connection object multiple times without having to specify the 8+ configuration options each time?", you could return it from a function:
def get_connection():
    return pymysql.connect(
        host='localhost',
        user='root',
        password='',
        db='runewage',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor)

connection = get_connection()
try:
    with connection.cursor() as cursor:
        #etc
 
6:30 PM
@PM2Ring OK. Agreed. Glad I ran it by someone else before I went crazy. :)
thanks for the input
 
No worries
 
And so, i put this is connection.py, and in que.py i just do import connection.py ?
 
@MooingRawr Good.......good.....carry on.
 
@KristianHareland Pretty much. Although you'd do import connection rather than import connection.py
Possibly there's also a way to set some of those configuration options in an external configuration file. Generally one should avoid putting sensitive credential information in a .py file
 
Yeah i guess
but if someone already have access to that file they are already in
its not callable from the web
but if you want to guide me to best practices i am all in for it
 
dyb
6:33 PM
@MooingRawr as far as i understand the example i quoted is a list comprehension and it works well with a list against list check. but i have a nested list.

`nestedlist = [['aXc','123','321','444'],['bbY','222','234','333'],['ccc','555','666','777']]`
`checkforthese = ['X','Y']`

i want to check if 'X' or 'Y' is in first element of each list inside the nestedlist using something like this: `[i for e in checkforthese for i in nestedlist if e in i]`.
oh. and output would be the nested list.
 
Did you try to do this without jumping to a comprehension first?
 
>>> nestedlist = [['aXc','123','321','444'],['bbY','222','234','333'],['ccc','555','666','777']]
>>> checkforthese = ['X','Y']
>>>
>>> all(any(c in sublist[0] for c in checkforthese) for sublist in nestedlist)
False
 
@idjaw Yeah, I agree that it would be a good idea to improve the title, and I like your suggestion.
 
Wait, I'm confused, why would the output of a yes/no question be a nested list
"is X or Y in the first element of each list?" only has a single True or False response
 
@PM2Ring OK. So I will go ahead and do that on that question. I think it will help bring it up easier in search results
My google searching never brought that question up
ok done
 
6:37 PM
x =  [['aXc','123','321','444'],['bbY','222','234','333'],['ccc','555','666','777']]
y = ["ccc",'bbY']

print([True if b[0] in y else False for b in x])
@dyb something like this? which returns [False,True,True]
 
I'm guessing the output he wants is [True, True, False], given his original values. "X" is in "aXc", "Y" is in "bbY", but neither X nor Y are in "ccc"
 
it was mentioned to print the sublist
so I assume it is "if it is in there -> print the sublist"
 
dyb
yes, i wanted the sublists
 
oh one sec
 
dyb
i will check on @MooingRawr example to make it work now
 
6:40 PM
5 mins ago, by idjaw
Did you try to do this without jumping to a comprehension first?
have you solved this without doing it the cute way yet?
a lot of times it helps to do it a line at a time, to realize what the solution is going to be. Then to see how you can fit it in to a comprehension (if that is even necessary)
 
@MooingRawr [True if b[0] in y else False for b in x] is an overly verbose way of writing [b[0] in y for b in x]
 
That it is PM but I wanted to lay out a well defined answer first before suggesting a compact one.. in hopes of learning/teaching. Generally if you see me answer any SO answer I generally want to give a longer but more clearer answer, then I compact it
 
I want to see their longer way of solving it.
 
dyb
oh sorry @idjaw somehow missed that... no i didn't. this is a good suggestion though.
 
"longer but clearer" is a fine ideal, but True if <condition> else False is arguably less clear than just <condition> on its own
 
6:44 PM
@dyb I'm being difficult because I want you to learn :)
do it step at a time. Figure out what you want exactly and write out as many lines as you need to, to solve it
figure out how it will work
get it working once in however method your brain figures it out :)
when you get something, come back. ping me
 
I think I do understand the impetus behind writing it that way, though. I think some people are gun-shy about putting expressions-that-evaluate-to-a-boolean in a context where a boolean is permitted but not explicitly expected.
And there is a perception that the boolean literals True and False are somehow more legitimate, so they're allowed
 
dyb
i understand :) i'm quite fixated on finding the fastest methods of doing this since i'm working with drawbot (drawbot.com) and it's really easy to overload it and freeze forever on my machine. somebody mentioned that this list comprehension is faster
 
@dyb I'd do something like this:
nestedlist = [['aXc','123','321','444'],['bbY','222','234','333'],['ccc','555','666','777']]
checkforthese = ['X','Y']
a = [seq for seq in nestedlist if any(u in seq[0] for u in checkforthese)]
print(a)
 
List comprehensions are not considerably faster than the equivalent long-form for loop.
 
i imagine they get unpacked to for-loops under the hood anyway
(or whatever they both resolve to)
 
6:48 PM
A more efficient way, especially if checkforthese has lots of strings, is to use sets:
checkforthese = {'X', 'Y'}
a = [seq for seq in nestedlist if checkforthese.intersection(seq[0])]
@Kevin Agreed. And if the list comp is a bit hard to read it's a Good Idea to write it with a traditional for loop instead.
 
Hello again @Kevin
Arent these two basically the same:
PHP: preg_match("/\<span title\=\'(.+?)\'/i", $webpage, $matches);
Python: data = re.search("/\<span title\=\'(.+?)\'/i", html)
 
@Marcus They do. The time saving comes from a special LIST_APPEND bytecode, which is more efficient than looking up the list.append method on each iteration and calling it (Python function / method calls are relatively slow).
 
@dyb Well faster is very debatable here. I mean, yeah sure, it is most likely going to outperform it to some degree....but not as much as you think where your exploded method will bring your machine to a halt
 
@Marcus Experimenting with dis, I'd expect list comps to have a little bit less overhead because the bytecode doesn't need to call append or load the iterating value in the Python environment. I assume something equivalent happens in the C environment, but it's magically faster because it's C.
Oh good, PM pre-agreed with me.
 
makes sense
 
6:54 PM
OTOH, list comps in Python 3 don't have quite the edge they had in Python 2 because there's a little bit more overhead: a Python 3 list comp has to create a new scope, the old Python 2 list comp ran in the scope of the surrounding code, for efficiency reasons. But a lot of people didn't like that, and got bitten when the counter var(s) in their list comps clobbered names in the surrounding code, since they expected those counters to be local to the list comp.
 
@KristianHareland Hmm, I can't say, because I don't know what preg_match does.
 
It matches my regular expression pattern
 
Note that gen exps and the other comprehensions have always created their own scope.
 
and puts matches into $matches
 
I expect Python's regex engine to work near-identically to any other mainstream language's regex engine.
 
6:55 PM
$webpage is pure html
ok, let me share you a gist eh ?
 
'Kay.
 
@dyb using @PM2Ring approach of intersection. His implementation provides the following: 2.740125388998422, while exploding his implementation in to a classic for loop -> 2.5442982719978318
it's not different to the point of mind shattering.
 
dyb
@PM2Ring this works great already and it is almost instant on a list of 40k lists against 100 checks. i will investigate sets later. thank you for the insightful and encouraging answers! makes me want to spend more time just fiddling with different approaches on this single problem ^^ sorry, don't know how to express the gratitude from your approach. this place is study heaven!
@idjaw so the for loop is actually faster in this case?
 
@KristianHareland If you're using /i in the pattern to indicate that the regex should be case-insensitive, that's not how that flag is indicated in Python.
 
6:59 PM
ahh
 
@dyb oddly enough.....I expected the comprehension to be faster and by about the same margin...but not the other way around
 
and yes i am using it for that
 
dyb
@idjaw perhaps it's related to the size of the list
 
Try data = re.search("\<span title\=\'(.+?)\'", html, flags=re.IGNORECASE)
 
>>> def bar():
...  nestedlist = [['aXc','123','321','444'],['bbY','222','234','333'],['ccc','555','666','777']]
...  checkforthese = {'X', 'Y'}
...  a = []
...  for seq in nestedlist:
...   if checkforthese.intersection(seq[0]):
...    a.append(seq)
...  return a
 

« first day (2476 days earlier)      last day (2471 days later) »