Write Clean, Professional, Maintainable, Quality Code in Python

Bad code can work. But if it’s buggy, messy and difficult to maintain, it can eventually break a project, a development team or even an entire company. The necessity to write clean, professional and maintainable code is obvious and is getting more important nowadays as projects grow, more people become involved in development, and more projects go open source.

In today’s world projects are huge, with dozens and hundreds of people working on the same code base. Early detection of possible problems in code plays a huge role in helping developers write clean, professional, high-quality code that will be understood by others. Luckily, there are a number of tools that allow Python developers to analyse their code against errors and possible perils. These include pyflakes, pylint, pep8, and others. The problem, however, is that many developers use them after the code is already written, just to check what can be improved. A much more sound approach is, as with Continuous Integration, to find problems early and write clean code from the very beginning. This is where IDEs come in with their code intelligence.

What distinguishes a good IDE from good text editors? By definition, an IDE tightly integrates a range of development tools tuned to work with each other seamlessly. Unlike text editors, even superior ones like Vim or Sublime Text, a good IDE intimately understands your code and its flows. While some IDE functionality can be enjoyed in a text editor by installing third-party plugins, these plugins are not guaranteed to work smoothly as they don’t interact with each other. They do their highly-tailored job, but without communicating with other subsystems. An IDE with its core collects data from different subsystems, effectively transfers this data to other subsystems and reuses it whenever is possible. Consequently, it provides code intelligence with refactoring abilities, code navigation, automatic code fixes, testing assistance, smart code autocompletion and ultimately suggestions to keep your code maintainable and of a good quality.

PyCharm is one of the most intelligent Python development products on the market today. It has a lot of specially selected tools, tuned and tested to work with each other: an advanced editor derived from IntelliJ Platform, a debugger with the ability to collect runtime type statistics, many unique code inspections which work on the fly, and lots more. Any PyCharm user can benefit from using it for their development.

The ultimate goal of any development tool is not only to speed up your development, but more importantly, to keep your code under control, in a consistent state. This is applicable to any project, but is most valuable when you have a team or simply some large project that must stay maintainable. Or when you have coding standards to adhere to. Or when you just want to get unified and standardized code as output that you want to share with others.

A key benefit you get from PyCharm is being able to write clean, professional and maintainable code from the early development stages. It proactively monitors your code state as you type, checking it against numerous inspections for code style violations rules and sophisticated traps that are not obvious but potentially can break your application. As a result, you can prevent possible problems, rather than having to troubleshoot them later. You start to form a development practice where you get instant feedback right as you’re coding. This saves time on bug-fixing and, in the end, allows your team to develop cohesive software more rapidly.

dangerous

Let me highlight some of the features in PyCharm that can help you consistently hold your code to a high quality standard.

Code Style violations

The very first feature I need to describe is basic code style checking. Python is very sensitive to code formatting by its nature. The very basic requirement to keep your code in a consistent state is to preserve the same formatting style across all over your project. PyCharm has a special subsystem that controls code style and inspects different code style violations. It watches for code formatting rules like tabs and indents, spaces, wrapping and braces, blank lines etc. If there are any code style violations, PyCharm will highlight them in the code:

codestylehighlight

PyCharm has special automatic quick-fixes for errors that it finds, so in this case you can quickly apply the “Reformat file” fix and PyCharm will make the file conforming to project code style settings:

reformatfile

These code style settings are highly customizable, and you can set your own code style scheme for each desired language, per project:

codestylesetings

You can also save your settings and apply them to other projects or share with your peers.

Simple formatting is not enough! Here come customizable inspections

PyCharm has a huge number of code inspections for various projects, languages and frameworks. Those inspections checks your code against different errors. PyCharm finds different types of errors such as unresolved references, unused variables and imports, deprecated functions, classes and modules, PEP8, package requirements, and many many others. You can review the list of available inspections in Settings | Inspections. The checklist is comparable to pylint functionality, and you’ll notice it’s very comprehensive. Pylint is still the definitive tool for Python code analysis, but PyCharm’s advantage is that it checks your code on the fly. PyCharm has many settings to control those inspections: enable and disable, set the severity of inspections, edit the behavior of alerts, etc.:

