« first day (3611 days earlier)      last day (1336 days later) » 

3:02 AM
Not entirely a python question, but when learning a new language how do you not let python ideals mix up? started with python (only language I know) and now when learning a new language I always compare that with python (eg: itertools does this better and shorter)and I feel like I am not picking up what the new language has to offer, how do actual devs deal with this? Should I just learn the language and then look out to syntactic sugars and concepts?
 
3:12 AM
Hello
 
 
2 hours later…
5:07 AM
I would say a comparative approach to learn and ability to distinguish between what every language has to offer under the hood, is a valuable asset but it may not be beneficial when you tend to do that for every case.

The simplest approach i would advice to go with is - keep going with the language (it's natural for ya to compare between language specific approaches for a single problem). For eg. if you tend to learn Cpp after Python (i did the reverse actually), and u come across let's say splitting a string around a specific character, YOU WILL miss the .split('char') method from python.
 
5:36 AM
appreciate the suggestion, that is exactly what I felt like, I will try to use this
 
6:07 AM
:)
 
6:18 AM
@MisterMiyagi sorry for bothering ya, but did ya find any better approach for minimum unfairness sum instead of variance one?


I am actually planning to look up on solutions by other participants (there are about 4k+ successful submissions including all languages' coders). And also will let you know how they did.
 
Open question, what is the most common way to host a python web app? through a Linux server, dockers, or Heroku?
 
6:38 AM
@Kwsswart I'ma go with dockers but it's a matter of choices tbh
 
@PSSolanki Im in th process of learning each in turn to see which I prefer before deciding just curious in the actual industry which is most common
 
6:54 AM
@Kwsswart I would say Dockers, kubernetes, nginx, heroku...
 
Docker, ECS, Lamba, Kubernetes, Nginx
 
Hey all. I have a question that's not really appropriate for the site, since it's more opinion-based and/or recommendation. I need to send some documents. Some get sent via email as plain text using HTML, which is fine, but some *must* be sent as PDFs via fax. I can convert the source file to PDF, but I'm not sure how to send via fax. As unlikely as that may be, is anyone here aware of how to do this kind of thing?

I've seen some things online (e.g. Twilio, etc), but I'm trying to avoid those kinds of things. (Not interested in more accounts to manage, etc).
 
@pygeek Thanks man keen to learn more on all of these
 
7:15 AM
when running a vagrant server is it possible to access the /ssh/sshd_config file to disable root logins? or is this only on virtual servers
 
7:31 AM
@python_learner If you feel that a language is lacking in tooling, that's a good motivation to build these tools yourself. Great to get some feeling for doing useful things.
You'll probably trash most of it when you later find out there is a canonical way to do what you want, but the experience is worth it.
 
Exactly. That's why I love naive approaches more than the direct methods to carry out tasks.
 
Indeed. There's a good chance that whatever other language you pick up is lower-level and/or stricter than Python. Building something familiar with this unfamiliar challenge is a good way to get a feel for differences.
@PSSolanki Sorry, didn't ponder it any more.
Looking at other solutions seems like a good idea, though.
@code_dredd Unless you are looking for automation, I can really recommend using an online Fax service. We're still nibbling away at the 10€ we put into an account years ago with a few faxes per year.
 
@MisterMiyagi Yeah, guess i'll just see what those successful submissions are after fusion and kevin are done with their 'researches'.
 
@code_dredd github.com/interfax/interfax-python might offer a solution, and it was last updated within a year.
 
@Kwsswart Sorry, not familiar with how Windows manages those things.
 
7:44 AM
@MisterMiyagi No problem it seems that I have no choice as vagrant and hypervisor cannot run at the same time
@MisterMiyagi are you familiar with Vagrant?
 
A bit, but again, I am not familiar with Windows. If killing a hypervisor on Windows would be comparable to Linux, you would not be asking such question. You'd know.
 
@MisterMiyagi Fair enough I am currently in the situation where I have setup the server so far seems ok... However looking for the sshd_config file on the ubuntu server and cannot seem to locate it and am unsure as to whether it is due to being on a vagrant server on local machine or if i am just being silly and not knowing where to look.
 
Why python has many system calls than C++? it causes to speed of programme(considerable)?
 
@Kwsswart sshd_config normally lives in /etc/ssh, I believe. Does that help?
 
@Janith I'm sorry if i'm being silly, but i didn't get the question there.
 
7:54 AM
@Janith Are you asking why Python programs make more system calls that C++ programs? If so, where does that information come from?
 
yeah
I tracked using strace
 
@holdenweb Actually that helps perfectly thank you
 
@Janith Over all possible programs, or just one?
I think you'd need a large sample to draw that conclusion ...
@Kwsswart Watermelon
 
I tried same program in python and C++ by using socket.... but,python makes many systemcalls than C++
 
The Python interpreter alone will do tons of system calls just from loading everything on start up.
It's generally difficult to compare "the same program" because there usually is no such thing. Many things the compiler does AOT the interpreter has to do at runtime.
 
7:57 AM
There is, I would argue, no such thing as "the same program" in two different languages, only "programs that do the same thing".
 
it causes to speed of program (considerable)?
 
unless your program is trivial, it should be negligible.
 
That is the script I checked....
#!/usr/bin/env python3
import socket
import struct

s=socket.socket(socket.PF_PACKET,socket.SOCK_RAW)
s.bind(("eth0",8))
x=struct.pack("4I",4194304,64,2048,131072)
s.setsockopt(263,10,0)
s.setsockopt(263,5,x)
in python
 
A noop Python program will be considerably slower than a noop C++ program, for example.
@Janith That doesn't even seem to do anything. So, see above.
 
Ring buffers
 
7:58 AM
But one would, surely, expect a high-level language to make more demands of its environment. And Python interpreter startup is a significant load, which as @MisterMiyagi reminds us will contain many system calls.
That's a very small program to be drawing general conclusions from ...
 
yeah
 
What have ring buffers got to do with anything?
 
I must state this chat group is the most helpful one on stack overflow all others are very dry
 
@Janith It still does not appear to do anything with these.
 
@holdenweb It is useful for packet capturing like Zero-copy
@MisterMiyagi not appear anything ...but ,strace will show systemcalls
 
8:01 AM
Ugh.
It doesn't do anything useful with these. Of course it does something by nature of being an executing program.
 
@Janith But you drop it into the conversation with no context. We need to undertand before we can help
 
I mean only an example ...
 
As an example for a trivial program, it shows that Python is slower for trivial programs, yes.
 
@MisterMiyagi I think using mmap,it can be mapped .(no need to call recv())
 
@Kwsswart The Python community put a lot of early work into trying to maintain some sort of spirit of mutual aid and discovery. In my case this was a reaction against the rabid flaming that used to happen on comp.lang.perl
 
8:04 AM
@Janith I'm not following. Of course a program starting with this can do something useful. A program being just this does not seem to do anything useful.
 
It is like zero-copying....
Same buffer can be accessed in userspace and kernel space
 
@Janith Perhaps you should focus on getting something - anything - working before you start worrying too much about efficiency? Old wisdom from Don Knuth
 
It is just an idea.... I think people don't use python frequently for system programming because of that
 
Consider that there is no question that Python is slower than C++ – or practically all other common languages. So explicitly mentioning that Python is slower for task X automatically raises the question why it is significant that Python is slower for task X.
The usual answers are a) it is not significant and b) Python is not suitable at all.
 
