« first day (2818 days earlier)      last day (2129 days later) » 
00:00 - 20:0020:00 - 00:00

12:01 AM
Thanks folks. Yeah, section 4.8.3, "Bytes and Bytearray Operations" seems to be the right place to look. Or if you happen to be looking at the old Python 3.1 documentation, go to 5.6.5, "Bytes and Byte Array Methods". I didn't quite understand the heirarchical structure before and got confused then section 5.6 introduced bytes and then the next section after it was String methods, but really that was a child section.
 
I have a cloud of points that could fit within a sphere. I wish to be able to rotate the sphere in any direction I choose.
 
@DavidGrayson just close the 3.1 docs, that's ancient
 
rotation would depend on user input.
 
@user1740058 for truly arbitrary rotations you probably need Euler angles or something equivalent
 
I was reading up on matrix transformation, but was not sure.
 
12:03 AM
either way you're looking at one or more matrix products: 3x3 matrices define the rotation of 3d points
if you're using numpy, and you should be using numpy, you have rotmat @ points assuming points has shape (3,n_points) (points @ rotmat.T if points is transposed)
 
And when looking at the modern documentation here, I think I got confused that the section immediately after "Bytes objects" was called "Bytearray Objects" and I have to actually skip forward past that section to find 4.8.3, "Bytes and Bytearray Operations"
 
@DavidGrayson FWIW you can ctrl+f and search for bytes.decode if that's specifically what you're looking for, and its first occurence will contain the link to its docs entry
 
Thanks, I'll give it a look.
 
no problem, good luck
 
12:36 AM
@DavidGrayson another one would be:
% python
Python 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help(bytes.decode)
 
 
6 hours later…
6:45 AM
Hi, I'm working on a project that use dict initializing extensively. I wanna put those dict in a separated module. I'm using class and __slots__ for modeling them. Is this good approach or should I just put them in a function?
 
@AliShahrivarian That question's a bit vague. Can you post a small amount of code to illustrate the concept? If you can do it in about a dozen lines or less you can post it directly in here, otherwise use an external site like dpaste or a Github gist.
 
ok @PM2Ring, I'll do it now. thanks
sorry I'm going to correct it now
@PM2Ring is it ok now?
 
7:15 AM
cbg
 
@AliShahrivarian It's a little less vague now, but your example code doesn't show the use of __slots__. So with what you've shown I think that using a simple function to create your dicts makes sense. I can't see the benefit of using a class for this task. And in Python we generally prefer to use functions and the built-in types (or standard library classes) unless there's an obvious benefit to using a custom class.
 