inspections

You can also create and share customized inspections profiles. That is very helpful when you want to apply the same set of checks against different projects, or if you want your entire team to develop in the same style.

Manageable code inspections scopes

PyCharm provides flexibility for managing code quality with inspections scopes. Inspection scopes settings let you set and manage different rules for individual project parts:

scopes

Code analysis reports

With PyCharm, you can check your code against different inspection profiles, both standard and customized, and get a detailed report for further investigations. Lots of actions can be performed with code analysis reports as well:

inspections_reports

You can export the results to HTML or XML for further investigation. In that way PyCharm works similar to pylint.

PEP 8 integration

Among a number of different inspections, PyCharm supports the PEP 8 standard by integration of the official pep8.py tool. This tool is being run in the background and you get an instant results with the highlights of PEP 8 violations in the code editor. Like with other inspections, you can change the severity of PEP 8, edit highlighting and other settings.

pep8

Python code compatibility checks

Living in a world with two contending versions of Python 2 and 3, it’s very important to check your code for compatibility against different versions of Python. PyCharm has a special inspection that helps you do that:

compatibility

Quick-fixes

OK, so PyCharm finds errors and warnings. What else? PyCharm doesn’t just alert you to potential problems, but helps you with suggestions to fix them in-place. When a problem is found at the line your caret is on, you’ll notice a red or yellow bulb next to it. Choose from the list of ways to fix the problem and apply the suggested fix in one click / keypress.

quickfixes

As you can see, PyCharm has a powerful and highly customizable toolset for code quality assurance. It checks your code on the fly and helps you eliminate problems early.

This article only scratched the surface of what PyCharm can really do. There are a lot more features in PyCharm that assist you with code quality for your projects. For more details on features mentioned in this article and to learn additional handy features like code auto-generation, type hinting and more, please consult the tutorial Code Quality Assistance Tips and Tricks, or How to make your code look pretty? available in our tutorial space among other useful tutorials about PyCharm.

All the described functionality is available in PyCharm Community Edition, which is free and open source! Feel free to use it to improve your code quality and speed up the development process for your professionally developed projects!

Develop with Pleasure!

About Dmitry Filippov

Product Marketing Manager at JetBrains
This entry was posted in Cool Feature, Tutorial. Bookmark the permalink.

