Anyway, I think somewhere (maybe in the 2.2 "welcome to generators" doc that never got updated but is still linked somewhere from the current docs, like the 2.3 MRO docs) it says that while 0: yield is the officially recommended way to force a generator function. Using while False: instead of while 0: is an improvement, but yield None instead of yield, I have no idea why they did that.
If you return a generator (rather than a non-generator iterator), the only things I can think of off-hand are performance things (e.g., your frame isn't kept alive if you return a generator, unless the generator you return is a closure, but on the other hand there's no extra function-call cost).
I can't find it right now, but I remember reading that, while using isinstance per se is not bad, pythonic code avoids scenarios where it is necessary. Is that so?
Yes, in Python, the general rule of thumb is that duck typing is best, inheritance relationships next best, explicit isinstance calls only when necessary, and type(x) is… checks only for really important micro-optimizations.
I have a lot of friends who complain about not seeing their types in python and not knowing what to do because of it but I don't really experience it much
other than the fact that official python documentation leaves much to be desired and really should list available methods etc more easily IMO
So I assume the difference is that my code style for python rarely needs to consider type directly
@IljaEverilä This question looks pretty good, though it's very old and most answers are outdated. There's a nice collection of ideas, and if you add an answer about type annotations on local variables, it'll be a good fit
I love flexible dynamic typing, like Python and Smalltalk. I also love powerful static typing, like Rust and Haskell. But most of the people I see complaining about dynamic typing in Python are people who use weakly-typed languages like C and Java, or dynamic-but-faking-it languages like Go, so I have no idea how to even make sense of their complaints.
I have a coworker who can go on for half an hour about how Go is great because "the compiler catches type errors" after we just spent 3 hours chasing down a null pointer exception that would have been impossible in a language with a real static type system or a 5-minute debug session in Python.
The only issue I have with Python's dynamic typing is that when reading unfamiliar Python code in a function, I'm not sure with what the class of an argument is.
@abarnert What does the code look like when you said, "inheritance relationships next best", in " duck typing is best, inheritance relationships next best"?
@Aran-Fey I'll try and find a better candidate. That question I linked is such a mess itself that it'd require quite a bit of editing, while trying not to change its spirit, and would be so much easier just to cv as dupe.
@SeanFrancisN.Ballais Usually, the class doesn't matter; it should be obvious what the object is supposed to do. For example, you often don't care whether you get a file, a list of strings, or an iterator that generates strings on the fly. Even if the guy who originally wrote the function was thinking of it as taking a file, I can still pass it a genexpr that transforms a list of strings.
@SeanFrancisN.Ballais But sometimes, you need a function that does different things with different types. Sometimes that inherently means type-switching—like a function that can take either a file-like iterable-of-strings, or a filename to open and read a file. But sometimes it's something you can express as with a base type and subclasses that do different things for the same methods.
Like asyncio(or Twisted) protocols: they have to have a suite of related methods that all work together in an appropriate way, so it makes sense to expect them to be subtypes of some Protocol type.
@IAmBatman Unless you need to work with older versions of Python, between to use d: MyClass = None.
Then yeah, comments. Although when I've used Mypy for porting a mess of 2.7 code to 3.x (really the only thing I've found it useful for…), I mostly only annotate parameters, not locals.
I use annotations quite a bit in 3.x code when they make something clearer or more readable, but, oddly, I rarely run Mypy on it.
Can someone explain to me why this question ranks getting down voted? https://stackoverflow.com/questions/50326886/why-can-format-not-be-used-seperately-from-the-declaration
I realize the over-site was a simple, but it doesn't seem it warrants getting down voted and I'd like to avoid future "bad questions".
my point is that people probably thought that it reflects a fundamental misunderstanding with how python works, and for some people that's enough for a downvote. Or they thought that thoroughly reading a tutorial should cover this. I can only guess.
Well, I just tried to install Pyre and it needs to update my OCaml and OPAM… and OPAM needs Python 2.7, and it will only use the Brew 2.7, not the Apple one. So, in order to install a tool for Python 3, I have to build Python 2.7.
On a side note... there's mixed opinions about using the line continuation stuff... in your case it looks (imho) slightly nicer if you rely on adjacent strings being concatenated...eg:
Oops! I didn't notice that West, the [['a','b','c'],['d','e','f'],['g','h','i']] guy had commented on my answer. I'm a little concerned that he doesn't know how to convert a list of strings into a list of lists. If he doesn't know easy stuff like that, then those Algorithm X functions are going to be a total mystery.
@JonClements That was actually copy/paste code from a SO question relating to the topic prior to posting my question. I had been playing with this silly problem for almost an hour because it didn't make sense that it didn't work and I was missing the reassignment. The actual code wasn't used and looks nothing like that. The test code was much simpler. :)
@Dave no worries... I upvoted anyway as I don't think it hurts to have a post thinking that .format works in place when it's tripped you up and str.replace has tripped plenty of others up for exactly the same reason as well...
@abarnert I'm not comfortable saying that Python has dynamic typing. Sure, it looks like dynamic typing, if you think that Python names are variables. :) And although it's possible to change the type of a Python object apart from the ones that are defined in C), it's not exactly simple or obvious.
I am trying to create multiple instances of a Soda object using information from a file. The file is formatted like this Name,price,number
Mtn. Dew,1.00,10
Coke,1.50,8
Sprite,2.00,3
My code I have is this (this is a function within main()):
from Sodas import Soda
def fillMachine(filename) ...
@AndrasDeak I felt a bit mean DVing since the question is clear and the OP has gone to the trouble of posting relevant code. And this "feature" is disconcerting when it catches you unawares, since code in a function behaves differently to identical code in the global context. But it's a fairly common question, and you'd think that people would check a one page doc before asking on SO.
it seems we need a canonical for classmethods/staticmethods factory methods like from_string. Something whose title is more amenable to being located than:
Could someone explain to me the meaning of @classmethod and @staticmethod in python? I need to know the difference and the meaning.
As far as I understand, @classmethod tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that...
You can't have multiple constructors, but you can have multiple aptly-named factory methods.
class Document(object):
def __init__(self, whatever args you need):
"""Do not invoke directly. Use from_NNN methods."""
# Implementation is likely a mix of A and B approaches.
...
Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at ...
@Aran-Fey, Because the docs suggest None: "If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed."
I guess using None is probably faster because it avoids some function calls, but that's micro-optimization
How long do I have to wait for a dupe hammerer to respond to my "that's not a suitable dupe" complaint before I'm legally allowed to reopen the question?
@Aran-Fey Depends on how confident you are. If it's absolutely clear, then I'd comment + reopen. If there's some ambiguity comment + wait a few hours, I guess.
I'm a bit concerned about the variable variables canonical (stackoverflow.com/questions/1373164/…). The answer is great, but there's not a great explanation why it's so bad. One answer does a decent job but it's half way down and talks more about coding effort.
@AlphaRomeo Weird. I tested it (again) before I wrote that post. But I guess it's possible that Tkinter's been upgraded since I installed Python 3.6.0, which is the last time I updated Tkinter on my system.
95% of users will be fine if they follow the top few answers, and the skeptical 5% can be explicitly pointed to that one answer that explains why they shouldn't do that
@jpp Honestly, I like the fact that you have to scroll to see the getattr and globals answers. If you tell a n00b "this is bad because X", they'll think "I don't give a flying yam about X". Just tell them "use a dict" and everyone's happy.
@jpp It's not great, but it's better than it used to be. We deleted several of the worst answers. I'm not happy that Nadia's answer shows how to do it by man-handling globals(), but we can't really delete such a high-scoring answer.
I'm reading how to switch case and I did ok on 1 method, because I had to call 1 method but when I have to assignt it to a variable is that possible without putting it to method? I mean :
@Skizo-ozᴉʞS Yes, it's a little more efficient. But since your keys are small contiguous integers, why even bother with a dict? Just use a list of functions.
also.. If its not much to ask ... Can someone give me some tips on the code which I have written.. I mean it works but i dont think its good way of writing code.
@Anarach Im confused on the need for it all to be inside a for loop. But Ill let one of the other guys in the room take a look as they will be able to give you better pointers to start with. Also looks like in my testing you can use functions from a file inside a for loop. So not sure why yours isnt working yet
Do you get any errors? Looks like you would run into some variables being undefined but Im not sure without trying to run your code.
I would think, (keep in mind Im pretty green) that it would be better to call the function multiple times rather than define it. Not sure on the impact but I would assume there is.
that might work if someone has a good understanding of the basics, but Skizo seems to be still in the phase of learning the basics
if you're confronted with an advanced pattern you might find it easier to give up because it looks daunting, even though it would be easy to comprehend in a few smaller steps and some guidance
I think it's hard to come up with that solution unless you already know the basics. It's a "huh, I didn't know you could do that" sort of thing, I think
It is. And we already told Skizo the solution :) They just need to understand the gist of it in order to adapt to their own problem
looking at the original and my suggestion in the surrounding 10 messages should help understanding dispatch, or let them ask specific questions if it doesn't
and then it's just a matter of replacing the names with what their real code contains
at least that's my take on the matter
either way if Skizo gives up we can still give them the answer ;)