|
Everything is a dictionary anyway so why pretend otherwise, just use dictionaries for everything (I'm lying, don't actually do this) Eela6 posted:I am of this opinion. I agree as well; too many times I've seen unnecessary class implementations of things that really seemed like the developer was just looking for excuses to create classes rather than using classes to make the code easier to understand/use. I think it's easy for developers coming over from C++/Java to fall into that trap, whereas developers coming from Matlab/Fortran have the opposite problem (everything should be a function!)
|
# ? Mar 13, 2017 00:12 |
|
|
# ? May 15, 2024 03:19 |
Finding the correct level of abstraction is like tuning a guitar string by ear. The correct tuning depends on the pitch of the strings around it, and large changes might require re-tuning of the surrounding strings. Similarly, there is no uniform level of abstraction that is 'always correct' for a particular concept. Whether or not a particular piece of code is correctly abstracted is not just a function of the code itself, but the larger program as a whole.
|
|
# ? Mar 14, 2017 19:37 |
|
I am trying to understand OrderedDicts. I am reading the documentation and am having trouble understanding what the following line is saying: "The OrderedDict constructor and update() method both accept keyword arguments, but their order is lost because Python’s function call semantics pass-in keyword arguments using a regular unordered dictionary." Is this saying that if I add items to the OrderedDict as follows Python code:
code:
|
# ? Mar 14, 2017 21:01 |
|
If you add items like you did in your example, you should be fine. The problem is when you do it like this: Python code:
|
# ? Mar 14, 2017 21:18 |
|
It's more that if you were to do:code:
code:
However, the way you were adding to the dictionary is the recommended way that would ensure the order always.
|
# ? Mar 14, 2017 21:19 |
|
Got it, thanks!
|
# ? Mar 14, 2017 21:29 |
|
Jose Cuervo posted:Got it, thanks! And remember, in Python 3.6, dicts are now ordered. Python Changelog posted:New dict implementation
|
# ? Mar 14, 2017 21:55 |
|
It's right there on the quote that you should not rely on that ordering.
|
# ? Mar 15, 2017 00:18 |
For now, if you are relying on the order, use OrderedDict all the way through. In CPython 3.6 it's just the new dict implementation under the hood, so you lose nothing, but you keep back-and-forward compatibility. (I will never go back! f-strings are too useful.)
|
|
# ? Mar 15, 2017 00:59 |
|
I often do something like this:code:
Specifying the parameter to some arbitrary value before the while loop feels inelegant. Is there a better way for doing this? A more fleshed-out example, maybe I want to randomly draw an even integer between 140 and 75858 whose third-to-last digit is a 4 or a 7 for whatever reason: code:
I guess this is a very minor thing, but it's a pattern I use all the time and it feels weird.
|
# ? Mar 15, 2017 12:42 |
|
I try to start with None or a boolean value if I don't have a default value that makes sense.
|
# ? Mar 15, 2017 13:23 |
|
HardDiskD posted:I try to start with None or a boolean value if I don't have a default value that makes sense. But sometimes these 'natural defaults' match the condition. E.g., what if False matches my criterion of being (not var % 2 and var < 1000)?
|
# ? Mar 15, 2017 13:26 |
|
Sorry to be unspecific, but in that case you have to analyze whatever makes the most sense to you and work around the code's limitations.
|
# ? Mar 15, 2017 13:34 |
|
You can also avoid the issue in several ways. My favored solution would be to turn the stochastic process into a generator then use it like this: Python code:
Python code:
|
# ? Mar 15, 2017 15:19 |
|
I like the generator one! Thanks guys.
|
# ? Mar 15, 2017 15:41 |
|
You could also do next(filter(checker, generator)) if you're into that e- whoooooops
|
# ? Mar 15, 2017 16:17 |
Cingulate posted:I often do something like this: Python lacks the construct DO -> WHILE, so you have to figure out what makes sense given your level of abstraction. Personally, since this is a single construct ('get a number that satisfies this condition'), I would abstract it out to a function. This also lets you skip the 'pointless' initialization of your parameter that you find inelegant. This is similar to SurgicalOntologist's suggestion of using break. I just like functions. Python code:
Eela6 fucked around with this message at 19:26 on Mar 15, 2017 |
|
# ? Mar 15, 2017 19:23 |
|
Not sure if I should put this here or in the Scientific Computing thread, but whatever. I have a data analysis project that involves computing a series of variables on a dataset (specifically, I'm adding DataArrays to an xarray DataSet, but it's the same idea as if I were adding columns to a DataFrame). Each calculation requires some variables to already be available and adds one or more variables to the dataset. Some of these are expensive to calculate and may not be necessary to run in all circumstances so I don't want to run everything. In short, I want a way to handle this dependency graph. This seems like it should be a common pattern but I don't know of an existing easy solution. Closest thing I can think of is dask's DAG compute engine but this doesn't really fit into that model since I'm enriching the dataset object rather than passing around values. If there's no existing solution the the best option I can think of is to have something like a require method call at the top of every function that checks if the required elements are present and then runs the corresponding function if they are not. Any better ideas?
|
# ? Mar 16, 2017 22:59 |
SurgicalOntologist posted:Not sure if I should put this here or in the Scientific Computing thread, but whatever. You want to implement lazy attributes - only calculated if they don't already exist. Here's an implementation, taken from Python Cookbook, 3rd Ed by David Beazley and Brian K. Jones, pg.267-278. (The example class is my own.) This works because a __get__() method associated with an attribute is only called if the attribute being accessed is not in the underlying instance dictionary. Python code:
code:
Eela6 fucked around with this message at 00:00 on Mar 17, 2017 |
|
# ? Mar 16, 2017 23:45 |
|
I always use the one I stole from django.Python code:
|
# ? Mar 17, 2017 00:01 |
|
Ah yes, that's the way it should work. But it is complicated slightly by the fact that these aren't attributes but rather DataArrays within a DataSet (analagous to columns in a DataFrame). And xarray does the same thing pandas does to allow these variables to be set with __setitem__ but retrieved with __getitem__. I could subclass DataSet and make my lazy variables true properties...but I'd probably have to override the name collision detection error. Or I could make my own get function: Python code:
|
# ? Mar 17, 2017 00:12 |
|
Hmm seems like this is more complicated. The methods I need to be calling aren't really getters but assigners, because sometimes coordinates need to be fixed or other implementation details when assigning a new data array. Also some of them assign multiple arrays. For example see these two methods: Python code:
Not sure that coming up with a general solution will be worth it. Maybe I could make the lazy properties work with composition instead of subclassing...
|
# ? Mar 17, 2017 00:28 |
|
I've got a login form and a registration form on a single page with a nav that toggles a hidden class between the two. By default, when the page loads, registration is set to hidden. However, if a user fills out the registration form and there are errors on submit, the page refreshes and login is loaded. How could I get the hidden class to instead be applied to registration if a user registers but has errors?
|
# ? Mar 17, 2017 02:47 |
|
huhu posted:I've got a login form and a registration form on a single page with a nav that toggles a hidden class between the two. By default, when the page loads, registration is set to hidden. However, if a user fills out the registration form and there are errors on submit, the page refreshes and login is loaded. How could I get the hidden class to instead be applied to registration if a user registers but has errors? Pass a flag to the template and, depending on the state of the flag, apply (or not) the class to the offending elements. Python code:
HTML code:
Space Kablooey fucked around with this message at 04:43 on Mar 17, 2017 |
# ? Mar 17, 2017 04:39 |
|
Honestly, big shouts to the OP for having a great post for Python newbies like myself.
|
# ? Mar 17, 2017 20:26 |
|
Is it okay to do something like this:code:
e: Silly example aside in the real case I wrote the base class as an interface layer to other classes. It's not actually meant to be instanced directly but I have a few subclasses deriving from it that implement actual functionality. At the moment I have a module level getter function that's just more or less the __new__ method shown above. It's just more convenient and user friendly though I think to be able to instance an object by doing "beer = Beer('ipa', args)" instead of "beer = get_beer('ipa', args)". I want to avoid instancing the actual subclasses directly. e: vvv What's the proper way to do it then? Boris Galerkin fucked around with this message at 12:40 on Mar 18, 2017 |
# ? Mar 18, 2017 09:20 |
|
Boris Galerkin posted:I think the proper term is using the __new__ constructor as a factory function? Is this an accepted way to do something or is this one of these things I shouldn't do in python? Yes, this is what you're doing and no it is not a normal thing to do. I can't think of anything really wrong with it, but it's definitely weird and you will surprise people if you do it.
|
# ? Mar 18, 2017 10:59 |
|
Boris Galerkin posted:e: vvv What's the proper way to do it then? Maybe just a regular function or a classmethod on Beer. Python code:
|
# ? Mar 18, 2017 16:19 |
I agree with Thermopyle. @classmethod is the way to make alternative constructors. If your method could be described as Python code:
Generally speaking, overriding __new__ is deeper magic than you need to solve a problem in python. However, it is very fun! This happens most often when you want to create new classes 'on demand'. I don't know if your problem requires this, but if you want to get into runtime construction of classes, you should look into Metaclasses. Python Classes make Instances - > Python Metaclasses make Classes I am not confident enough in my python magic to give a good example, but both Fluent Python and the Python Cookbook, 3rd. Ed, have great tutorials. (I'm sure they exist online, but I don't know them well enough to suggest one). As a final point, your override of __new__ won't work in the first place. It is a class method that implicitly takes cls as the first argument. The signature is as follows: Python code:
Eela6 fucked around with this message at 18:20 on Mar 18, 2017 |
|
# ? Mar 18, 2017 18:09 |
|
Thanks guys, I'll just stick with having a separate get_class_thing(...) function. It's what I had before but then I found out about __new__ and thought maybe I could just overwrite it. Another question: I'm using sphinx to document things and in some of my methods I have latex math syntax, e.g code:
code:
|
# ? Mar 19, 2017 14:02 |
|
I decided to pick up Python, I have a fair amount of experience with Perl and C++ but want to update my skillset a bit. My laptop that runs Linux is having hardware problems so I decided to fart around on my Windows gaming PC with this. I'm working through a tutorial book but just encountered an issue. They want you to mess around with turtle which is part of the standard library. If I call my script or invoke Python in a command shell from my base user directory (C:\users\TGS) I can import turtle and work with it just fine. If I try to import it from a folder on my desktop, I can't. I just get an unknown attribute error since it can't find the library. I've checked the PATH and the installation directory for Python is there so uh, anyone know what gives?
|
# ? Mar 21, 2017 01:36 |
|
The Gunslinger posted:I decided to pick up Python, I have a fair amount of experience with Perl and C++ but want to update my skillset a bit. My laptop that runs Linux is having hardware problems so I decided to fart around on my Windows gaming PC with this. I'm working through a tutorial book but just encountered an issue. You'll need to modify your PYTHONPATH to point to the folder where your script lives. Print sys.path to see what your PYTHONPATH looks like; if your file lives in a folder that isn't in sys.path then Python doesn't know about it https://docs.python.org/2/using/windows.html#configuring-python If that doesn't work then I misunderstood the problem and you should probably copy-paste the actual error Did you install vanilla Python or did you install Anaconda? If you're going to work in Windows then it's strongly recommended that you uninstall vanilla Python and install Anaconda, which will likely circumvent tons of headaches. Once you have Anaconda installed you can use the Spyder IDE (which comes with Anaconda) for your development / playing around. If you want to get serious, then you could look into installing the PyCharm IDE.
|
# ? Mar 21, 2017 04:32 |
The Gunslinger posted:I decided to pick up Python, I have a fair amount of experience with Perl and C++ but want to update my skillset a bit. My laptop that runs Linux is having hardware problems so I decided to fart around on my Windows gaming PC with this. I'm working through a tutorial book but just encountered an issue. This is a bit strange. How did you install Python? If you're a beginner, especially on windows, I would try using Anaconda. As mentioned, Spyder is a great beginner's IDE. I personally use Visual Studio Code
|
|
# ? Mar 21, 2017 04:32 |
|
I just uninstalled Python and installed Anaconda instead. Having the same problem though.code:
I can only import sys and print sys.path if I run python from a shell in C:\users\TGS. It shows the default Anaconda install directory, scripts sub folders and etc. I just want to be able to run scripts from any directory instead of being locked to my user directory.
|
# ? Mar 21, 2017 13:17 |
|
The Gunslinger posted:I just uninstalled Python and installed Anaconda instead. Having the same problem though. I think you have a file named turtle.py in the same folder as the file bob.py. So when it looks to find the turtle module, it "finds' it where it first looks - in the same folder, and never gets to look in the folder where Python is installed.
|
# ? Mar 21, 2017 13:34 |
|
Haha holy poo poo I hope it's that simple, just got into work but I'll RDP into my machine later and check. Thanks man.
|
# ? Mar 21, 2017 13:42 |
|
The Gunslinger posted:Haha holy poo poo I hope it's that simple, just got into work but I'll RDP into my machine later and check. Thanks man. This is probably it. I've been writing python for a decade and this will still occasionally trip me up...particularly when it's a large project and I've been doing lots of refactoring.
|
# ? Mar 21, 2017 15:19 |
|
I am using Python 2.7 with PyCharm Community Edition 2016.3.2. I have the following snippet of code:Python code:
|
# ? Mar 22, 2017 15:29 |
|
Try using a comma instead of a colon in the typehinting
|
# ? Mar 22, 2017 22:51 |
|
|
# ? May 15, 2024 03:19 |
|
Hi goons. I am trying to teach myself to build a web scraper for Craigslist using Scrapy and BeautifulSoup. I've never programmed before, but I've worked through Python Crash Course, and now I'm using Web Scraping With Python. I have this program that pulls exactly what I want into a CSV, if I manually feed it urls. Python code:
The problem I'm having is I can't get my own crawler to work. I can get Scrapy's tutorial crawler to run so I know everything is correctly installed. What I need, or I imagine I need, is a crawler that populates that variable "html" or reconfigure the "soup" variable and the rest of my code will finish it off. Again I'm relying on Scrapy's site: Python code:
FingersMaloy fucked around with this message at 21:05 on Mar 23, 2017 |
# ? Mar 23, 2017 20:57 |