« first day (4031 days earlier)      last day (903 days later) » 

1:26 AM
cbg
 
 
4 hours later…
5:01 AM
Hey people!
I wanted to format the output of MySQL query.. but I got to know that it is not possible to do so using MySQL
So I guess I have do it using Python..
This is the output of my query:
in The Heap™ – Consultancy ©® on The Stack Exchange Network Chat, 12 hours ago, by Random Person
+------+-----------------------+--------------+-------+
| Test | Subject               | Subject Code | Marks |
+------+-----------------------+--------------+-------+
| MT1  | Maths                 | 041          |    29 |
| MT1  | Physics               | 042          |    36 |
| MT1  | Chemistry             | 043          |    42 |
| MT1  | Informatics Practices | 065          |    46 |
| MT1  | English               | 301          |    38 |
| MT2  | Maths                 | 041          |    37 |
I want to format it like this:
in The Heap™ – Consultancy ©® on The Stack Exchange Network Chat, 12 hours ago, by Random Person
+------+-----------------------+--------------+-------+
| Test | Subject               | Subject Code | Marks |
+------+-----------------------+--------------+-------+
| MT1  | Maths                 | 041          |    29 |
|      | Physics               | 042          |    36 |
|      | Chemistry             | 043          |    42 |
|      | Informatics Practices | 065          |    46 |
|      | English               | 301          |    38 |
+------+-----------------------+--------------+-------+
Please check the transcript link to see the full output
 
 
2 hours later…
6:55 AM
@Dodge I don't use the USER command a lot, but it looks like the switch from root to the jupiter user might be the issue. what if you order the statements roughly like this? dpaste.com/66HEQVXL6
 
7:21 AM
question is it ok to ask the op to accept the question if they said it helped them? i.e. stackoverflow.com/questions/69722095/…
 
8:01 AM
@Kwsswart accepts yes if OP has a history of not accepting. Upvotes never.
@RandomPerson you really don't have to post those full oneboxed messages here. That's pure noise
 
hey guys, what is the alternative to this for i in futures: i.result() , if all I want is to know if an exception is raised, is the only way just to iterate over the futures? I do not want the return value
@Kwsswart accept the *answer :p
 
8:22 AM
@python_user Looks about right. You can also use concurrent.futures.wait with FIRST_EXCEPTION, or all(f.exception() is None for f in futures).
Ah, no, FIRST_EXCEPTION won't actually work.
 
looking at wait, it could be handy if it had a raise=True argument
so FIRST_COMPLETED is a string or is this some constant in the module?
 
8:37 AM
Apparently, both. concurrent.futures.FIRST_COMPLETED is just the string 'FIRST_COMPLETED'.
 
one obvious way to do it :D
 
@AndrasDeak Sorry. Should I use dpaste?
 
9:14 AM
@RandomPerson if you already posted the code elsewhere then no. Just instead of posting two chat message links that onebox to these huge ugly things, post the two links in the same message which will prevent oneboxing
 
@AndrasDeak 👍🏽
 
in general if you put anything else next to the link in a message, it will break oneboxing
@Kevin are you missing an evil/good twin? stackoverflow.com/users/11890564/pepper
 
Switzerland isn't in the evil/good business. Could be a neutral twin...
 
9:51 AM
Nothing to do with previous messages, just a cautionary word: Trying to wrap the folium library is nothing but pain. You have been warned.
 
there's a mediocre joke in there
 
It's one of those weird moments where I think it's easier just to use leaflet in JS. Maybe that's a joke in itself?
Wrapping a wrapper. It's just setting up the most irritating of pass-the-parcel party games
 