Speed depend on what?
system calls?
 
8:09 AM
Also, I'd advise against statements like s.setsockopt(263,10,0) - this fails to explain the intent of your code, an issue that is normally handled by the use of so-called manifest constants - named values whose names give insight into the intent.
 
@Janith Usually walltime and CPUtime.
 
@holdenweb I do believe it is a better principle as in the end everyone learns together
 
A more typical use would be self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - the socket module provides the constants you need, and name names give you a lot more idea of what's (supposed to be) going on.
 
I'm not familiar with using the number of system calls as a performance measure. They are mostly a result of program design.
 
@holdenweb 263 -SOL_PACKET, 10-PACKET_VERSION,0-TPACKET_V1
 
8:11 AM
@Kwsswart Me too, ergo: PyCon
@Janith The very fact that you had to tell me that reveals the weakness of your code, which should always endeavour to be self-explanatory - otherwise you get berks like me asking questions that need your time to answer. You pick techniques like that up as you mature in programming.
Often the person who needs to understand the code is you, returning to it after some time.
5
 
9:13 AM
@holdenweb which also ticks the "write code as if the next person having to maintain it is a raging psychopath who knows where you live" box
 
So far, my attempts to murder past me have failed. Not for lack of trying, mind.
 
@MisterMiyagi @holdenweb I am looking for automation and the interfax thing is an online service I had seen, but as I said with the twilio thing, I'm trying to avoid such things.
If I weren't looking for automation, I wouldn't be asking in a Python programming chat ;)
 