23 Responses to Write Clean, Professional, Maintainable, Quality Code in Python

  1. you-suck-emacs-rocks says:

    If you are not using emacs, then you fail.

  2. where_to_download? says:

    so where do i get this vim plugin? vim.org search doesn’t show any matching results for “pycharm”

  3. Alex Jerez says:

    The latest release of PyCharm looks excellent. I use vim with python-mode for development, but I’m looking forward to trying this out.

  4. Javier says:

    I interestingly began to read this article until I stumbled the part where it really is a PyCharm commercial…. :-/

    • RobertX says:

      Wow, an article on a PyCharm blog is about….PyCharm and how it helps you code better. Wow.

    • Ben says:

      Yeah. I definitely clicked in looking for tips on Python coding, rather than a gorilla advertisement for an IDE.

      FYI A similar FOSS alternative is PyDev/Liclipse.

    • Yury V. Zaytsev says:

      So, in an official PyCharm product team company blog of JetBrains, the makers of IDEA, you unexpectedly stumbled upon a commercial for their product? Surprise!!!

    • Ivan says:

      U can use free community edition of PyCharm.
      But personal license price is not so much and allow U use IDE on all you computers.

  5. Shosa says:

    What you mention is nothing more than the standard tools like pep8, pyflakes or the combi of both flake8 already do with some additional repackaging/rearranging.
    As for “automatic” fixing and “auto-completion” as means to “Write Clean, Professional, Maintainable, Quality Code in Python”, IMHO those are the very things which make IDE’s to the very anti-pattern. It leads to laziness and changes outside proper understanding of their implications. How many times did I see a project architecturally distorted and overall poorly designed, because an IDE makes it possible to have such a thing “run”. People new to the tools have the power of the IDE on their side to continue without internalizing the way things are usually done in Python. Had that experience with a particular Java programmer once who insisted on using a IDE, he ended up just continuing to write Java in Python. The result was mildly put; off-putting. This is IMHO no isolated case.

    What you call a “Simple Text Editor” with all its limitations in regards to global understanding of the software project at hand, are exactly what forces you to a sound and beautiful software design in the first place. Otherwise it “just does not work”. Let alone the positive impact on the habits of the individual developer.

    So basically my take on your post;
    * Your statement contradicts the very nature of an IDE.
    * IDE’s make most people lazy and complacent. The result is a mess.
    * The dynamicity of a language is inversely proportional to the usefulness of an IDE. PyCharm does not govern this, and seems not to have overcome the classical limitations any other IDE displays when it comes to Python.
    * You are selling a product in this post, not a solution. Dare say, even the source of further problems.

    But overall charming… it just is not what you state it does in that killer title.

    Best regards,
    ~Shosa

    • RobertX says:

      Your points are all wrong and your own personal opinion is just that.

    • Vasili Syrakis says:

      PyCharm has actually improved my ability to make readable and efficient code.
      The inspections provide helpful explanations and have helped me understand Python better.

      An IDE does not make a person lazy. That person just happens to be lazy in the first place.

  6. wollywog says:

    Shosa, while I agree with a lot of what you said – especially as it relates to the nature of this article, which really doesn’t ‘teach’ anything except to download PyCharm – I disagree with your statements on the nature of IDEs, or at least the universality of your statements.

    While I think that there is something to be gained from doing things the ‘hard’ and rigorous way, I also think that IDEs can be extremely helpful for people who might not have the coding background that you apparently do. Having spent the last two years learning Python (the first language that I have achieved anything resembling ‘fluency’ in) as a means to various ends, I have found that PyCharm’s constant reminders and formatting hints have helped me produce much more elegant code than I was when using generic code editors.

    What people who have achieved an understanding of a language tend to forget is that aside from not knowing the answers, many newcomers do not understand the QUESTIONS to ask. So while it is entirely possible to sit down and read hundreds of thousands of forum postings on the proper formatting of multi-line comments in Python and integrate the net result into the way you are writing code, it is not something that a newcomer would necessarily know to pursue. If every line of every example was formatted properly and the reasoning behind such formatting was made clear every time in a way that made sense to every reader, then maybe it would be possible to just stumble upon an understanding of these sorts of errors and intuitively grasp what the language is ‘trying’ to do. I don’t find that the learning materials (outside of the actual docs, perhaps) are consistent enough to make that leap without researching (and knowing to research!) sundry, esoteric topics.

    I believe that there is a lot to be gained from syntax checks like those available in PyCharm. I know a lot about Python formatting that was not covered explicitly in the examples, guides, and forum posts that I read when getting started, and a lot of it I owe to making those little warning/suggestion tick-marks disappear in PyCharm. PyCharm has not made me lazy; it’s made me increasingly structured and committed to writing readable, maintainable code. When it hints that I’ve done something unusual and I don’t know why, I research it and sometimes find out that there’s a standard that I was unaware of or misinterpreted.

    That’s not being lazy – that’s learning with guidance.

  7. Anton says:

    Are you plaining to integrate pycharm inspection to TeamCity?

  8. Pingback: Write Clean, Professional, Maintainable, Quality Code in Python | Blog

  9. James Kerns says:

    I’m shocked at all the hate generated by this post. PyCharm is a beautiful IDE that makes me, a non comp sci scientist, want to use Python. For comparison, examine Matlab’s IDE vs PyCharm and you’ll come racing back to PyCharm.

    Claims of laziness are completely founded. I am lazy enough to use an IDE. I’m also lazy enough to use a car instead of walking everywhere, and to use a dishwasher instead of washing by hand.

    Keep going guys! Oh, and work on a numpy array GUI =) http://youtrack.jetbrains.com/issue/PY-10956

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">