| « Back to Search | Reader Mode | Switch to Full Retro Site View | Links: Stay in Reader | Retro Mode: ON | Original » |
However, Python has conventions about naming functions that go beyond these rules. One of the core Python Enhancement Proposals, PEP 8 , defines Python's style guide, which includes naming conventions. According to PEP 8 style guidelines, Python functions should be named using lowercase letters and with an underscore separating words. This style is often referred to as snake case . For example, Function names should also describe the actions being performed by the function clearly and concisely whenever possible. For example, for a function that calculates the total value of an online order, You'll explore these conventions and best practices in more detail in the following sections of this tutorial. Remove adsWhat Case Should You Use for Python Function Names?Several character cases, like snake case and camel case , are used in programming for identifiers to name the various entities. Programming languages have their own preferences, so the right style for one language may not be suitable for another. Python functions are generally written in snake case . When you use this format, all the letters are lowercase, including the first letter, and you use an underscore to separate words. You don't need to use an underscore if the function name includes only one word. The following function names are examples of snake case:
Both function names include lowercase letters, and one of them has two English words separated by an underscore. You can also use the underscore at the beginning or end of a function name. However, there are conventions outlining when you should use the underscore in this way. You can use a single leading underscore , such as with A single trailing underscore is used by convention when you want to avoid a conflict with existing Python names or keywords. For example, you can't use the name import for a function since You can also use a single trailing underscore if you wish to reuse the name of a built-in function or other object. For example, if you want to define a function that you'd like to call max , you can name your function Unlike the case with the keyword Double leading underscores are also used for attributes in classes. This notation invokes name mangling , which makes it harder for a user to access the attribute and prevents subclasses from accessing them. You'll read more about name mangling and attributes with double leading underscores later. Snake case is the preferred option for Python function names as outlined in PEP 8 . However, Python doesn't enforce its use and you may occasionally see Python functions named using camel case . Camel case , which is also referred to as lower camel case or mixed case, is popular in other programming languages. An example of camel case is Often, this style is used in Python by programmers who mainly code in other languages or in modules that have historically always used this case, such as the It's best to avoid using camel case for Python functions unless you're working on an existing code base that already uses this format. Why Should You Use Descriptive Names for Python Function Names?Readability is a key principle of modern programming and plays an important role in Python. You can make your code more readable by choosing function names that clearly describe the function's purpose. Consider the following function: Language: Python
You can determine what action this function performs if you're familiar with the However, the function name Now, look at this version of the same function: Language: Python
The intended purpose of this function is clearer in this version since the function name
The function and parameter names help you understand the code in the function's body. The function calls confirm that The parameter name This naming convention enables you to use functions as higher-level building blocks since the name tells you what it does, and you don't need to be concerned about how the function is implemented at a lower level. A function can be used as a black box once it's defined and tested, and a descriptive name is an important part of the function's documentation. You also want to avoid unnecessarily long names. Long names make the code more verbose and lead to longer lines, which may require scrolling or splitting into multiple lines. Therefore, Programmers have different preferences, and you may also need to adapt to naming practices within teams or in existing code bases you work on. There isn't just one right answer when deciding how to name a function. Here's another example. You write a function that finds the number of vowels in a text. You could name your function However, others may prefer a shorter, sufficiently readable version: So, why are short names still used if they're not recommended? In the early days of programming, short names were required since code had to be punched on cards, and the available memory and line-length were limited. Single-letter variable and function names were common, and these practices can still be seen in some present-day code. However, there's no longer a need for short names since the limitations from the early years are not relevant today, and modern editors have helpful tools such as name autocompletion. Also, since today's computers can deal with higher demands, programs are longer and more complex than in the early days of computing. As a result, code readability has become more important over the years, and choosing function names is a tool programmers can use to make code easier to read and maintain. Readable code can also minimize the likelihood of bugs. Remove adsWhat Are the Naming Conventions for Methods?Methods are functions defined within a class. The naming convention for methods is identical to regular functions. Therefore, you should also write method names using snake case, and they should describe the method's actions. You learned earlier in this tutorial that there are conventions around when to use underscores at the beginning or end of a name. The most common use of underscores at either end of a method name is associated with special methods . These are methods called by Python to perform specific operations on an object. Special method names include two leading underscores and two trailing underscores, such as with To demonstrate a number of methods and their names, you can create a bank_account.py
The class includes two special methods, which both have two leading underscores and two trailing underscores as part of their names:
Keep in mind that you can't choose the names for special methods since they're an integral part of the Python language. You also shouldn't use names with two leading underscores and two trailing underscores for any methods other than Python's special methods. You can add more methods to this class: Language: Python Filename:bank_account.py
The first method you add is
Like function names, method names should be a verb or start with a verb to highlight the action they perform whenever appropriate. Note: In Python, it's often preferred to use attributes like The next method you define is This method doesn't have any code yet. It should perform the following actions:
You could define two methods called You want to use this method within the class definition, but you don't want to make it part of the interface for this class. A user of this class doesn't need to call this method. To state your intention about how this method should be used, you can add a single leading underscore to the method name: Language: Python Filename:bank_account.py
This notation doesn't prevent someone using the class from calling this method directly. You can confirm this in a REPL session: Language: Python
Some Python tools will use the single leading underscore convention to assist you when programming. For example, here are the autocomplete suggestions provided by PyCharm, a popular Python IDE : The suggestions show the two data attributes, The method you defined with a leading underscore, You also need a method to deduct funds from the account and to write the code in bank_account.py
The Note: Python has a convention for attribute names with two leading underscores and, at most, one trailing underscore. Name mangling occurs with these attributes. You can read more about the two leading underscores convention and name mangling in the Single and Double Underscores in Python Names tutorial. You add two more methods to this class: Language: Python Filename:bank_account.py
The You can test this class in a new REPL session: Language: Python
When you use the class to create an instance, you can perform all the actions using instance methods that don't have leading underscores. The first What's the Difference Between Naming Functions, Variables, and Classes?You've learned about the conventions for naming Python functions and how you usually choose descriptive names with lowercase characters and underscores to separate words. How do these rules and guidelines compare with the conventions for naming variables and classes? The naming rules that Python enforces apply to all names, including the names of variables and classes. Therefore, variable and class names can't start with a digit and can't have ASCII punctuation marks other than the underscore. Python raises a In addition to these rules that Python enforces, there are conventions for naming variables and classes. Variables follow a similar convention as function names and should be named using lowercase characters with underscores separating words. Here are some examples:
It's preferable to avoid single-letter variable names or short abbreviations unless these are acceptable within specific domains. An example of an exception to this guideline is when single-letter variables are used in mathematical applications, where the letters are commonly used in mathematics and science. Variable names should describe the data they represent to make the code more readable. Often, the variable name is a noun. When the name represents a constant value , it's conventional to use uppercase characters, such as Class names use a different case. The first letter of each word is capitalized, and there are no underscores separating words. Programmers refer to this case using different terms. Here are some of them:
All these names refer to the same format. When a class name includes a single word, only the first letter is capitalized. Here are some examples of class names:
Note that most of the built-in core data types don't follow this convention. The names This case is also used for the names of type variables when using type checking , such as ConclusionIn this tutorial, you learned how to choose Python function names that follow the core naming rules and the conventions defined by Python's style guide. Function names contain all lowercase letters. When function names contain more than one English word, you use underscores to connect these words. Function names should also be descriptive to make the code more readable and easier to maintain. Python doesn't enforce these naming guidelines. However, most programmers follow these conventions for consistency and to improve readability. You can keep these conventions in mind the next time you need to choose a name for a new function. Get Your Code: Click here to download the free sample code that you'll use as you learn how to choose Python function names. Take the Quiz: Test your knowledge with our interactive "How Do You Choose Python Function Names?" quiz. You'll receive a score upon completion to help you track your learning progress: Interactive Quiz How Do You Choose Python Function Names?In this quiz, you'll test your understanding of how to choose Python function names. By working through this quiz, you'll revisit the rules and conventions for naming Python functions and why they're important for writing Pythonic code. Liked it (thumbs up) Disliked it (thumbs down)🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. About Stephen Gruppetta Stephen obtained a PhD in physics and worked as a physicist in academia for over a decade before becoming a Python educator. He's constantly looking for simple ways to explain complex things in Python. » More about StephenEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Brenda Geir Arne Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Keep Learning |