So you actually want to maintain your own fax modem? Presumably you are talking about low volumes? Best solution would be a printer with fax line. Most Brother and H-P printers will do that, but I'm not able to point to specific Python code to manage printing a PDF in your specific environment.
And you'd be surprised the things people ask here. "There's nobody in the JavaScript room, can anyone here help?" has been seen many times, I believe.
 
10:00 AM
lol, the JS comment. I have an HP printer that can fax, though I don't have a land line to use with it (yet, at least). I guess some things depend on whether I can or cannot get this to work before I incur in the expense of a land line, although if there's a way to avoid that, it'd be great lol --though it seems unlikely, since fax machines work on analog signals, so ... :/
 
10:32 AM
Hmm, this question seems unusual. I assume there's some simple explanation but it's not jumping out at me
aha, nm, view vs. copy. I can imagine being bitten by that :P
 
11:05 AM
I've been trying to see which rows of data are exactly the same between 2 dataframes. isin() doesn't do it because it does it per column if I to something like df.isin(df1) the same is true for df == df1
 
raf
11:37 AM
Hi, can you guys please check my code and tell me some suggestions to improve my code, especially the Country Name Checker function checkl() here: stackoverflow.com/a/63711039/7673979
or does there exist any dedicated module to handle my issue?
 
@Pherdindy Take a look at thispointer.com/….
 
@holdenweb Thanks i've been looking around some solutions in SO but can't seem to find it
 
Call me Captain Obvious - I just did a Google search for "pandas dataframes find equal rows" ...
 
11:53 AM
@raf As a start, do pd.read_html(us_url) once and process the result, instead of doing it again and again and throwing away most data.
 
@holdenweb I was thinking there was some kind of feature where I can compare 2 dataframes together and it will return some kind of boolean result
@holdenweb But I think this can work I just have to merge df and df1 and use the duplicated()
Didn't think of that
 
I'd also expect to see actual pandas methods being used, instead of converting everything to lists. That's usually very inefficient.
 
@raf There's the CodeReview site if you'd like your code to be scrutinised.
 
As a concrete suggestion, please take a look at PEP 8, and consider how your code is read by others.
For example, I have no idea what res_ind = [ele for ele in ind if(ele in T)] is supposed to express.
 
I was reading PEP8 the other day
functions are named like_this and variables are also toy_size?
except for constants which are all caps?
 
12:01 PM
If you de-duplicate the data frames before merging then the duplicates in the merged df are the rows df1 and df2 have in common. The non-duplicate rows can be attributed to their base dataframes by using deduplication against both df1 and df2. And df.duplicated convenientlty returns a Boolean series to let you select the identified elements.
 
classes are caps lock on the first letter of each word
I remember seeing some people write stuff in format like helloWorldGoodEvening
 
@Pherdindy We normally use the term "upper case" but yes. Search for "camel case" to understand the various conventions.
 
