There are two main reasons for @property. One is when you want to present a uniform API to your users. If you have a single method that takes only self and will always return the same result for a given object, it's "really" a property. For example, you might lazily compute the perimeter of a 2d shape when asked for, but the users don't need to know whether it's computed during __init__ or when you ask. Plus, if we only implement a 'getter' for perimeter and not a 'setter', our code won't let us create a rectangle where P! = 2(WH) well, within the limits of Python floats, anyways... This helps makes some guarantees about our rectangles being actual rectangles. The second is as a step in refactoring. Suppose we have a class Frisbee. You initially had a property, Frisbee.curve that was a public attribute. Later on, you implemented an advanced physics and materials simulation; it models the deformation of the Frisbee during its flight! That is, Frisbee.curve is no longer a static property - it can change over time! Clearly, Frisbee.curve needs to be a method that works with your physics simulation. The problem is, all over your codebase and your customers' codebases, there are calls to some_frisbee.curve, not some_frisbee.curve(). Using @property makes the change "invisible" so that the old calling signature will still work. Excessive use of @property is a warning sign of brittle code, though. At that point you might want to start raising warnings on old API usage that tell the user about your new API that more closely suits how your new code actually works. if you want to know more, there are sections in 'Effective Python', and a speech by Brett Slatkkn, the author of that book, about this. Eela6 fucked around with this message at 17:30 on Mar 8, 2017 |
|
# ¿ Mar 8, 2017 17:15 |
|
|
# ¿ Apr 29, 2024 12:00 |
I wrote something pretty fun today. I got sick of writing __repr__ for functions, so I made a decorator that does it for me!Python code:
|
|
# ¿ Mar 10, 2017 02:02 |
That's the way I tried to do it at first, but it wasn't inherited properly through subclassing, which bugged me. You get the name (and signature) of the base decorated class. E.G: Python code:
Eela6 fucked around with this message at 04:35 on Mar 10, 2017 |
|
# ¿ Mar 10, 2017 04:31 |
Why not just have two attributes? country.name being the default, and country.name_in_lang being a dictionary that holds the other names? I think you're overthinking this.
|
|
# ¿ Mar 10, 2017 09:04 |
Boris Galerkin posted:Because it was just an example. I too came from MATLAB, where you can call a zero-argument function without the parentheses. The reason why you can't (well, shouldn't) in python is because Python has functions as first class objects. That means you can put functions into containers, have functions with extra attributes (that could be functions themselves), all sorts of weird stuff. This is powerful, but it means you need a way to refer to the function itself as an object. When you use the parentheses you are referring to the action of the function. When you don't use the parentheses you refer to the function itself. This is a crucial distinction! Here's an example that might help. IN: Python code:
code:
Other languages do not have this philosophy. I am of the opinion it is one of the best things about Python, but you may disagree. That's OK; just be warned the majority of the community will not be on your side. The Zen Of Python posted:Explicit is better than implicit. Eela6 fucked around with this message at 22:00 on Mar 10, 2017 |
|
# ¿ Mar 10, 2017 21:48 |
Elm is a neat language! I'm not sure if I love it but there are a lot of interesting ideas there.
|
|
# ¿ Mar 11, 2017 18:03 |
Whenever you call a function, it does some action, then returns an object. The function sorted() takes an iterable* and returns a sorted list of the contents. This is a new list; not the old one. list.sort(), on the other hand, is a method of a list (a special kind of function, attached to an object), that sorts it without making a new copy. To remind programmers of the difference, it returns None. Try this code:
*An iterable is an abstraction of anything that can give you a 'flow' of objects, one at a time. Tuples, lists, sets, and dictionaries are all iterable. For now, all you need to know is anything that supports code:
|
|
# ¿ Mar 12, 2017 04:14 |
Thermopyle posted:There's a not-entirely-unjustified school of thought in python-land that too many developers pull out classes unnecessarily. I am of this opinion. This is a good video on the subject: [video type=""]https://m.youtube.com/watch?v=o9pEzgHorH0[/video] Classes are useful when they make your code easier to reason about. Too many classes are often a signal of code without forethought.
|
|
# ¿ Mar 12, 2017 20:44 |
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 |
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 |
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 |
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 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 |
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 |
As a small note, this part of your code:Python code:
Python code:
edit: EFB
|
|
# ¿ Mar 23, 2017 21:47 |
^^ No idea, but I would love to know the answer. I gave my second talk at San Diego Python last night! It went really well. Who in the thread is going to PyCon this year? It might be fun to have a goon Python dev lunch.
|
|
# ¿ Mar 24, 2017 18:03 |
tricksnake posted:Hi I am a new python user just now working my way through Learn Python The Hard Way I would recommend downloading Anaconda. It comes with a lightweight IDE, Spyder, that I find excellent for beginners to-intermediate programmers. In addition, Anaconda includes many of the most useful packahes and dependencies 'in-box', some of which can be frustrating to install otherwise. It has decent autocomplete and will warn you about syntax errors, and it has a very easy REPL work flow. Other good choices for IDEs are PyCharm and Visual Studio Code, but you might find them a little heavyweight for what you're doing right now. Good luck with Python! I hope you enjoy it
|
|
# ¿ Mar 28, 2017 02:52 |
huhu posted:Would this be the best way to log errors on a script that I'm running? Python has a standard logging module . However, if you're just doing something very basic, this is the 'pythonic' way to do what you're asking. Python code:
Python code:
|
|
# ¿ Mar 28, 2017 20:49 |
Indeed I did. Thank you. Edit: this is actually a great example of why to use 'with' over manual open/close: even with experience it's easy to gently caress it up doing it manually. Eela6 fucked around with this message at 21:41 on Mar 28, 2017 |
|
# ¿ Mar 28, 2017 21:33 |
Why not? I'd love to know
|
|
# ¿ Mar 30, 2017 06:23 |
oliveoil posted:Is there anything like the JVM spec but for Python? CPython is the standard. The best place to start is probably the Python/C API Reference Manual Garbage Collection is handled by reference counting. Objects whose live references hit 0 are immediately. Cpython countains an occasional cyclic garbage detector; while the running of the garbage collection can be forced, outside of that it's behavior is not (meant to be) predictable. Python is more about knowing how things behave than 'what they are'. EG, All integers are implemented as “long” integer objects of arbitrary size. Python Doubles behave as IEEE 64-bit doubles, full stop. If you want to know more about Python's data model and how things work behind the scenes, I recommend Fluent Python, as I do to everyone.
|
|
# ¿ Apr 1, 2017 20:30 |
OnceIWasAnOstrich posted:numpy for the array and matplotlib imshow() to render? A uint8 array of dimensions [m, n, 3] works well to represent images on a pixel level. The library skimage (installed by default in anaconda) works well for basic image manipulation as well. E.G: Python code:
Eela6 fucked around with this message at 16:57 on Apr 8, 2017 |
|
# ¿ Apr 8, 2017 16:54 |
I mostly use visual studio code as well. I don't do any webdev so I can't comment on its use for that.
|
|
# ¿ Apr 12, 2017 21:36 |
Boris Galerkin posted:https://github.com/python/cpython/blob/3.6/Lib/collections/__init__.py I have no idea. This is really strange.
|
|
# ¿ Apr 15, 2017 23:40 |
The first rule of namedtuple is 'don't look at the implementation of namedtuple'
|
|
# ¿ Apr 16, 2017 19:10 |
Thermopyle posted:IMO, typing.NamedTuple is also better than collections.namedtuple with no extra dependency. I haven't used attrs, though. Thanks for pointing out typing.NamedTuple! It has a really cool syntax with support for type hints: Python code:
Eela6 fucked around with this message at 03:04 on Apr 17, 2017 |
|
# ¿ Apr 17, 2017 01:39 |
Boris Galerkin posted:I need to be able to inject a function into a class when the object gets created Why do you need to? Metaclasses are the preferred way of customizing classes, but most of the time you think you need them (or the even deeper magic of method injection) they are not necessary. To quote Tim Peters Tim Peters posted:[Metaclasses] are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why) Eela6 fucked around with this message at 05:06 on Apr 18, 2017 |
|
# ¿ Apr 18, 2017 05:04 |
You don't need to do any special magic to create a method and attach it to an object. So long as the first parameter is self it should 'just work'. Phoneposting so i cant go into more detail, but if you want an example I do so in my easyrepr implementation from earlier in this thread.
|
|
# ¿ Apr 18, 2017 19:00 |
SurgicalOntologist posted:That's what I thought would happen (it would get self passed automatically), but I just checked and Boris is right, it doesn't. Huh. This is the first time in a while I've been surprised by Python. I guess you do need to do that thing with the types module (or use the first method I suggested). Ah, I see! Thank you for the correction. It's a technical point but an important one.
|
|
# ¿ Apr 18, 2017 20:48 |
Boris Galerkin posted:Thanks for all the help and discussion. I don't want to sound dismissive, but it looks like the original method I proposed works and Dex's solution is more or less the same, so I'm just going to stick with what I have. You took a good look at alternative suggestions and then made an informed decision. That's not dismissive in the least. You brought up an interesting question in an area that's relatively niche/complex within python. If nothing else, I learned a lot from the discussion! Just because Metaclasses and method injection are the wrong solution most of the time doesn't mean they're the wrong solution all of the time.
|
|
# ¿ Apr 20, 2017 17:52 |
Epsilon Plus posted:I've tried to figure out super() in Python a few times and everything I look at makes no goddamn sense; do you ? have any good resources covering it? I don't mind doing regular old DI for the project I'm doing in Python it would be nice to properly understand how super() works. Super() considered super by Raymond Hettinger is a good resource. Raymond did this as talk at PyCon a couple years back so it's available as a video presentation too. Raymond is a fantastic presenter. As always, Fluent Python covers this in some detail.
|
|
# ¿ Apr 21, 2017 02:40 |
The best thing you can do to get basic fluency is to take a project you've written before in another language and re-inplement it in Python.
|
|
# ¿ Apr 22, 2017 22:57 |
baka kaba posted:pathlib is cool, Path.iterdir() is not because it's not sorted. Is there a natural sort I'm missing (where 'file2' < 'file10') or do I need to screw around parsing numbers from filenames here pathlib Paths are hashable and orderable (and therefore sortable) so you can just call sorted! EX: code:
Python code:
code:
Death Zebra, can you give us the full stack trace? Eela6 fucked around with this message at 19:50 on Apr 24, 2017 |
|
# ¿ Apr 24, 2017 19:46 |
Ordering is lexigrapic according to the path of the file. It works 'like you would expect' - file0 < file1 < file9. More specifically, Lexigraphic ordering of strings and paths works more or less as follows: Note that Python code:
EDIT: Oh, I see, your files aren't left-padded with zeros! I'm dumb. You can fix this by re-labeling the files. I'll have a solution up in a jiffy. Eela6 fucked around with this message at 20:32 on Apr 24, 2017 |
|
# ¿ Apr 24, 2017 20:01 |
baka kaba posted:Badly, I was using sorted() until I realised my data was out of order, tracked it down to the files coming in all file1, file10, file11. That's why I was hoping a natural sort was lurking in the standard library This is kind of an overwrought solution but it should work just fine. I'm sure a REGEX wizard can do this in three lines if not less. Python code:
Python code:
code:
Eela6 fucked around with this message at 21:14 on Apr 24, 2017 |
|
# ¿ Apr 24, 2017 21:07 |
ynohtna posted:Here's my common snippet to convert an iterable into natural sort order: Ooh, this one is nice.
|
|
# ¿ Apr 25, 2017 00:26 |
Cingulate posted:Crank it up a notch. Mods?
|
|
# ¿ Apr 27, 2017 06:46 |
QuarkJets posted:Probably execution is supposed to stop at that point, once the error is raised? Definitely throw a raise at the end of that except, if so A catch of Exception (or worse yet, BaseException) without a re-raise is a huge red flag.
|
|
# ¿ May 9, 2017 23:09 |
Hi Python goons! PyCon starts next week. I will be in Portland, OR for it. Anyone else going?
|
|
# ¿ May 14, 2017 16:30 |
|
|
# ¿ Apr 29, 2024 12:00 |
LochNessMonster posted:So I've been messing around with Python for a few months but I feel I'm stuck at a level slightly above complete beginner. I know how to work with lists/dicts/tuples and create loops/conditions. You actually want to know two things: 0. How to write pythonic code; Solution: Read Fluent Python. It is by far the best intermediate-level book I know of. You don't have to read it cover to cover; read the first few chapters and then skip around to stuff that interests you. As you learn more, you can go back to the more advanced topics. Plus, it's an excellent reference. 1. How to organize your code in general. Solution: this is a little tougher! I would recommend Clean Code by Robert C. Martin. This is the best book I know of on the topic. It's about Java, but the concepts are universal. Honestly, though, it's just going to take a lot of practice. Eela6 fucked around with this message at 14:51 on Jun 1, 2017 |
|
# ¿ Jun 1, 2017 14:45 |