So my work which had used older Python 2 is doing some code updating, anyways I am just learning python and am actually pretty new here, but what are the major syntax changes that went from 2-->3
Or is there really even that much syntax changes at all (like I know print got changed, but what else MAJOR)
Thanks
What’s New In Python 3.0:
http://docs.python.org/release/3.0.1/whatsnew/3.0.html
PEP: 3000 - Python 3000:
http://www.python.org/dev/peps/pep-3000/
PEP: 3099 - Things that will Not Change in Python 3000:
http://www.python.org/dev/peps/pep-3099/
Did you read this: Overview of Syntax Changes ?
The things you really notice in the syntax are the print statement, and the change in the exception syntax. 2to3 will handle all that.
That won't cause you any headaches though. Those generally come from the split of strings into binary bytes and Unicode strings. 2to3 doesn't handle that.
So the changes in syntax aren't really what you need to worry about. :)
Then there are some minor changes in the syntax, tons of small changes in various functionality and a huge reorganization of the standard library, most of which 2to3 handles.
There isn't any canonical summary of all changes afaik, although I've tried to make one in my new book. There may be some misses, but there you go.
You can't do much better than to read the documentation: http://docs.python.org/release/3.1.2/whatsnew/ covers all the changes pretty succienctly. Read the "What’s New In Python 3.0" section first for the main changes.
Related
Why would my code be an appropriate style for Java, but not for Python?
dct=getDictionary()
if dct.has_key(3):
invokeTriples(dct[3])
postProcessForTriples()
print("Done for triples")
if dct.has_key(7):
invokeSeptuples(dct[7])
postProcessForOthers()
print("All done!")
Personally, I don't see the problem. Can you explain what she meant by 'appropriate'? And maybe give me a good idea of the approach I should take to making it more appropriate?
python is entirely based on indentation so your if statements being indented is wrong (since they don't need to be)
You also have your dct indented by 1, your if 3 more and then your internals of if statement 4 more so your indentation is not consistent.
Finally your statement is pretty ambiguous since your code isn't actually styled for java.
here is how your code should probably be formatted
dct=getDictionary()
if dct.has_key(3):
invokeTriples(dct[3])
postProcessForTriples()
print("Done for triples")
if dct.has_key(7):
invokeSeptuples(dct[7])
postProcessForOthers()
print("All done!")
Haven't used python for like 4 years so might be wrong but pretty sure that's how it works
Without seeing the rest of the code it's hard to say exactly what the commenter might be referring to, but a few things stand out even without context:
The names don't follow standard Python conventions (e.g. snake_case)
Indentation is wonky (this would cause a runtime error in Python because indentation matters)
has_key is deprecated; I don't think I've ever seen it used in actual Python code.
A more "pythonic" version of this code might look like:
dct = get_dictionary()
if 3 in dct:
invoke_triples(dct[3])
post_process_triples()
print("Done for triples")
if 7 in dct:
invoke_septuples(dct[7])
post_process_others()
print("All done!")
Your exact question is, "Why would my code be an appropriate style for Java, but not for Python?"
So, if I as an instructor gave you that comment, I would mean that you have not complied with PEP 8 -- Style Guide for Python Code. And, as your instructor that is an expectation I have of your code.
Your professor is basically asking you to compare Java and Python. Since I am more experienced with java, I can tell you that you should compare the external libraries you used and calling if statement method.
If you have any further questions, feel free to ask.
I can't help you much because your question is generic
Have a good day!
I'm creating a project in Python that I intend to be able to run under both Python 2.7 and Python 3. I created a class where it became apparent that a nice piece of functionality was available under Python 3 using some Python 3-specific functionality. I don't believe I can replicate the same functionality in Python 2.7, and am not trying to do so. But I intend for the Python 3 app to perhaps have some additional functionality as a consequence.
Anyway, I was hoping that so long as the 2.7 app never called the functions that used the 3.x functionality I'd be okay. But, no, because the presence of the code generates a compile-time error in 2.7, so it spits the dummy despite the function never being called at runtime. And because of Python's lack of any compile-time guards I'm not entirely sure what the best solution is.
I guess I could create a subclass of MyClass, call it MyClass3, put it in another module and add the extra functions there. But that makes a lot of things substantially grubbier...many more split code paths based on sys.version_info, circular inclusion problems unless I do a lot of file-splitting and...(waves hand). It's a mess that way. But maybe it's the only option available?
EDIT:
The original question made reference to "yield from" which is why the answer below discusses it. But the original question was not actually looking for advice on how to get "yield from" working in 2.7, but the moderator seemed to THINK this was what the question was about and flagged it as a duplicate accordingly.
As it happened, just as I edited the question to focus it on the issue of organizing the project to avoid compile errors (and to remove references to "yield from"), an answer came in that referenced the yield from issue and turned out to be super-useful.
yield from was backported to Python 2.7 in the following module: yieldfrom.
There is also a SO question about implementing yield from functionality back to python 2 that you may find useful as well as a blog post on the same topic.
AFAIK, there is no official backport of the functionality so there is nothing like from __future__ import yieldfrom that one could expect (please correct if you know otherwise).
I've seen a number of questions like following one: What's the canonical way to check for type in Python?
And there's always someone answering something like: "The pythonic way of checking types is not checking them. and here goes another passage about duck typing."
First of all, I do understand pros of duck typing, and I do use it quite a lot. But is it really worth not to check types?
Suppose I have following code:
class DuckA:
def quack():
print("QuackA")
class DuckB:
def quack():
print("QuackB")
def duck_creator():
return DuckA()
def duck_client(duck):
duck.quack()
if __name__ is "__main__":
duck_client(DuckA()) #ok
duck_client(DuckB()) #ok
duck_client(duck_creator()) #ok
#totally fine untill you actually call it,
#which might be quite tricky to check in
#relatively big project
duck_client(duck_creator)
#one more typo, which is pretty hard to spot
#from first sight
duck_client(DuckB)
Yes, I do realize that we're all engineers and thus, we're supported to write adequate constructions, but what about all kinds of typos?
I'm a beginner in python, and I came from c/c++ crowd. Basically, all those answers involving duck typing sound to me somewhat like "if you don't want to spend hours in debugger, you just need to write code without errors".
So, python gurus, is there are any valid/pythonic/accepted techniques to overcome things like that?
I've seen all kinds of type checkers, which are good enough, although I don't like the idea of binding project to one of those ides.
Assertions in the beginning of the function do look quite promising from my point of view.
Any other ideas?
I think what you're looking for is Mypy, a static type checker for Python 2.7+/3.4+. It's the type checker that Python 3.6's annotation system is designed around, but they've been careful to make sure it can be used with older versions of Python. (In fact, part of the motivation for type hints in the first place is that Guido wanted to use Mypy to help guide upgrading a large codebase from 2.7 to 3.5.)
Of course you can't use 3.6 syntax in older versions of Python. In 3.5, parameters can be annotated, but not locals. In 3.4, annotations are limited. In 2.7, annotations don't exist at all.
If you read the docs, there are a few ways around this, but the basic idea is that you put all the annotations into comments in "public" code, while you write "typeshed" files full of out-of-line annotations for "internal" code.
The good news is that, because Mypy has been blessed by the core language, other static type checkers—and related tools like IDE indexers or deeper static analyzers—are adapting to do things the same way, so whatever you use for your 2.7 or 3.4 code is probably going to work with your favorite IDE or vim plugin or analyzer or whatever (if not today, then soon).
Python is a "whitespace delimited" language. However, the use of semicolons are allowed. For example, the following works, but it is frowned upon:
print("Hello!");
print("This is valid");
I've been using Python for several years now, and the only time I have ever used semicolons is in generating one-time command-line scripts with Python:
python -c "import inspect, mymodule; print(inspect.getfile(mymodule))"
Or adding code in comments on Stack Overflow (i.e., "you should try import os; print os.path.join(a,b)")
I also noticed in this answer to a similar question that the semicolon can also be used to make one line if blocks, as in
if x < y < z: print(x); print(y); print(z)
which is convenient for the two usage examples I gave (command-line scripts and comments).
The above examples are for communicating code in paragraph form or making short snippets, but not something I would expect in a production codebase.
Here is my question: in Python, is there ever a reason to use the semicolon in a production code? I imagine that they were added to the language solely for the reasons I have cited, but it’s always possible that Guido had a grander scheme in mind.
No opinions please; I'm looking either for examples from existing code where the semicolon was useful, or some kind of statement from the python docs or from Guido about the use of the semicolon.
PEP 8 is the official style guide and says:
Compound statements (multiple statements on the same line) are generally discouraged.
(See also the examples just after this in the PEP.)
While I don't agree with everything PEP 8 says, if you're looking for an authoritative source, that's it. You should use multi-statement lines only as a last resort. (python -c is a good example of such a last resort, because you have no way to use actual linebreaks in that case.)
I use semicolons in code all of the time. Our code folds across lines quite frequently, and a semicolon is a definitive assertion that a statement is ending.
output, errors, status = generate_output_with_errors_and_status(
first_monstrous_functional_argument(argument_one_to_argument
, argument_two_to_argument)
, second_argument);
See? They're quite helpful to readability.
Why is print a keyword in python and not a function?
Because Guido has decided that he made a mistake. :)
It has since been corrected: try Python 3, which dedicates a section of its release notes to describing the change to a function.
For the whole background, see PEP 3105 and the several links provided in its References section!
print was a statement in Python because it was a statement in ABC, the main inspiration for Python (although it was called WRITE there). That in turn probably had a statement instead of a function as it was a teaching language and as such inspired by basic. Python on the other hand, turned out to be more than a teaching language (although it's good for that too).
However, nowadays print is a function. Yes, in Python 2 as well, you can do
from __future__ import print_function
and you are all set. Works since Python 2.6.
It is now a function in Python 3.
The print statement in Python 2.x has some special syntax which would not be available for an ordinary function. For example you can use a trailing , to suppress the output of a final newline or you can use >> to redirect the output to a file. But all this wasn't convincing enough even to Guido van Rossum himself to keep it a statement -- he turned print into a function in Python 3.x.
An answer that draws from what I appreciate about the print statement, but not necessarily from the official Python history...
Python is, to some extent, a scripting language. Now, there are lots of definitions of "scripting language", but the one I'll use here is: a language designed for efficient use of short or interactive programs. Such languages tend to allow one-line programs without excessive boilerplate; make keyboard input easier (for instance, by avoiding excessive punctuation); and provide built-in syntax for common tasks (convenience at the possible expense of purity). In Python's case, printing a value is a very common thing to do, especially in interactive mode. Requiring print to be a function seems unnecessarily inconvenient here. There's a significantly lower risk of error with the special syntax that does the right thing 99% of the time.
I will throw in my thoughts on this:
In Python 2.x print is not a statement by mistake, or because printing to stdout is such a basic thing to do. Everything else is so thought-through or has at least understandable reasons that a mistake of that order would seem odd. If communicating with stdout would have been cosidered so basic, communicating with stdin would have to be just as important, yet input() is a function.
If you look at the list of reserved keywords and the list of statements which are not expressions, print clearly stands out which is another hint that there must be very specific reasons.
I think print had to be a statement and not an expression, to avoid a security breach in input(). Remember that input() in Python2 evaluates whatever the user types into stdin. If the user typed print a and a holds a list of all passwords, that would be quiet catastrophic.
Apparently, the ability of input() to evaluate expressions was considered more important than print being a normal built-in function.