@holdenweb right I actually initialized a class to remove duplicates within runs since I simulate code a certain number of times
So I plan to compare runs from each other
When reading pep8
I don't see any camel case being used
is it okay to use camelCase for variables and this_way for functions? Or is it not the way people to it in standard?
oh right they call it also mixedCase I guess can do any of the stuff they listed
 
mixedCase usually isn't used in Python.
 
12:18 PM
Is there a way to pass a variable by reference in python?(any direct method) I know arrays always does it...
 
Python has neither pass-by-reference nor pass-by-value semantics. It is often called "pass-by-name" for those insisting on passing semantics.
You can just pass in a mutable object, such as a list, though.
 
list always does.... but,variables not(When I check id(var) inside a function and before passing it ,they are different )
 
what is the default colormap of matplotlib? rgb?
 
@Janith lists are not passed by reference either.
def reassign(smt):
    smt = [45]

test = [42]
reassign(test)
print(test)
You can mutate a list, e.g. smt.append(45) or smt[0] = 45, just like any other mutable type.
 
12:38 PM
yeah
but,I expected a solution like in C++......
 
I'm just trying to keep you from the false notion that Python passes "arrays" by reference. That's a rabbit hole leading straight down to madness.
 
something like two identical names are referenced to the same memory address
 
Names are completely distinct from memory in Python.
 
@MisterMiyagi Ok
 
What you are looking for is a container.
It might help to think of variables in C++ as containers ("memory containing values") in order to properly map them to Python semantics. That way, a Python container (e.g. a list) comes rather close in behaviour.
 
12:44 PM
morning cabbages, folks
 
@MisterMiyagi cool mostly going to code for myself but just might as well do it a little close to the standard if I can hah
 
@Pherdindy Sticking to coding standards is a huge win when you ask others for help, and likewise when you try to learn from others. I can really recommend it even if you do not plan to directly work with others.
 
@MisterMiyagi right going to read more on it soon
 
@Janith To what purpose did you imagine this "solution" would be put?
 
Just curiousity is there a python flask package that assists with developing a file upload, storage and downloading app similar to that for music streaming
 
12:56 PM
TIL: "increment in a loop" is considered a programming pattern. SO questions are educational after all.
 
Hello. I'm using Flask to create an API. My question is, using PUT request, is it possible to update only a specific value of the JSON or all the keys to be updated?
Because when I try to update only a specific key, I get "keyerror" because the rest of the keys are not presented
or all the keys have to be updated? **
 
That seems unrelated to PUT, or for that matter even to Flask and JSON.
JSON is a notation, if you update things and get KeyError it means you are working with dict objects.
Can you explain the core of what you are trying to do?
 
1:26 PM
Yes. I have an API in which I post a json object at first. So if I go to localhost/cars/car_1 the properties of that car will be displayed in JSON format.

If I want to update the properties of that car, I make a PUT request on .../cars/car_1
On my Flask app, when a put request is performed, I update each of the json object's one by one. But the json on the put request has to have all of the properties' keys. If any key is missing I get an error
I want to be able to update only one property only without getting that error
 
So write your code in such a way that it doesn't crash on missing keys?
 
I don't think I explained it well but weirdly enough writing the problem helped me to solve it
 
1:52 PM
@holdenweb what do you mean?
 
@John that is known as rubber duck debugging :)
 
@Pherdindy you already found it, didn't you?
I thought that was what df.compare() actually did
 
Are there applications in python using mathematical concepts like laplace transformation? Like image processing ?
 
@John that's an error in your application design. It's not possible to help you without seeing the code
 
@AndrasDeak lol, just looked it up. Didn't know it was a thing, thanks
 
2:00 PM
@roganjosh I did check it out but it had some weird headers that I was too lazy to try understand how it was structured it ended up having multiple columns with self and other columns
 
@roganjosh yes, just fixed it. But thank you :)
 
I'll proabably take another look
 
@Pherdindy not sure I understand what that means, but I'll nod sagely
 
It had additional self and other rows
So I have to probably mold the resulting frame to fit my needs
But i'll take a look at the examples still going to understand how to use it lol maybe it's what I need indeed
 