You thought it would be a walk in the park but the library foiled your plans
 
 
1 hour later…
11:05 AM
Does anyone know a recent (PEP 518'ish) guide or example project for packaging with Cython for performance? Trying to figure out whether it's reasonable effort to maintain the additional Cython meta-parts.
 
The only thing I can suggest is hdbscan which you actually helped me with in terms of installing python through brew. That shouts very loudly about PEP 517 otherwise (which I think is linked?)
 
Does "numpy" count as an example project? :P
 
11:52 AM
@roganjosh Looks much better than whatever else I could dig up. TY!
@AndrasDeak If I get a research team and five years, then yes. :P
 
You forgot about demanding tenure
But hey, it's your life, not mine :P
 
I work in science. Klingon promotion is easier than tenure. :P
 
Klingon progression might be easier than what I'm facing at work. Apparently I don't fit any box, so I have to create a new one to be able to progress
Qapla'! (maybe, but probably not)
 
12:11 PM
Kill 'em all!
Wait, no, that might be counterproductive...
 
It would leave me in charge, but I think it might also leave me with other issues
Klingon society is very complicated
 
How do I format this to this in Python? (Please check the full code in the message.)
 
How is this different to this post earlier?
 
Different formatting. 🥁
 
The room has a memory, and a transcript, so posting another time is likely to rile people up (or maybe that's just me). There is no out of the box solution for this
I already told you how to put it into a dataframe, so look into the ways that can be displayed
 
12:24 PM
Ok roganjosh. I see that you are a room owner. Please delete my recent message.
 
Room Owners can't delete messages. We can only move them.
 
I guess there's a room to dump messages. You can move my message to that.
 
Typical British humour :p
 
Boaty McBoatface is a national treasure and don't you dare say otherwise :P
 
Nice
 
12:28 PM
My car is Mr Gassypants, in honour of Mr Splashypants, and nobody even questions it in general conversation anymore
 
@MisterMiyagi improved(!) formatting
 
morning cabbages, folks
 
@JonClements Good thing my mic is muted in conference calls. 🤣
 
12:45 PM
I want one of those 50p's!
 
BTW, is this a better code: dpaste.com/674ZDGM2Y (to prevent SQL injection)?
 
Have you verified that the query works on students other than #1?
To answer the question, it is technically safe from sql injection
Much in the way that a house with no doors or windows is safe from burglars
 
@Kevin yup. It does.
@Kevin yay!
@Kevin what do you mean? Can you please elaborate?
 
Your query contains WHERE roll_no=1, so it will fetch the results of student 1, no matter what number the user inputs.
 
@RandomPerson did you make a mistake copying the snippet over? your query says WHERE roll_no=1
oops, kevind
 
12:55 PM
Since the contents of inp have no influence on the query at all, a bad guy can't use it to perform sql injection, no matter how clever they are
 
The code doesn't even make use of the user input
 
Today I'm working with trees. I have a function that takes two nodes ancestor and descendant, and returns the single node that satisfies n in ancestor.children and n in descendant.ancestors. In other words, if ancestor is the great-times-Xth grandparent, then the return value is the great-times-(X-1)th grandparent.
I have spent more time trying to think of a good name for the function, than actually writing it. getNotSoGreatAncestor?
getAncestorOneLevelBelowThisOne
getChildOfAncestorAsLongAsThatChildIsAlsoAnAncestor
 
Yam, they are killing a wordpress blog I've been using to get updates about something, replaced by a twitter feed. My feed reader can't handle twitter feeds and twitter doesn't expose an rss feed.
the internet sucks
 
1:10 PM
Yes
Similarly I've been trying to programmatically fetch a list of youtube videos for a given channel and time frame, with little headway. I'm 85% sure that youtube-dl can get this information, but I haven't figured out the correct combination of flags.
I don't even want the video data, just the urls*. This is like, piracy lite.
(*and maybe some metadata like title and thumbnail image url, but beggars can't be choosers)
This is a violation of my mental model of a just world, where illegal things should be hard, and TOS violations that don't harm anyone should be easy
 
@AndrasDeak I hear webscraping is the newest rage. Who needs APIs, amirite?
 
@MisterMiyagi although a not insignificant amount of people for some reason call it "webscrapping"
 
@JonClements Wishful thinking, I assume.
 
"APIs are dumb. We're pouring millions of dollars into keeping our users inside our walled garden, and you want us to drill holes into it so people can reach in and pluck apples?"
Most websites don't even want to be accessible via a web browser, let alone an API. Citation: the dozen "download our app for a superior experience!" popups you encounter during a typical 15 minute mobile browsing session
 
1:36 PM
@Kevin oh shit. Sorry. Didn't notice that.
 
I know, that's why I suggested that you test it with other users, so you would notice it.
 
I tried with other roll number.. name of student changed.. but marks did not change.. so I thought everything went smooth 😅
I tried this:
marks_query = ("SELECT exam.test Test, subject.name Subject, exam.sub_code 'Subject Code', exam.marks Marks FROM exam INNER JOIN subject ON exam.sub_code = subject.sub_code WHERE roll_no=1=%s ORDER BY exam.test,exam.sub_code;")

db_cursor.execute(marks_query, inp)
but I got error :(
 
Incidentally, x = ("some string") has identical behavior to x = "some string". This is true of all kinds of expressions actually.
 
@Kevin So should change roll_no=1=%s to roll_no=1=(%s)?
 
Sorry, I don't know. The contents of that string should adhere to the syntax of your DB engine. I'm not familiar with that syntax.
I'm basically just suggesting that you delete the parentheses from the marks_query = (...) line. It won't solve your problem, but it will be stylistically nicer
(subjectively)
 
1:52 PM
@RandomPerson please avoid using expletives here
 
@AndrasDeak ok. Sorry. Shall I flag it for mod such that they can delete the message which contains expletive?
 
No
If I wanted a flag I'd have raised one myself
 
I see that the example given, select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s", does not put parentheses on the left of its percent sign. Therefore, I don't think you should change your query to use roll_no=1=(%s).
Nor do I think roll_no=1=%(s) would be helpful, nor roll_no=1=%()s. It seems like parentheses are only used for named parameters, and you aren't using named parameters, and don't need them
 
@RandomPerson First, this is totally unmaintainable if that's your code, and second, you haven't given the actual error
 
2:01 PM
ProgrammingError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s ORDER BY exam.test,exam.sub_code' at line 1
 
In the future, you don't need to say "I get an error" and then wait until we say "what's the error?" before you tell us the error. You can just say "I get an error: <put the error here>"
 
So the query is:
marks_query = """
    SELECT
        exam.test Test,
        subject.name Subject,
        exam.sub_code 'Subject Code',
        exam.marks Marks
    FROM exam
    INNER JOIN subject ON exam.sub_code = subject.sub_code
    WHERE roll_no=1=%s
    ORDER BY exam.test,exam.sub_code;
    """
That gives us a start on understanding this
 
Now that things are lined up a bit, WHERE roll_no=1=%s looks odd to me. What's the =1 for?
 
roll_no=1=%s?
Kevin'd again :/
 
I feel like I should have noticed this during one of the three times that I pasted that exact segment
I wasn't being coy or anything, just unobservant
 
2:06 PM
Ha, I'm happy to give you this one :P
All the aliasing makes no sense, either
 
@Kevin I did notice it
 
@Kevin sorry. that was a mistake.
 
@MisterMiyagi I'm seriously considering doing that myself
 
Well, is it a mistake that explains this unknown error, or not?
 
I changed it to roll_no=%s and I still have an error. ProgrammingError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s ORDER BY exam.test,exam.sub_code' at line 1
 
2:10 PM
Nothing wrong with mistakes, I make a dozen a day. More, if I'm being productive.
 
Are single quotes valid SQL?
 
@AndrasDeak yeah
 
I don't think it even needs to be quoted in MySQL
 
I guess what's left is an MCVE
 
Can you please post the actual code, noting how I formatted the query, @RandomPerson?
 
2:11 PM
In Oracle, apostrophes are the only valid quote mark.
 
We have to be able to actually read it
 
I know we're not using Oracle here, but I want to complain about Oracle
 
Complain away :P
 
It's bad
 
How bad? like > < this bad?
 
2:13 PM
So I'm wondering how hard it will be to set up a service on localhost that gets hit by my feed reader, prompting a scrape/API request from twitter, figuring out what's new
 
All my whitespace got stripped :'(
 
(exactly the kind of fun times I don't have time for)
 
I suspect localhost RSS would be easy in the broad design, but difficult in the fiddly bits
Configuring your web server to respond to non-HTTP requests, that kind of thing. Lots of toggling of check boxes four menus deep.
On second thought, I have no idea if RSS requests look any different from a normal HTTP request. But even with that fiddly bit out of the way, there are surely 999 more
 
@AndrasDeak twitter has as streaming api - you can use that to pick up keywords/hashtag/at matches and then convert it to an RSS feed :)
you might be lucky and there's probably even some zapier stuff you could use as is
 
@Arne Thanks for the follow up. That probably would have worked. We ended up solving the problem after we realized that a persistent storage volume that we use within our ecosystem was being mounted over the directory where we were copying to in the container, hence stuff just disappearing.
 
2:23 PM
Incidentally, my userscripts & trees project has come to an end, culminating in a script that removes the "sign up" overlay from Twitter.
I'm not terribly fond of the callback pyramid at the bottom, but I haven't got the spiritual strength to figure out promises and futures in JS
 
@AndrasDeak umm... yeah... zapier.com/apps/twitter/integrations and then search for RSS - seems there's plenty of options there
 
@Kevin Nice!
 
Thanks. I had to zap quite a few fiddly bits to get to v1.0.
 
@JonClements it wants me to sign up. There's already rss.app that would presumably let me sign up for an rss feed. But signing up for a random service just so I can get a yamming RSS feed is where I draw the line :P Thanks though.
 
Signing up for services is for mere mortals who can't customize their own web server
I don't want Internet of Things, I want Airgapped LAN of Things
 
2:31 PM
@Kevin I assume there's a reason why there's an anonymous function that just gets called, rather than just putting the contents in the same place (and that the reason is "JS")
probably not technically an anonymous function because I seem to recall these to have => inside
 
Well, the script begins to execute before Twitter's scripts finish dynamically populating the page content. So I can't just say "look for these two buttons, which are surely already present, and call prune(a,b) with them". And JS doesn't like it if you say "sleep this thread* until these two buttons exist, then call prune(a,b) with them" because it thinks the script is hanging
 
Nameless named function?
 
So I have to have some kind of asynchronous context, and function(){} is an easy way to make one of those, so that's what I used
 
Ah, there it is. "JS". Thanks.
 
I considered => syntax, but I couldn't remember the exact way to write it without looking it up, and that's a red flag that I'm approaching "too clever to debug" territory
 
That territory is much larger for JS than the other languages I've used. I don't necessarily blame JS for that, but...
 
Ah, I see, the function just defines callbacks and then registers them
 
Yeah
 
I thought the syntax was just (args) => {body} but even if that's the case there are probably subtle(?) differences between that and fulll function syntax
 
Possibly there is a way to tell the engine that your sleeping script is not hanging. I didn't look very hard for a solution there
I recall (args) => {body} behaving in a way I found surprising, when I was trying to do something tricky with the arguments. But I'm not doing anything tricky here, so I'd expect them to work as well as my function(){}s
 
2:40 PM
that callback inside a callback is a bit dizzying
@Kevin I know there are some wonky binding rules
 
JS was all about nested callback pyramids back in the day. A lot of people used them, and a lot of people hated them. There are more alternatives now, all of which I didn't bother looking up
 
to be fair anything can be dizzying for me because I don't know any JS
 
I try to adhere to a language-agnostic design, since that protects you from most of the language's WTFs
But I allow myself anonymous-functions-as-expressions as a treat, even though it's very non-language-agnostic
@RandomPerson Does anything change if you delete the semicolon from the query?
 
3:20 PM
@RandomPerson I don't get it? What's your question now?
 
FWIW, the query works perfectly in sqlite, if you change the parameter syntax from %s to ?. MCVE
I doubt that using "?" will make it work for MySQL though, so the mystery persists
 
Hmmm, I didn't get that image when I first launched the link. I'm going to blame the cache
what is inp here?
 
Going by previous code snippets, it's an integer, ostensibly matching a valid student id
If that was a rhetorical question meant to highlight the fact that the code is not an MCVE since it refers to variables that weren't declared, then ignore me
 
No, I'm strenuously trying to find the error in their code, and I don't think I can
 
Now that I've reverse-engineered a functioning equivalent, my money is on "there's a problem in the code that we haven't seen"
Something like "Oops, I just noticed that I'm actually executing WHERE roll_no=%s && grade > 70. I didn't mention the second condition because it didn't seem important"
If inp is an int, then db_cursor.execute(marks_query, inp) should probably be db_cursor.execute(marks_query, (inp,)). But I doubt that's the cause of the syntax error. Sqlite validates the statement's syntax before it validates the type of parameters, and MySql probably does too
 
3:37 PM
Anyone want to demand a real MCVE? No? OK.
We've spent way more time guessing what they might have done than actually solving their problem
And it's not like this is their first round of help here either
 
what do we want?
MCVE!
when do we want it?
before we expose the XY problem
before we try to be psychic
...
 
Normally I'm pretty lax in demanding an MCVE for database problems, since supplying all the necessary setup statements can be a lot of work. But for this specific problem, I did it in five minutes without access to the specifications, so maybe I should rethink that policy.
 
@Kevin You are right! changing db_cursor.execute(marks_query, inp) to db_cursor.execute(marks_query, (inp,)) fixed the issue! Thanks a lot! <3
 
Well, I said that wouldn't fix the issue, so strictly speaking I'm the opposite of right
 
but it really fixed the issue..
 
3:42 PM
In fact I suspect that it didn't fix the issue, because it would be really weird for MySql to raise a syntax error for a problem that has nothing to do with the query's syntax. More likely you inadvertently fixed the issue while experimenting, but didn't notice until you incorporated my additional suggestion
Anyway. If the problem is solved, that's a good thing
Even if there is some contention about how we got there, exactly :-P
 
@Kevin so we must blame MySQL now. 😂
 
even when Kevin doesn't, Kevin Kevins
 
I love blaming the SQL engine for my problems. I do it often and with enthusiasm. But this one doesn't feel like a slam dunk
 
BTW, back to the original question, is the code safe from SQL injection? dpaste.com/CXPZXYLFT
 
Oh good lord, was that the actual issue all along?
 
3:48 PM
Yes, it's finally safely parameterized
 
@Kevin yay!
 
Ugh. Twice in one week I've missed the tiny errors
 
roganjosh, you mean errors in my code? or something else?
 
It seems strange to me that you didn't share the complete code until after we guessed the solution to the problem. In the future, share the complete code immediately after we ask any question that includes the letters "MCVE"
 
Yes, errors in your code, and also a reference to when I linked people to a question that ended up being a typo
 
3:50 PM
Of course, even the complete code here isn't an MCVE, because it doesn't include the sql statements necessary to create and populate the tables, but it's way better than two isolated lines of code
 
I don't believe that MySQl actually gives the error you showed when it tried to unpack characters into a parametrised query, but I'll take your word for it @RandomPerson
 
@Kevin Everytime I share full code, people become upset and say me to trim the code and request for MCVE. I try to give a good MCVE but I fail to do so :(
@roganjosh hmm. ok.
 
I can't speak for anyone else, but, I hereby promise to never become upset if someone's Complete Verifiable Example is unusually long
 
OK Kevin! Will never upset you :)
 
@RandomPerson Actually, I think you did ok here in terms of reducing the code, but I don't think it catches the actual problem
 
3:54 PM
ok.
 
I might say "thanks, but it's a bit long. Can you trim it?", but I won't get mad or consider it a mark against the asker
 
OK Kevin :)
My only concern is this: Warning: QtConsole does not support password mode, the text you type will be visible.
 
Lol
What does that have to do with python or any of the previous conversation?
 
@roganjosh That ties into my "you fixed the issue but didn't notice" theory. Perhaps Random fixed the syntax error, and ran his code, and saw that it was still printing a stack trace instead of his desired output. He may have overlooked that the error message changed from "syntax error in query" to "expected tuple, got int". Then when he incorporated my suggestion, it fixed the latter error.
 
@RandomPerson In most of the examples I see online, the password of the database user is mentioned in the Python code itself 🤦🏽‍♂️
 
3:57 PM
@RandomPerson So when the user types in his password, it will be plainly visible on the screen. If you want the console to get the user input invisibly, then try using a console other than QtConsole. Windows' regular command prompt supports invisible getpass, for example.
 
@roganjosh It's related to my program. I am running my program in spyder. To establish a connection with MySQL database, I use getpass.
 
I see that stackoverflow.com/questions/47213310/… has some other workarounds
 
I'm gonna just back out. I don't think I can follow this one
 
@Kevin yeah.. I tried this. the problem is the command prompt closes immediately after the code execution completes.
@roganjosh ok.
 
That makes it even more secure! (25% serious)
There's always the good ol' input("Program complete. Press Enter to exit.")
 
4:03 PM
lol.. I think they can press any key (not just Enter).
 
ugh
 
input("Program complete. Press any key to exit.")
 
4:47 PM
cbg everyone
 
I've read several times that SO is a toxic place, but I think that in the Python tag people are actually friendly. Are the other tags different?
 
You haven't met me yet then :P
 
TBH I haven't seen you on the Python tag :P
 
I believe, most people here don't answer on daily basis. So IDK who you've met though. But you are lucky :p
 
4:57 PM
@DaniMesejo given that a large percentage of their impressive rep comes from python, I'm inclined to believe that it's more that your python questions are outside of their expertise.
 
@inspectorG4dget Thanks for replying, but I didn't get what you mean
 
@DaniMesejo CoolCloud's stackoverflow profile shows that they have significant activity on . So it's possible that the reason you haven't seen them on the tag is that your questions are very specific, and specifically outside of the types of questions they typically answer
 
Got it
 
@DaniMesejo SO can be pretty toxic towards people contributing bad content. If you feel that people react friendly to you, consider it a good sign.
 
Thanks @MisterMiyagi
 
6:09 PM
@Random You can just use the readchar module to capture keystrokes so the password doesn't appear on the screen. It works in both Windows and Linux.
array[ptr] = ord(readchar.readkey()) #array is a bytearray
 
The standard library getpass should provide "silent" input in a portable way.
 
6:26 PM
Hello everyone, I am using a driving simulator that records a participant driver's data. These data include speed and position of the driven car in the simulation. The data are stored in a .daq file. Using the socket library and driving simulator's API, I can receive the data in python console in real time. How can I store and send these data to another device? Do I need to create a desktop app to get the data? Thanks for your help in advance.
 
You can in principle redirect the data stream directly to another device, provided there is connectivity.
Is this TCP or UDP?
 
UDP
Could you please elaborate on how I can redirect the data stream to another device on the same network? Is that possible with socket? @MisterMiyagi
 
it is absolutely possible to do this with a socket
 
The simplest approach would be to directly tell the simulator API to send the data to the other device.
If it's hardwired to send to localhost, ssh, nc and similar tools allow you to forward the data to another machine.
If these are not available, rewrite the Python program that currently receives the data via a socket to use a second socket to send the data to the other device.
 
@RandomPerson I think I need to use TextTable. What do you all feel?
 
6:39 PM
@RandomPerson Aren't you just trying to remove duplicate entries from a CSV-like format? That should be doable using a simple generator.
 
@MisterMiyagi Thank you. I think I understand that. I need to figure out which ports to send the data to. This is more of a networking problem than python. Time to learn networking.
 
@MisterMiyagi more than that.. I would like to make my data look like a table..
 
Your data already is formatted as a table, isn't it?
 
@MisterMiyagi nope. I am using MySQL data in Python. I have used it as DataFrame.. but DataFrame does not have borders like table..
 
7:14 PM
@RandomPerson Strange. This one looks very much like a table to me.
 
@MisterMiyagi that was output of "query". in Python, it won't look like that.
 
Well, why not use that query and merely filter out the repetitions?
The MySQL table output format is well-defined; it should make for a stable starting point if what you want is a table format anyways.
 
@MisterMiyagi I don't think filter is the right word. What I was trying to do was something similar to merge cell in Excel.
@MisterMiyagi do you know how to print MySQL data as table in Python?
 
7:35 PM
I think we're just talking past each other.
 
7:53 PM
@MisterMiyagi :(
 
@RandomPerson if you'd like to disclose, why would you need that particular format you are trying to achieve ? i mean what is your end goal ?
 
@PIngu I am working on my project, i.e., student report card management.
Tables look good as output.
 
9:00 PM
@RandomPerson Umm and what was wrong with print(fetched_result)?
Also, I don't see why PrettyTable is not worth a look
 
9:30 PM
Good evening fellas! What is the best practice recommended when I need to check if a variable is already initialized, and initialize it if not, inside a class? This is what I'm using now but I have a linter telling me it's not good:
def _init_factor(self):
	try:
		factor = self.factor
	except AttributeError:
		if self.type == 1:
			self.factor = 3
		else:
			self.factor = 5
	return
"local variable 'factor' is assigned to but never used"
 
you can try
if not self.factor:
then you can assign factor with the type of the instance.
 
have just tried it @DenizKaplan, but it's returning an AttributeError
 
oh my bad. you can use hasattr(self, "factor")
 
oh nice! had an idea just now and it seems to work aswell:
try:
	self.factor = self.factor
except AttributeError:
	self.factor = 10
 
i'd use self.factor = self.factor if hasattr(self, "factor") else 10
 
9:45 PM
why? to double-check it? (I'm a beginner)
 
But it belongs to the data, how many times you'd expect to get AttributeError? If it is less then 50%, it is better to use try/catch blocks :)
 
lol I didn't even know this syntax was possible:
foo = 1
bar = 10 if foo == 1 else 20
how awesome
thanks mate :)
 
Anytime. You can always find better versions, more performant or more readable. Sometimes they might not be together, but generally you can find a pythonic version which is optimal to maintain your code.
 
yeah, it's not the first time someone in this channel helps me with stuff like this :D
it's funny I didn't know that syntax because I have been reading tutorials and working on my own code for more than 1 year now in python, and never seen it b4
 
it is called the ternary operator, generally, it is better to choose this for one-line solutions
there is a tuple version if you're interested to read
(false_value, true_value)[condition]
I found this as hard to read but works great :)
foo = 1
bar = (20, 10)[foo==1]
 
9:58 PM
Indeed that's very nice to learn. I was annoyed to use so many lines in cases where it's so simple a one-liner won't compromise readability at all.
just saved those 2 examples for future reference, thanks again pal :)
 
np, have a nice evening
 
you too :)
 

« first day (4031 days earlier)      last day (903 days later) »