Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started following PEP-8 strictly, because I thought I should at least try it before just picking and choosing the things I like.
However, there seems to be a conflict. They strongly recommend limiting each line to 79 characters, yet they strongly recommend that method and variable names use_underscores_between_words.
On a typical line, where you're nested in a
class ->
method ->
loop ->
conditional ->
my_var_name += do_some_function(some_parameter, another_parameter)
you already have 79 - 16 = 63 characters to work with, and you're wasting 6 on just underscores. So the line above is already too long and it's actually pretty short.
It seems productivity would suffer if I have to count characters so often, or split a rudimentary line like this onto several lines.
I understand that now it says "if your team agrees, use 99", but it seems this should be the standard, or rather that camelCaseVars should be the standard since we like short lines so much.
My issue with coding standards-compliant Python is that I can't seem to write any code without either using cryptic names, or violating the line length or naming convention. I could post my code here to show you my specific issues, but my example above represents the issue I'm having with my code.
Which ideal is less important? Clear names, short lines, or using_underscores?
UPDATE: while no one actually suggested this, I'm getting the feeling that using less descriptive / function and variable names is actually what is tacitly being asked of me. I know people would say "of course not, just wrap your lines", but in practice, it seems to be a mix of "use very short names" and "wrap lines", but stick to 80.
I think that's what people have done, but I think on the business project level, where productivity is king, teams have just thrown out that rule and jumped to 120. For now, I think I'll just stick to 79 with lots of (imho) ugly line wraps, and feel comforted by the thought of me being able to view 2 files side by side on a small monitor.
Python Zen says:
Flat is better than nested.
Therefore consider decreasing a nesting of your code by code decomposition - make the code less nested by extracting some parts into separate methods or functions. And you'll always have enough horizontal space in your editor.
Update
For the nested loops with conditions you can also decrease the nesting level by the decomposition.
For example you can change this code:
class MyClass(BaseClass):
def my_method():
for item in self.my_collection:
if item.numeric_property % 2:
self.my_property = item.other_property + item.age * self.my_coefficient
self.do_other_stuff()
to this one:
class MyClass(BaseClass):
def my_method():
"""People see what happen because of clear names"""
self.process_my_collection()
self.do_other_stuff()
def process_my_collection():
"""People see what happen because of clear names.
They probably don't even need to read your math from
process_my_collection_item(item) at all.
And you make the code more flat as well.
"""
for item in self.my_collection:
self.process_my_collection_item(item)
def process_my_collection_item(item):
"""The most people don't need to read these calculations every time
since they just know it's working and tested
but they'd like to work with methods above frequently:
"""
if not item.numeric_property % 2:
return
self.my_property = item.other_property + item.age * self.my_coefficient
As you can see I divided one method to a few simple operations and made it less nested.
Your goal should be to write code that is easy to understand.
Generally speaking, adhering to PEP8 gets you a step closer to that goal. If the nature of your code and/or your team is such that camelcase works better, by all means use camelcase.
That being said, if you think it is import to save six characters for what you perceive is a typical line, maybe that is telling you that your typical lines are nested too deep, and there's a better solution than to change naming conventions.
Use underscores, it's what everyone expects.
-However- the 79 character limit is one of the more easily set aside recommendations. My team uses pep8 with 119 character lines, but the vast majority of our lines are under 80 characters anyway.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Why in this millennium should Python PEP-8 specify a maximum line length of 79 characters?
Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator.
Are there any (legitimately) good reasons for adhering to 79 characters in this age?
Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.
Readability is also one of the reasons for enforced line indentation.
I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.
As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.
I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.
I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.
I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.
I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.
Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.
Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.
Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Imagine I am defining a function (in this case it is in Python), which does some simple manipulations with a string and returns a string too. I can, for example, define it in two different ways, that will produce the same output:
def signature(s):
"""Returns the signature of this string.
Signature is a string that contains all of the letters in order.
s: str
"""
1) return ''.join(sorted(list(s)))
2) t = list(s)
t.sort()
t = ''.join(t)
return t
Is there a benefit to stick to any of these two ways in the long run? I have seen different developers practising both methods, but is it just a matter of taste?
Would appreciate any feedback to help me establish better programming habits.
Simply put, it's up to your project style guide.
This isn't a performance question, as both these statements take the same time to run, benchmark it if you'd like. Therefore, the difference is in syntax and syntax alone; and when choosing your syntax, it's best to conform to your styleguide.
If you're working in a corporate production setting, you could look around your project to find best practices. If you're working alone, you can decide which one you like better. Either way, consistency is the way to go when aiming for sustainable readability on your code.
The first statement reminds me personally of Linq syntax, which aims make your code readable as is by chaining functions together. The second statement would be easier for a beginner to read, as the different functions are separated in their own lines.
As John specified in your comments, return ''.join(sorted(s)) would suffice for what you're trying to do, and it's likely one of the shortest ways to implement this code.
If you want to read more about different style guides and creating your own, I'd recommend further reading about linters.
There is a basic canon hidden in the this module. Execute
import this
to get it printed:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
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.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
See https://www.python.org/dev/peps/pep-0020/
Your example seems to fall under
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
and would lead me to return ''.join(sorted(s)) because list(s) is not needed as strings are iterables and can be fed into sorted() as is.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm going to be teaching some year 9 and 10 students Python soon and thought it would be cool to do some Project Euler type challenges with them. The first problem seems doable by them, but I think some of the others may be a bit over their head, or not require enough programming.
If anyone has a place to find some easy programming problems, or can think of any, can they please let me know.
edit: By year 9 and 10 I mean that they have been in school for 9 or 10 years. So about 13, 14, and 15 type age. Sorry for the confusion!
Oh I remember something I was taught in school! My IT teacher created a class in python which attributes created a mathematical sequence. The goal was to guess the formula behind this sequence using only python. Obviously, you couldn't look at the file with class, only import it in python. Maybe there's more math than programming here, but to solve this, students will have to learn how variables, namespaces (to find the variables), loops (to print those variables), and classes (which store those variables) work in python and this is more or less everything you need to know at first, in my opinion.
Ah, good times. We also used to play "hide and seek" in shell on IT lessons: the teacher would hide a file somewhere and leave some clues scattered around, and we had to find that file using text environment on linux :)
Get the right number :
The program chooses a random value betwen 1 an 100 then you have to guess.
It tells you if you are above or below.
My first scholar contact with programming really left a mark on me ;) The teacher provided us with a gui containing a sort of 2-d checkered board (let's pretend it was 20x20 cells). One of the cells contained a 'robot' and the programming interface basically exposed 3 methods: move forward, turn left, and check if the cell directly in front of the robot is a wall or open space. The game was then to 'program the robot' (teaching basic logic and loop constructs) to do all sorts of tasks like pass through every cell in the board. Later on, methods were added to the interface (to the original 3 methods) and 'objects' (not OOP, but .. other states the cells could occupy than just wall or empty) were added to the game. In the end the goals were for example for the robot to 'pick up' car parts and bring them to a 'car factory'. It was very nice IMHO to view programming as a game with 'scores' (least amount of cells required to achieve objective in this case) and I really promote Gamification http://en.wikipedia.org/wiki/Gamification in any school environment.
Cheers
Not sure how long you have to teach this, but Udacity's cs101 class has some pretty cool problems and starts from a pretty simple level. The course is free, and you may find some of the problems useful stand alone if you don't have time for the whole thing.
Finally if you run out of ideas for meaningful projects that are easy enough / quick enough in Python or decide to find something easier for part of the class then consider using Scratch, this is a fun visual programming language from MIT which allows you to use the constructs such as variables, loops, conditions etc. without worrying about syntax. This makes it nice and easy to create basic games / animations.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
The community reviewed whether to reopen this question 11 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
In "The Zen of Python", by Tim Peters, the sentence "Complex is better than complicated" confused me. Can anyone give a more detailed explanation or an example?
although complex and complicated sound alike, they do not mean the same in this context.
The Zen therefore says: It is okay to build very complex applications, as long as the need for it is reasonable.
To give an example:
counter = 0
while counter < 5:
print counter
counter += 1
The code is very easy to understand. It is not complex. However, it is complicated. You do not need to manually perform most of the steps above.
for i in xrange(5):
print i
This code is more complex than the above example. But: knowing the documentation of ´xrange´ you can understand it by a single glance. Many steps are hidden behind an easy-to-use-interface.
As processes grow bigger, the gap between complicated and complex gets wider and wider.
A general rule of thumb is to follow the other principles of the Zen of Python:
If it is hard to explain, it is not a good idea.
If it's easy to explain, it might be a good idea.
Complex: Does a lot. Usually unavoidable.
Complicated: Difficult to understand.
I like this quote (source):
A complex person is like an iPod. That
is to say that they are consistent,
straightforward and ‘user friendly’
while also being rather sophisticated.
Unlike the complicated person,
interacting with a complex person does
not require special knowledge of their
complicated ways-because their ways
are not complicated. When mistakes are
made, they tend to be very forgiving
because they understand that people
are imperfect. In short, they are
mature, sensible human beings.
and this one (source):
An Airbus A380 is complicated. A
jellyfish is complex. The Paris Metro
network is complicated. How people use
it is complex. Your skeleton is
complicated. You are complex. A
building is complicated. A city is
complex.
Some more articles on this:
Simple vs. Complicated vs. Complex vs. Chaotic
More on Complex versus Complicated
i haven't read this book.
complex is in my opinion a solution that might be not easy to understand but is writen in simple and logic code.
complicated is a solution that might be simple (or complex) but is written in code which is not easy to understand because there are no patterns or logic in it and no proper metaphors and naming.
Complicated systems are highly coupled and therefore fragile.
Complex systems are made of simple parts operating together to create complex emergent behavior. While the emergent behaviors may still be a challenge, the individual parts can be isolated, studied, and debugged. Individual parts can be removed and reused.
I comment more on this topic and provide examples on my blog
For "complicated", the difficult thing is on the surface. (You description is complicated.)
For "complex", the difficult thing is under the table. (A car is complex.)
Just as shown by EinLama's examples.
According to Pro Python third edition:
For the sake of this guideline, most situations tend to take the following view of
the two terms:
• Complex: Made up of many interconnected parts
• Complicated: So complex as to be difficult to understand
So in the face of an interface that requires a large number of things to keep track of,
it’s even more important to retain as much simplicity as possible. This can take the form
of consolidating methods onto a smaller number of objects, perhaps grouping objects
into more logical arrangements or even simply making sure to use names that make
sense without having to dig into the code to understand them.
So you as the book said, you need to make your code and file more organized and use most readble names to define variables/funtions as you can.
Actually, the best answer accepted is more likely to describe the upper rule:
Simple is better than complex.
Here is the snippet example of "Simple is better than complex." from the book:
if value is not None and value != ":
if value:
Obviously, the second line is simpler than first one and more easy to munipulate, and more likely with the best answer example code.
Complicated: Need a lot of brain juice (your internal CPU) to solve. But once you solved it, you know it is right. Solving a math problem is complicated. Once done, easy for you to do it a second time. But difficult again for your friend.
Complex: Need a lot of intuition to solve (your accumulated experience). And once you choose a way, you cannot be sure this was the best one. Human relations are complex. Doing it again a second time will still be challenging for you. But someone following your path (reading your code...) can follow you easily.
Algorithms aim to solve complicated problems.
Machine learning aims to find answers to complex problems.
Algorithms are predictable. Deep Learning raises explainability questions on why the computer has decided to select that specific answer.
So now it is your time to answer: was your question complex or complicated?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to come up with a good coding problem to ask interview candidates to solve with Python.
They'll have an hour to work on the problem, with an IDE and access to documentation (we don't care what people have memorized).
I'm not looking for a tough algorithmic problem - there are other sections of the interview where we do that kind of thing. The point of this section is to sit and watch them actually write code. So it should be something that makes them use just the data structures which are the everyday tools of the application developer - lists, hashtables (dictionaries in Python), etc, to solve a quasi-realistic task. They shouldn't be blocked completely if they can't think of something really clever.
We have a problem which we use for Java coding tests, which involves reading a file and doing a little processing on the contents. It works well with candidates who are familiar with Java (or even C++). But we're running into a number of candidates who just don't know Java or C++ or C# or anything like that, but do know Python or Ruby. Which shouldn't exclude them, but leaves us with a dilemma: On the one hand, we don't learn much from watching someone struggle with the basics of a totally unfamiliar language. On the other hand, the problem we use for Java turns out to be pretty trivial in Python (or Ruby, etc) - anyone halfway competent can do it in 15 minutes. So, I'm trying to come up with something better.
Surprisingly, Google doesn't show me anyone doing something like this, unless I'm just too dumb to enter the obvious search term. The best idea I've come up with involves scheduling workers to time slots, but it's maybe a little too open-ended. Have you run into a good example? Or a bad one? Or do you just have an idea?
I've asked candidates to write code to implement bowling scoring before, which is readily comprehensible but contains enough wrinkles that most people have to iterate their approach a couple times to cover all the edge cases.
A lot of the problems at http://www.streamtech.nl/site/problem+set, which are taken from ACM competitions, are also suitable for your use. I used them to familiarize myself with python syntax and language features. A lot amount to straightforward application of standard data structures; some are more focused on algorithmic issues. If you sort through them I'm sure you'll find several that fit your needs.
I can recommend to you Checkio.org
You can always just give them a few more questions on top of the Java one, like ask them to do the Java task, then ask them to define a class, then ask them to do FizzBuzz. That should be about as rigorous as your Java task.
Don't be afraid to ask a series of questions. Maybe you can even ask them to write a few one-liners to make sure they get the finer points of Python (write a list comprehension, how do you define a lambda, etc.)
Here's a question I answered on SO recently that might be the start of something suitable:
Given a string "O João foi almoçar :)
.", split it into a list of words.
You must strip all punctuation except
for emoticons. Result for example:
['O','João', 'foi', 'almoçar', ':)']
I've tidied up the question a bit. See the original linked above along with my answer. It tests a number of things, and there are different ways of tackling the problem. They can also get a half-solution out that first disregards the emoticons and punctuation aspect. Just finding the emoticons is another sub-problem that can be solved separately. And so on...
You could extend it to asking about emoticons adjacent to other punctuation, adjacent emoticons, overlapping emoticons, defining emoticons in :) form but also searching for those of the form :-). You could also turn it into a frequency count problem instead of just splitting to somewhat line up with your Java question.
I also suggest searching through the python+interview-questions questions posted on SO. There are some good ones, and you may even want to broaden your search to skim all interview-questions posts if you have time.
I don't know about Python specifically, but I found that interview questions which involve recursion are a very effective filter. I have asked candidates to produce all the permutations of a string (and think about how to test it), and I have been asked to pseudo-code the Longest Common Subsequence.