I'm a long way away from a laptop currently, so I'm not gonna be able to help other than suggesting you spend some time working through that method
 
2:07 PM
Thanks I was able to find another solution to it though but i'll still take a look at it since it might be shorter way
I also realized the order of the rows matter in compare()
The dataframes I need to compare are jumbled around and unable to really sort it to match
 
2:26 PM
has anyone used Google Cloud Platform? Are you familiar with the dashboard and general API/credential workflows? Is there a training document I could learn from?
 
raf
@MisterMiyagi I see. Okay! I am gonna try it. Thank you.
Oh, That's great. I didn't know about that site. Thank you.
Just now, I have asked it there: https://codereview.stackexchange.com/q/248918/230104
 
@Janith I was simply asking, if Python contained references, how you would expect to use them.
@inspectorG4dget I've used GCP (a couple of years ago now), but I didn't really need any complex credentials for what we were doing. What do you need to do?
 
2:42 PM
Oh, this is about the second time that I'm using GCP for anything (last time was for a personal project, so the stakes were lower). While I have no issues with "writing code" (I've been pythoning for over a decade now), it's non-trivial to get started with GCP because the ecosystem is not intuitive (for me, at least). I therefore wonder if there is a "welcome to GCP. Here's how you generally do things" document that I can learn from
 