Thank you, I'm coming from 5 years experience in .Net environment, So I didn't know how to write models here and also want to remove duplicate codes from project.
I was going to use __slots__ to reduce memory usage (because there's a lot of key in that return dictionary and if I would to use classes I must make class efficient)
 
7:39 AM
@AliShahrivarian Sure, __slots__ in a class reduces the memory overhead compared to a class that doesn't use __slots__, and that can be very important if you're making lots of instances. But using a class instance to store data is less flexible than using a plain dict, eg the attribute names must be strings that are valid Python names.
OTOH, a class with __slots__ gives you the protection that only the attributes that you define can be used; with a dict the user can easily add other keys to the dict.
 
@AliShahrivarian If your dictionaries are well defined and you can use python3.7, using dataclass might make sense.
iirc, it doesn't copy constructor params either
 
@PM2Ring Yes, I know using class make restriction on storing data but the dict I'm returning data has a standard definition among our company teams. but I think using str names to access dict in a lot of places would make application less reliable.
@Arne thank you, I'm reading it and will back
 
@Arne Good thinking.
 
8:02 AM
FWIW, I just did a quick test using Python 3.6.0, 32 bit. sys.getsizeof is not recursive, it only tells you the size of the container, not the contents. So each key and value may also consume some space that the output below doesn't count. I say "may" because small integers are interned, and strings may be cached. As you can see, the class instance is quite a bit smaller than the dict.
import sys
class Q:
    __slots__ = ('a', 'b', 'c')
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def __repr__(self):
        return f'Q({self.a}, {self.b}, {self.c})'

q = Q(1, 2, 3)
d = {'a': 1, 'b': 2, 'c': 3}
print(q, sys.getsizeof(q), sys.getsizeof(Q))
print(d, sys.getsizeof(d))
#output
Q(1, 2, 3) 32 444
{'a': 1, 'b': 2, 'c': 3} 128
Each additional slot consumes 4 bytes (on a 32 bit system), I assume that's linear.
 
8:25 AM
@PM2Ring thank you, sorry for late reply, i'm at work
but class blueprint itself has more size than dict
 
8:51 AM
@Arne `dataclasses` are very helpful. Although I must check my project and design. I'm not going to change received `dict` and just going to build output `dict` once.
it's like received `dict` from another web service => build a `dict` from previous received `dict` => return new `dict`
I think with dataclasses python will reduce memory usage a lot.
you have control on everything
If I assign `my_dict` variable to `my_class` then do `del my_dict` will it reduce ram usage?
if not then I'll continue using dictionaries but will put them in a function instead of copying everywhere
 
@AliShahrivarian Very true. But hopefully you're making enough instances of each class that you can ignore the fixed cost of the class definition itself. FWIW, sys.getsizeof(dict) is 200 in Python 3.6, but twice as large in earlier versions. Of course, dict is a built-in, so it's a fixed cost as soon as you fire up the interpreter.
 
Hi..One quick question..Is there any pythonic way to check the variable value which is "undefined".
It would be really appreciated
 
if variable == "undefined":?
 
@Aran-Fey: is there any other way ?
 
Well, I'm not really sure what your question is. But if that code answers your question then no, there's no other way.
 
9:04 AM
@AliShahrivarian If you save a copy of a dict to an instance attribute and then destroy the original, the RAM used by the original dict object will get recycled.
 
except for if "undefined" == variable: and if variable == "un" + "defined": and other pointless variations
 
@user2224250 I guess you want something equivalent to JavaScript. Python doesn't work like that. If you attempt to access a variable that isn't defined in the current scope NameError is raised. You can catch that with try:... except NameError
 
Maybe the question is "How do I check if a variable exists"?
 
@Aran-Fey I know the pythonic way to check whether variable exists or not...My questions is, what is the best way to check if the variable value is "undefined". Infact, I see only == operator..And I agree with @PM2Ring Python doesnt work like JS
 
@user2224250 You may find this article helpful: Facts and myths about Python names and values @AliShahrivarian you may also find it interesting, if you haven't seen it before.
 
9:10 AM
@AliShahrivarian it's usually best to let python handle RAM and not to call del by hand. If you delete/mutate a dictionary after feeding it into a dataclass, the dataclass will experience the same changes.
 
Is it just me or does reading "Mutable Presto-Chango" make anyone else hungry? Makes me think of pasta for some reason
 
@user2224250 If your question is literally «How can I test if the value of a variable is the string "undefined"» then something like if my_variable == "undefined": is the way to go.
 
@Arne , @PM2Ring , thank you
 
@Aran-Fey Not particularly, but I think I get where you're coming from. :)
 
e.g.
from dataclasses import dataclass

>>> @dataclass
>>> class Container:
>>>      my_var: str

>>> my_dict = {'my_var': ['foo']}
>>> my_data = Container(**my_dict)
>>> my_dict['my_var'][0] = 'bar'
>>> print(my_data)
Container(my_var=['bar'])
 
9:13 AM
It's hard situation. I must read more. I'm still thinking like C# world.
 
@user2224250 Well, yes, there is another way. But: "There should be one-- and preferably only one --obvious way to do it." "Although that way may not be obvious at first unless you're Dutch."
 
Do we have a dupe for iterating over a range of numbers? Need it for this question
 
You could do this:
>>> ["undefined".__eq__(s) for s in ("Cabbage", "undefined", "yam", "UNDEFINED")]
[False, True, False, False]
But you shouldn't.
@Aran-Fey There's this: stackoverflow.com/questions/28268196/… However, the accepted answer uses map, and it might not be a good idea to promote that to a newbie, although I think it's perfectly fine to call map with int` as the function.
There's this, which has been used as a dupe target, but none of the answers there use map. :) stackoverflow.com/questions/1906717/splitting-integer-in-python
 
9:29 AM
All we need is for num in range(N):, really
That OP doesn't want to iterate over digits
(more accurately, he has that part figured out)
 
@Aran-Fey Yes they do. 145 = 1! + 4! + 5! = 1 + 24 + 120 (is super) requires iterating over the digits of 145
Oh, sorry. I just had a quick glance at the question. I'll read it more closely.
 
Yeah, but they already implemented that successfully in the breakdown function. All that's left is adding a loop that prints out all the super numbers between 1 and the user input
I guess I should've been more specific, sorry
 
However using [int(i) for i in str(n)] is much faster than doing the necessary arithmetic yourself in a loop.
 
That's true, but I don't think we have to polish the OP's unrelated code. We just need to solve the problem at hand
 
9:47 AM
@AliShahrivarian Some of that info is out of date: the Python 3.6 dict is much more compact than it used to be.
 
yes, you're right
I didn't notice python version first. Also didn't see git date
sorry
 
There's a classic talk given a few years ago at PyCon Stop Writing Classes. You can find the video on YouTube. There's nothing wrong with using classes in Python, but Jack's point was to stop people from bringing their Java habits into Python.
 
@PM2Ring thank you
I'll check that
for now must forget some clean code and reach my development to deadline
 
10:33 AM
@PM2Ring thanks, that video is useful. but also in last minutes, audience had good questions.
he said that don't use classes but you can use classes for wrapping related works. I had classes with some works that are related and I inherited them from another class that used in other modules. If I go to change them to function then I must pass all necessary arguments between functions. I've seen a function in my project with hundreds lines of code. I separate them to several functions and removed unnecessary codes (that I could use python library codes).
Now I have several functions that related to eachother and working as a class.
I think passing arguments between function take more memory (but on primes not objects)
bu actually I have a field that all methods are using in a class
 
@AliShahrivarian That sounds like a good use of classes.
 
11:04 AM
@PM2Ring At first glance this seems a bit at odds with the rhettinger.wordpress.com/2011/05/26/super-considered-super talk/post. The talk by Diederich seems to really discourage utility classes (class X(parents): pass). Yet the post by Hettinger goes into great lengths how to use inheritance to write faster.
Often using classes like: MockCleaningRobot(MockRobot, CleaningRobot): pass
 
@paul23 Diederich talked to don't write a class that you just pass.
inheritance and code reuse are another things.
He mentioned Flow class that was empty in huge amount of code. why anyone should inherite a empty class?
 
11:20 AM
@paul23 class (): pass seems different to me: it's literally a placeholder. As opposed to a class with a single stateless function in it. At least I seem to recall that the main point of the talk PM linked was about wrapping single-use functions in classes. I may misremember
 
Well Diederich also goes against the idea of a (complicated) "inheritance tree", especially not "until really required". While the talk by Hettinger actually explains how to use the inheritance tree for advantage: one of these is fast test creation. Hettinger then also notes that to do so you need to have a cooperative model for those objects, which indicates you have to design this at an early stage. (Otherwise you'd have to rewrite large blobs of code at once).
 
so "until they really required" -> Hettinger does it in a way that it's required?
my point is that the examples you quoted may be legitimate use cases, whereas the talk PM linked is about not defaulting to shoving everything in a class unless you have a good reason to
don't take the title too seriously
 
Yes, but since anyone write unit tests for everything, wouldn't that mean that everything needs to be in a class anyways? - Especially considering that moving "into a class" is not trivial at all.
 
I have no idea what you mean, but anyway I'm going to look for some food
 
IE: Diederich creates a game of life simulation at the end of the talk, where he removed all classes. - Now this in itself looks good and is testable. However suddenly the cells inside it are no longer testable, since that became part of the "code flow".
 
11:40 AM
"the talk PM linked is about not defaulting to shoving everything in a class unless you have a good reason to". Exactly. If you're coming from a Java-esque language the temptation is to put everything into classes, to give it "proper" structure, and because you want your functions to be objects. But Python functions are already objects. Each custom class your program defines is a new type that the reader has to learn about.
If you can do the task just using built-in classes then you're leveraging the reader's existing knowledge. And if you do need a class, well that's fine, but often it's possible to make a fairly small class that merely wraps a couple of existing classes via composition, and adds a small number of methods. That way you get the best of both worlds.
 
11:52 AM
I wonder if this sort of thing would get flagged as a subtle put-down, or seen as a simple statement of fact? The OP doesn't appear to be offended. stackoverflow.com/a/51169945/4014959
 
everything short of rainbows and unicorns could be flagged as subtle put-down
in the old days it was just unnecessary fluff that can be removed
 
I'm rather concerned about "When giving feedback, avoid jokes and sarcasm -- tone is hard to decipher online." I understand where they're coming from, especially in regard to sarcasm, that stuff can be deadly. But jokes? Ok, it can be hard to tell if the intent behind a jocular remark is playful or malicious, but banning jokes altogether is going too far, IMHO.
 
It's the eternal problem of trying to make rules for things that can't be exactly distinguished. You can't make ruling for "laughing with them is OK, laughing at them is not", and this is what the CoC is trying to do. The inevitable result is erring on the conservative side
 
So I guess this would get flagged under the new CoC:
And you could use a thermonuclear device to kill mosquitoes. :) Pandas is fine when the OP is asking for a Pandas solution, or if they have a lot of data to process, but it's overkill when the OP just wants to turn a pair of small lists into a dict. — PM 2Ring 2 hours ago
 
12:14 PM
at least that isn't directed at the asker, presumably answerers have thicker skin
 
12:47 PM
I hope that one day I'll stop making design decisions that later maker me think "Why did I make that mistake again?"
 
cabbage
 
day 1: I don't need to write a library for this, I'm never gonna use this code for anything else
day 21: Hmm, I had a new idea for a script. Would be neat if I had put that code into a module...
day 24: I've moved some of the code into a module, but it's not extensible because I thought I wouldn't need to extend it
day 27: *rewrites everything*
 
Why does this return "None" instead of 0 or 1
import subprocess
vm = subprocess.Popen("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", stdout=subprocess.PIPE)
print(vm.returncode)
 
> The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet.
 
@Aran-Fey I read that
didnt understand :-(
 
12:55 PM
it means that Popen doesn't block; python goes on while your program is still running
 
It means the process is still running and hasn't returned yet, so there's no return code
 
if you want to wait for it to exit, you need to wait for it to exit
 
Umm.. How do I know if the app launched as expected or not?
 
define "launched unexpected"
 
like exe is running
 
12:57 PM
so you're really asking "how do I know if it's still running"?
 
If the process couldn't be started, Popen throws an exception. If the process crashed after starting, you'll get a nonzero returncode
 
@Aran-Fey right..
I think I am barking up the wrong tree here.
apologies..
my question makes no sense .. :-P
Only when I ask someone questions i realize how idiotic they are :-(
 
it's not idiotic :) and rubber duck debugging applies to design too
if asking is the first time you really think about your problem, these things happen
as long as you start really thinking about your problem when you ask the latest, we're OK with it :P
 
@AndrasDeak Yeah. My problem Is I become a total idiot and do assumptions and based on those assumptions, I prove my idiocy to the internet.
Anyways.. thanks guys
 
don't be too hard on yourself
 
1:14 PM
Know what would be neat? A collection of random programming tips.
Tip #1: A variable name's length should reflect its life time. A loop variable can be just i or j. A variable that's initialized at the start of the function and lives until the end of the function should have a significanly longer name. This makes it harder to mix them up and accidentally overwrite a variable (like I did just yesterday)
values = load_values_from_disk()
...
for values in whatever: # <- oops
    ...
return values # <- not what I expected
 
@Aran-Fey Been there, done that..
Might be actually doing it somewhere in my current codebase. who knows..
 
Tip #2: Don't ever give your classes from_X() or to_X() methods (like from_json or to_json). Instead, write a separate JsonConverter class/function.
 
DSM
Not-sure-I-agree cabbage for all!
 
I definitely don't agree, because of "Don't ever"
 
Ok, if you have a XMLElement class then it's acceptable to give it a to_xml method. But unless your class is directly related to the input/output format, don't
 
1:24 PM
I'm socialized on numpy's .astype and .tolist
 
Ah, I was thinking of (de-)serialization to/from text. Converting to other classes is fine
 
it seems natural to me for a class to determine themselves how they should be converted
 
\o cbg
 
if you write a new class you'd either have to define an appropriate .to_json, or take your converter class and add yet another elif isinstance(obj,NewestClass) case, right?
cbg, Moo
 
DSM
Cabbage for MR.
 
1:28 PM
What are we up to on this fine but mildly hot day??
 
a headache :(
 
I hope your day ends quickly so you can take a nap then.
 
thanks :)
 
cbg all. We're doing a feasibility analysis to build a simple desktop app that will perform Windows tasks on the click of simple GUI buttons. I proposed for tkinter, others proposed for native C#.NET solutions. After some discussions, we settled for Python for its speed and ease of use. I have two questions: can I write two scripts(one script for a tkinter GUI class and the other one for a class of all button functions) and package them into one *.exe file?
 
DSM
Isn't your day almost over? Got to be midafternoon there.
 
1:33 PM
yeah, half past 3
 
@user8212173 is your "tkinter GUI class" using script 2 ? or how are they going to be connected ?
 
i will just do a simple import from script 2 to the tkinter GUI script
 
@AndrasDeak Yes, but I prefer to have all the json-related code in a single place (i.e. the converter). The converter can internally do whatever it wants; if I want to have a separate to_json function for each class, I can do that. Adding a new newclass_to_json function to a dispatch table isn't any more difficult than adding a new to_json method to NewClass.
 
DSM
One word of warning: tkinter isn't the world's most fun to work with. Depending on the complexity of your task I'm not sure that working with the .net gui tools wouldn't be quicker.
 
1:36 PM
i would like to keep the two separate for modularity. Great, that answers my first question. @DSM, we just have one guy whose good with C# and others are happy with Python. We have little experience to work with tkinter but we thought its better than learning a whole new language.
 
^ Python is good for a lot of things and can do a lot but there are other languages and other tool that excels at certain things....
 
The problem I have with adding those methods directly to the class is that sometimes the file format just doesn't support it. Sometimes you get a single line of text as input and have to turn that into 5 instances of your class
 
I actually dislike tkinter and gui in Python in general, (If I'm building like a product I have to sell), it's fine for like personal use or what not
 
DSM
@user8212173: okay, that's reasonable enough. If all you're doing is adding some buttons it should be fine. I just wouldn't want to write anything sophisticated in it.
 
The second question is: to make this exe work, would the end user computer need Python and any dependencies?
 
DSM
1:38 PM
@Aran-Fey: I don't understand the objection. What prevents you from returning five class instances if you like?
 
I'm pretty sure that's what one of py2exe main selling point is for
 
@DSM It's not a technical impossibility. Sure I can make it so that Apple.from_json({'color1': 'red', 'color2': 'green'}) returns a list of two Apple instances, but who would expect/want that? A method that looks like a constructor should return an instance of the class
 
am I weird for expecting a single json to construct a single instance?
 
No :)
 
@MooingRawr, its not fun for us to build with tkinter. But the underlying functions for button events are easier to write in Python and the GUI is simple, at least for the moment. If it starts to get complex over time, is it possible to build the GUI with C# later and then call the Python scripts for each button event? But that would beat the purpose of a common dev platform.
 
1:45 PM
I would agree with you but I would want an Apple.from_json_multi() to generate multiple instances
I could see some use for doing so
 
@AndrasDeak In my specific case, the file format was forced on me by a big company who uses it in their application
 
"attorneys general", "Apples.from_json", etc.
@Aran-Fey if the file contains multiple serialized instances can't you write a helper that parses the file and calls an Apple.from_json on each chunk?
 
For example Fruit.from_json_multi({'apple':{'color':'red'}, 'orange' :{'color':'yellow-red'}})` which would yield me an apple instance of a fruit class and an orange instance of the fruit class. of course, I would like an optional parameter on that function to define the nested instance splitting
@user8212173 You can use c# code (so your GUI in c# in this case) to call python scripts. I have no personal experience in that field, so I can't comment on how well it works out
 
DSM
@Aran-Fey: .. you just got done saying "Sometimes you get a single line of text as input and have to turn that into 5 instances of your class". If I'm working in such a situation, then I might very well expect and want that. I think our instincts just disagree on this one; it seems to me a class method is a perfectly reasonable place to put constructor utilities for the class.
 
perhaps call it Apple.spawn_instances to make it obviously a non-constructor, maybe unpack_json for a more realistic example name
 
1:56 PM
@AndrasDeak Sure, but the point is that the helper function isn't associated with any class. It's a separate thing, and because of that I would prefer to separate all of the deserialization logic from the classes. If I can choose between putting the serialization logic for all of my stuff into a common place or implementing a tiny fragments of it in every class, I'd rather have it all in a single place
 
@MooingRawr @DSM Ok, fine, I'll admit that it's acceptable to do it that way sometimes. The problem is that it's hard to tell when, so I prefer to be consistent and always make the converter a self-contained entity
 
 >>> class Entity(list):
...     def __init__(self):
...         self.append(self)
...
>>> a = Entity()
>>> a in a
True
(^ self-contained entity)
 
not like that :/
I'm debating if I want to continue explaining my reasoning, but I think at this point I'll just let it go... nobody wants to hear me ramble, I don't think
 
I merely don't have the perspective to judge either way :)
 
2:14 PM
Morning cabbage
 
cbg
 
cbg
 
2:29 PM
"The result of the poll: 29 coredevs dislike 👎 PEP 572 vs 3 coredevs like 👍 it. Seems that just these 3 people generate 50% of comments. mail-archive.com/python-committers@python.org/…; - via Twitter
 
I need some design help: I'm working on a library that has a kind of central database that's expensive to access. Let's say it's a library for a shop, so there's classes like Customer and Product and all the existing customers and products are stored in the database. Since the database updates very very rarely and it takes a long time to access it, I have a local copy of the database.
Now here's the part I need help with: How should implement the coupling between the classes and the database? For example, db.get_customer(id=123) would make it easy to check if such a customer exists and update the database if it doesn't. On the other hand, Customer.from_id(123) looks like a much nicer interface to me, but then Customer would need to have a hard-coded dependency to a specific database instance.
(Though the database class isn't publicly accessible and can never be instantiated by anyone other than me, I still don't really like the idea of hard-coding a specific instance into all my other classes. Maybe I'm overthinking it?)
 
2:52 PM
I'll take that as "it doesn't really matter"
 
hmm weird scenario you got yourself there.
"if such a customer exists and update the database if it doesn't." but you just said the update are rare, are you expecting to update ? are you the only one who is going to be updating the database ?
 
3:08 PM
@shad0w_wa1k3r wow
 
@Aran-Fey It matter, but I'd say you are overthinking it. Pick & choose depending on the level of code resuse / simplicity you intend to keep.
 
let's hope the python core devs don't split
 
We still have a BDFL to handle such a scenario.
If it comes to that, I hope he uses that D to use :-p
 
Let's hope it's not BDFL who handles it ;)
 
also Nick's tweet earlier in that thread twitter.com/ncoghlan_dev/status/1014265779053711360
 
3:13 PM
@MooingRawr The updates are rare, but they do happen. So if someone tries to access a customer/product that doesn't exist in my local copy of the database, I have to assume that my copy is outdated and access the real database. And I'm not sure why you're asking, but the database is actually completely outside of my control. It's being updated exclusively by someone else.
 
there must be massive tension among core devs
 
@shad0w_wa1k3r Alright, thanks
 
@Aran-Fey can't you dynamically set the db instance as a class attribute? Assuming I understand you correctly
 
db = DB()

class Product:
    db = db

    @classmethod
    def from_id(cls, id_):
        try:
            return cls.db.get_product(id_)
        except ValueError:
            cls.db.update()
            return cls.db.get_product(id_)
^ like that?
 
yup
and update it if necessary
(I take it it isn't necessary)
 
3:18 PM
Is that really better than using the global db? What do I gain from binding it to each class?
 
Nothing, I guess. But you seemed to have been talking about hard-coding
 
I'm not sure I like that class idea, if you know there's a database update, but you are accessing Class Product, and then Class Customer, you have to update the database for each class
If it helps Aran, in my code at my company, I keep a local reference to my Database, but it's my code that updates the database as well, so when I send my update to the main database, I just update my local reference database accordingly, hence I asked my question on who updates
 
I guess "hard-coding" may not have been the best choice of words. Basically the question is if I should make the link between the classes and the database implicit (with a global and private db variable) or explicit (by making db public and a factory for products and customers) (or possibly a 3rd option I didn't think of)
 
I think in your case, if I were you, I would keep a "global" database references and update accordingly
oh .... hmmmm
 
I guess I'll go with the global db variable, then. Makes a nicer interface.
 
3:24 PM
on one hand I'm not sure I like the idea of a factory creating the product and customers over and over again everytime there's an update. On the other hand I'm not sure global would be easier to maintain in the long run.
man you are in a pickle :P
 
I'll just have to be careful to clear/update a bunch of memoized results when the database is updated
 
I had to fix a legacy code bug where the syncing of the database and the "local" database was off and it threw a weird edge case. That wasn't a fun week :\
 
@aaronchall @raymondh It's a tough one, and I wish I'd done this differently 20+ years ago. Changing it now would break so much code it would have to be called Python 4.0, and we don't want *that*, do we?
 
What's another 10 years for Python 4 :D
 
on the other hand it's a famous pitfall and decent tutorials will bring explicit attention to the phenomenon
 
3:29 PM
I also find it weird that database fetching is expensive, isn't that one of the main point of a database, is to have a quick search up.. I would thought that would imply not being expensive, but most of the cases it is expensive :\
 
also some of the replies are weird. "Python has a "feature" where default arguments are mutable.". Uh, no, they're exactly as mutable as they should be :/
 
More reasons why we need a python 4
 
you're joking but that's exactly what Aaron said :P
 
I wasn't really joking. I'd welcome a python 4, but I don't really need it
 
hah
I would have tweeted “YET”
I wouldn’t welcome a Python 4 at all. Python 2 isn’t even dead.
 
3:36 PM
@Aran-Fey there's no way a breaking change like 2->3 could be pulled off, considering how 2->3 couldn't be pulled off :'(
 
Python 4000
 
<2 years left of python 2 and people are sighing that nice new features aren't being backported to 2
 
'course, I have it easy - I update my personal projects to python 4 without having to care about supporting older versions. I understand if maintainers of more popular projects wouldn't welcome python 4 at all
 
I'm trying to understand the use-case for setting a default argument based on a global that you expect to change, but you don't want the default to change...
 
The mutable default is just a thing you have to know. That’s not too much to expect from users of the languages. At least we don’t have a holy trinity problem (and that apparently isn’t big enough of a problem either to prevent language adoption)
@AaronHall A breaking change is a breaking change. There doesn’t need to be a proper use case for the previous state.
 
3:39 PM
As I understand the mutable default argument is a direct consequence of defaults being defined at function definition time. Not a feature, it's just how it happens.
 
@poke I recognize it's a breaking change: twitter.com/aaronchall/status/1014494324787236865 - that's why we use __future__for breaking changes.
 
__future__ is not really useful here.
 
from __future__ import runtime_defaults
and runtime_defaults become mandatory in Python 4.
 
That would require there being an actual future where this becomes the default (which won’t happen because it’s a breaking change, a stupid one); and that only adds complexity you have to account for for no benefit.
 
How would something like that even work? What would happen to def foo(x=[4]): x.append(2)?
Error for using a mutable type as default?
 
3:45 PM
It would probably open up a few more questions..
in this case, it would probably have to be equivalent to def foo(): x = [4]; x.append(2)
 
oh my, it will break all my def foo(deftime=time.now()): ... functions :P
 
If we're open to changing the language as much as we have been, at least we should be open to considering changing this.
 
You do that?
 
I think he's being a little facetious.
 
People are complaining that the change would break these kinds of eager binding lambdas:
x = 3
f = lambda x=x: ...
But if we're honest that's a good thing because nobody wants to read code like that
 
3:51 PM
Doesn’t make it less of a breaking change.
 
What's wrong with breaking changes?
 
@AaronHall so the slippery slope argument was right :P 572 boo
 
There are people who are still not over the Python 2 to 3 conversion and are very frustrated about their experience with it. With breaking changes, especially those that are easy to miss (because everything would still compile just fine!) you just create hostility and that’s not something the Python community as a whole can have at the moment. Not when Python 2 isn’t even dead and when there are still a large number of users for that (who also currently still plan on keep using it).
You really can’t start planning a 4.0 on that.
 
Then the people claiming that python is unreliable as a foundation would be right
 
@AaronHall It doesn't have to be a global, the usual use case is when people are making a GUI and connecting callback functions to buttons in a loop like that:
for num in range(3):
    button = Button(command=lambda num=num:print(num))
    button.pack()
 
4:02 PM
I think the solution is to fix that.
 
"Fix"?
 
This should work intuitively:
def foo():
    lof = []
    for i in range(3):
        lof.append(lambda: i)
    return lof
lof = foo()
>>> for f in lof: f()
2
2
2
But that's a good point.
 
I'm not convinced that the current behavior of lambda functions is less intuitive than the one you're proposing
 
Yup
The behaviour is surprising but sane. The solution is better education
 
And a lot of the time the solution is functools.partial (:
 
4:06 PM
@Aran-Fey Yes, that would be better.
 
> The solution is better education
^ Truth.
 
@AndrasDeak As one providing such education, I do cover the mutable default argument issue, but I haven't yet covered the closure on a shifting local/global while looping issue.
(for globals it should be expected...)
 
4:51 PM
cbg
 
cbg
 
Did I miss an announcement about the new arrangement of answers? Upvoted answers are routinely listed lower than 0 voted answers
 
only if they are sorted by votes
 
... I've clicked a button then :P
Yep, well that was a quick fix :)
Do you happen to know what "F levels" are, Andras?
 
not without context, no
 
5:03 PM
"@roganjosh Related to physics, The possible values of F levels are | I - J |, | I - J | + 1, . . . . . . I + J."
I don't understand that sequence, and that's all I have to go on
This is the question if that helps because they stated the same (kinda) sequence twice.
 
@roganjosh OK, with that those are angular momentum quantum numbers when adding two quantum angular momenta of I and J
probably something with nuclear physics, or maybe particle physics but I find that less likely
the point is that the angular moment quantum number of the operator which is the sum of the two angular momenta goes from |I-J| to I+J (where both I and J are non-negative integers or half-integers)
 
Much appreciated, time to do some reading there. My searches were just pulling up haemoglobin and I have no way to discern what's relevant once I dismiss those articles
 
"addition of angular momentum operators"
F-levels are probably a very specific manifestation of this broader problem
 
 
1 hour later…
wim
6:26 PM
@AndrasDeak they got peer pressure badge, hehe stackoverflow.com/help/badges/38/peer-pressure?userid=1914034
 
Is there any harm in inheriting from abc.ABC twice? I'm subclassing an abstract class and explicitly inheriting from abc.ABC again, is that a good or bad idea?
 
wim
why do that in the first place
The dupe will be removed in MRO, so it seems harmless but also pointless
 
I played around with that before, there's no issue with it, but I haven't checked memory profiling
 
wim
there is one issue if you put them in wrong order it can be TypeError (but you would see that at class definition time)
 
Yeah you're right, there's actually no reason to do that
 
6:44 PM
@wim I saw that :D
 
bleh, I don't really have a good way of phrasing this:
pd.DataFrame({'colname': np.array([[1,2,3],[2,3,4]])})
 
ew :P
what do you want to achieve?
 
doesn't work, and prev SO answers say to wrap a list around it so [np.array(...)], but I wanted each row of the ndarray to be a row of the dataframe
I'm trying to squeeze MNIST images into each row of the dataframe (not pretty, I know)
 
and each row has a single 3-element-array-valued item?
 
It's just everything in this tiny utils repo is all in pandas..
yes
3 dimensional-array-valued-item
 
6:51 PM
I suspect you're misusing it or it's crap :P but anyway that's tangential
 
but in this example it's 3 element vectors yup
Technically, the image is a feature ;) and pandas should let me do it whether or not it's correct or not
 
you technically shouldn't want to put non-scalars in array-likes
>>> pd.DataFrame({'colname': list(np.array([[1,2,3],[2,3,4]]))})
     colname
0  [1, 2, 3]
1  [2, 3, 4]
the repr makes it look like those are lists, but no, they are arrays. If you want lists, use .tolist() on your arrays instead of calling list() on it (the latter will only replace the outermost level with a list)
 
ah, thank you. What would be a suggested alternative?
 
HI how to get percentile column on pandas group by i tried this but this is giving nan user['Percentile_95'] = user.groupby('User')['Count'].quantile(0.95)
 
Well, I don't know what you're doing but I'm not even sure you need to stuff all that data into a dataframe. But I'm not a pandas expert so I'm biased towards using vanilla numpy ;)
 
6:54 PM
Fair :) I agree. I already have that implemented.
 
numpy and pandas typically shine when they get primitive scalars inside; object dtype makes them lose a lot of performance
 
FWIW this isn't really a performant thing; it's like a mini datastore for testing functionalities
kind of like scikitlearn's data fetching
 
you're not making a good case here ;)
 
I doubt I can, but I need conformance to the standard, and I think that's the only case I need to make sometimes :P
 
yeah, "my hands are tied" is as good as excuses go
@KumarAK are you sure user.groupby('User')['Count'] itself is reasonable?
say, no missing data for a given group of users, etc.
 
7:06 PM
@AndrasDeak no i want seperate column in user dataframe that shows the percentile 95 value for each User group
 
that completely misses my question
 
df['Percentile_95'] = df.groupby('UserID')['Count'].quantile(0.95)
 
oh, perhaps the problem is the assignment
Does the right-hand-side alone have nans? Or only after assignment?
 
after assignment i have nans
i want this column df['Percentile_95'] filled with 95th percentile value in all row
 
>>> df = pd.DataFrame({'a':[1,2,1],'b':[-1,-2,-3]})
>>> df
   a  b
0  1 -1
1  2 -2
2  1 -3
>>> df.groupby('a')['b'].quantile(0.95)
a
1   -1.1
2   -2.0
Name: b, dtype: float64
>>> df['q'] = df.groupby('a')['b'].quantile(0.95)
>>> df
   a  b    q
0  1 -1  NaN
1  2 -2 -1.1
2  1 -3 -2.0
The dataframe has n rows, you're assigning a new column with m<n rows. Hence missing data.
is this what you want?
>>> df = pd.DataFrame({'a':[1,2,1],'b':[-1,-2,-3]})
>>> df.groupby('a')['b'].transform(lambda x: x.quantile(0.95))
0   -1.1
1   -2.0
2   -1.1
Name: b, dtype: float64
>>> df['q'] = df.groupby('a')['b'].transform(lambda x: x.quantile(0.95))
>>> df
   a  b    q
0  1 -1 -1.1
1  2 -2 -2.0
2  1 -3 -1.1
 
7:23 PM
thanks. iam trying to replace greater than percentile values with the original values in other column like this
if df['b'] > df['q']:
df['Capped_Count'] = df['q']
else:
df['Capped_Count'] = df['b']
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
this is the error im getting
 
You should probably be using np.where() for that
Is there an example DF I'm missing in the chat history that I'm missing or am I starting from scratch?
 
>>> df = pd.DataFrame({'a':[1,2,1],'b':[-1,-2,-3]})
>>> df.groupby('a')['b'].transform(lambda x: x.quantile(0.95))
0 -1.1
1 -2.0
2 -1.1
Name: b, dtype: float64
>>> df['q'] = df.groupby('a')['b'].transform(lambda x: x.quantile(0.95))
>>> df
a b q
0 1 -1 -1.1
1 2 -2 -2.0
2 1 -3 -1.1
 
I saw that but it's a bit hard to validate 0.95 quantile against so few values.
 
7:42 PM
@roganjosh latter
@KumarAK df['b'] = df['b'].clip(upper=df['q']) but you need to start looking at tutorials. The kind of error you got is a very typical mistake for new users of numpy/pandas who don't try to learn the basics first
you could've done this with a boolean index array, which is a basic feature of these array-like operations (elementwise operations in general)
(^^ or df['b'].clip(...., inplace=True), probably)
 
00:00 - 20:0020:00 - 00:00

« first day (2818 days earlier)      last day (2129 days later) »