3:13 PM
Not that I came across :-(
 
Cabbage guys
My project is using sqlalchemy , which obviously needs models.py which has to reflect the db schema. Which migration tool would you all suggest? alembic? or any other
django has spoiled me with its migration tool
 
@Anarach theres a nice one from the Flask Mega tutorial
flask-migrate
 
umm mine is not a web application
 
It doesn't "obviously" need models.py; that's just a convention. If this is Flask then use flask-migrate
 
may still work for just database migration
 
3:19 PM
@holdenweb may be
 
@Anarach then it's Alembic
 
@roganjosh if it doesnt need models , how would the code refer to tables?
 
You can name the file whatever you want
 
oh.. that yeah.
 
And the database models are not constrained to a single file
 
3:20 PM
noted.
 
Provided that your models inherit from a single Base, then you should be able to track all the changes
 
I just plan to have single file
but good to know
 
 
1 hour later…
4:24 PM
hi guys, i been working on an image viewer app but then im trying to do a formula for proportions like what if the image is too big vertically, then it would actually be shown below the screen, so i want to actually resize the image smaller so as to fit the screen, but does not want to distort the image, ive been trying to do the math but cudnt find it, any ideas?
literally the math for resizing image without distortion, aspect ratio?
BTW, am using tkinter
 
You need 2d interpolation, but you should probably use a dedicated image processing library
 
43
Q: Resize an image without distortion OpenCV

Tanmay BhatnagarI am using python 3 and latest version of openCV. I am trying to resize an image using the resize function provided but after resizing the image is very distorted. Code : import cv2 file = "/home/tanmay/Desktop/test_image.png" img = cv2.imread(file , 0) print(img.shape) cv2.imshow('img' , img) k...

 
i use PIL right now
 
I bet PIL can do that too
 
do you have an example? or any formula to be followed?
@AshwinPhadke thanks for the ideaa!!
 
4:30 PM
Dynamically? I'd have suspected the resizing was passed to the frame that the image is displayed in
 
I have this directory structure pastebin.com/bSWyRTtc , now maincode1.py imports maincode2.py but when I run the pip wheel and import maincode1.py it says no module named maincode2.py. Do i need to create a seperate folder now for maincode2.py. Also my init.py only includes maincode1.py
 
@roganjosh doesnt have to be dynamic, just so that the image doesnt overflow the screen
 
Solved, had to import from main directory, thanks all for the help.
 
@AshwinPhadke yes the link did help alot, thankss
 
@CoolCloud great.
 
4:40 PM
it creates like a thick black borders around the image, any idea why?
 
@CoolCloud I suspect that is a problem to be solved in tkinter, not an image library
Alas, I don't know tkinter
 
actually this image is what PIL directly saved, no tkinter used in the process of displaying that
 
@CoolCloud You can explicitly try to set padding to zero and check, I believe it is filling up space by automatically adding padding, verify and do.
 
mac?
 
windows
@AshwinPhadke where does the pad setting work? im new to PIL and python
 
4:47 PM
@CoolCloud From the same link of jdhao I sent , it mentions as "The PIL ImageOps module has a expand() function that will add borders to the 4 side of an image. We need to calculate the padding length in 4 side of the resized image before applying this method."
 
@AshwinPhadke i used the first method though
 
@CoolCloud That;s why i said, try explicitly setting padding to zero, I use opencv so don't know much about PIL but sure that you will find it, also adding padding formula is already given there you just need to get it to zero to verify.
 
well, yes the padding did work, thanks alot!!
still the vertical image overflows the screen by a bit
do you know some sizes that would fit the screen?
 
@CoolCloud good.
@CoolCloud not all sizes fit the screen you have to be dynamic about it depending on the screen size otherwise you would be coding a lot of if's for all available screen sizes, do that using tkinter maybe.
 
yes, i can get the screen size using tkinter, then depending on the screen size, what all do you think might fit
 
4:56 PM
How do I include folders in MANIFEST.in to package? anyone any ideas?
 
im on a 1080 screen, this image is still not fitting
 
You could distort it to fit
 
@CoolCloud that's pixels , screen size is in inches.
 
Is that what you want?
 
its like you see, if i open the image using windows image viewer
then the image does not overflow the screen right?
it shows the correctly sized image
 
4:58 PM
It is correctly sized. That's what we're looking at
 
actually it is, but it overflows my screen
 
That is because windows fits it's image to the screen, that's what I said you need to fit the image to the screen based on screen size or define the window size based on the current resolution of the screen
 
@AshwinPhadke oh okay i see, do you have some way i could use? or any links to help on that
 
@CoolCloud let google be your friend.
 
@AshwinPhadke actually ye, im googling, nothing seems relevant. Maybe the concept still seems a bit unclear to me, sorry
like does the image fit to screen depend on screen size(inches) or screen resolution(pixels) ?
 
5:11 PM
@CoolCloud in OpenCV you can resize the output image window for the image.
 
Thanks alot of the help!
 
5:42 PM
@CoolCloud If the aspect ratio of your screen is not the same as that of the image you have choices: either distort the image by scaling differently in each axis, or scale so that either height or width fits the screen (depending on whether the image is taller or wider respectively) and fill the remaining area with a border.
 
5:58 PM
are constraints required to be added in models.py? in sqlalchemy?
 
when recreating a database from sqlite to mysql using the flask-migrate within the server I am receiving this monster of an error message: dpaste.com/6RJXQ4946
which i believe is indicating that the database is there, but i have not created it yet due to changing over via the mega tutorials instructions
any idea if i missed something?
 
6:45 PM
@Anarach again, please stop using models.py as though is means something
 
@roganjosh Ah my bad. also after a fair bit of googling , stumbled on a superb blog
 
@Kwsswart you done broke it :P hmm
I could kinda understand if it hadn't worked in sqlite in the first place. This is literally just a re-deployment to mysql?
 
7:16 PM
@Anarach apologies, I'm on a phone and I crossed wires because SQLA seems to be the hot topic. What are you trying to do?
 
@roganjosh umm , I got mostly what I want from googling around but I do have a fundamental question, how is postgres allowing to add a non primary key from one table as foreign key in another tabkle
I thought foreign keys had to be primary keys or need to be unique
 
Why shouldn't a database allow that? At best it will see that the key exists
Foreign keys don't have to be integers
 
hmmm
 
It's not an invite to make things more complicated :)
 
7:33 PM
Ha ha Got understood
:-P
 
user12867493
My Python file just dissapeared in my folder, how can I recover it?
 
user12867493
It was 200 lines :/
 
wow
 
user12867493
Any ideas where it may be stored still? I'm on Mac...
 
@Daniil you could ask that of any file, no?
 
7:35 PM
"just disappeared " is little vague
 
It's either in the recycle bin or gone
 
user12867493
@Anarach I was in Finder viewing a folder, opened the program, it closed and disappeared from the folder.
 
What does the script do? Does it delete files? Move files?
 
@Daniil Not very familiar with mac but if the file is really important , you could try reloading a checkpoint in the os
 
I'd try asking Mac-savvy people specifically
 
user12867493
7:38 PM
It doesn't do any file operations apart from dumping to a couple of pickle files
 
user12867493
@Anarach It was my exam coursework as well
 
High stakes
 
I know this won't help you now but I've started using git for everything important
Might help in the future
 
@AndrasDeak t I Guess I will do that for my files
 
I mostly lose files when I accidentally redirect shell commands into an input file
 
user12867493
7:44 PM
I have recovered 50% of the code
 
user12867493
Turns out I pasted it into PEP8 checking software online, it's an old version but still
 
@Danii Do you use Timemachine?
 
user12867493
Yes but no backup made after I wrote the file.
 
Otherwise, if a script removed the file (os.remove, terminal rm, ...) the file is gone – it won't be moved to trash.
While it won't help you recover now, I'd highly recommend to use git and some institution or public git hosting service, e.g. gitlab or github.
 
8:50 PM
@Anarach Why would you want to refer to a row by something other than its primary key?
 
@holdenweb Yeah , Good Point, I going to have a word with the guy who made schema
 
@Daniil The normal mechanism would be to go to the Time Machine, but if you haven't been taking backups then your only hope is that maybe you dragged it into another folder.
In which case something like sudo find / -name filename might find it in its new location.
It's a lesson we all have to learn. I've learned it several times :P
 
9:18 PM
cbg all
I cannot seem to find whether or not Python guarantees that it will fall back to identity comparison when using in on a list
 
I was under the impression that in only uses equality comparison.
If you need identity comparison you'll do something like any(obj is search_obj for obj in list_of_objs)
Of course, barring some __eq__ implementation on the objs that does something like return self is other
 
"Fall back" sounds like what should be going on: if there's custom __eq__ it gets called, and __eq__ itself falls back on identity for object, right?
any(obj is search_obj for obj in list_of_objs) does not fall back: it runs forward
> User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
 
9:57 PM
This is where I got my crazy impression:
>>> class Int(int): pass
...
>>> i1 = Int(100)
>>> i2 = Int(100)
>>> i1 is i2
False
>>> i1 == i2
True
>>> i1 in (i2,)
True
>>> i1 in (100,)
True
I think the more relevant docs would be those describing __contains__, but they are ambiguous.
> Called to implement membership test operators. Should return true if item is in self, false otherwise.
If I wanted to test if the i1 object itself was really in a container, the default in would just do equality matching.
 
@PaulMcG but if you subbclass int you have int.__eq__ so there's no fallback to speak of?
perhaps we interpreted the question differently
Closing @Wayne as unclear
 
I guess I misread the question. (heh, kevin'd)
I know that in the past, equality matching by in has actually gotten in my way, when I really wanted identity matching.
 
Didn't you really need equality and type matching? Identity testing is susceptible to spooky implementation details
 
Even then, if I wanted to know if the i1 instance was in the tuple (i2,), in would erroneously tell me that it was.
 
250 hypothetical_in list_of_ints # False, or is it?
@PaulMcG then your use case was weird ;)
You're probably better off with an ExactList subclass
 
10:06 PM
When I want to do such identity-based testing, it is with my own objects, not those that might be interned by the implementation and do unpredictable stuff.
 
@PaulMcG I figured
 
Yes, subclass from list and override __contains__ using is instead of ==.
 
yup
Anyway, rhubarb
 
Then I can just do list = ExactList and all my lists will use identity testing!
 
Also [] = ExactList
 
10:08 PM
(New people: don't do this ^^ at home.)
 

« first day (3611 days earlier)      last day (1336 days later) »