Identifier and Naming convention in python

Python Keywords:

                                                            Keywords are reserved words for defining the syntax and structure of the Python language. Hence, you can not use them as identifier when naming variables, functions, objects, classes, and similar items or processes.

In python there are 33 keywords and avoid using them as identifier to avoid errors or exceptions:




Python Identifier:

                    An identifier is a name given to a variable, class, function, string, list, dictionary, module, and other objects. It  differentiate one entity from another.

Rules for writting Identifier:

1. Identifier cab be combination of any lower and upper letter(a-z, A-Z), digits(0-9) and underscore(_).
examples : Python, Python, _python,my_var, var9 etc..
2. Identifier cannot start with digit.
example:  9var -----> not a valid identifier.
                var_1 ----> valid identifier
3. Keywords cannot be used as identifiers.
example: raise =1 <-- Invalid identifier
4. Identifier may not contain special symbols like !, @, #, $, % etc
 example:  var# = 1 is not a valid identifier
5. Identifier can be of any length.

while declaring identifier you should avoid using the letters “O” (uppercase), “l” (lowercase letter l), or “I” (uppercase letter I)
as a single letter identifier as they may cause unnecessary confusion with the numbers 0
(zero) and 1 (one) in some fonts.


Class identifier:

                 Class identifier may be a CamelCase name. It consist a name of two or more words which all start in capital letters and are joined together without underscores or spaces.
Examples: MyNewWord, HennoL
         
Abbreviations in CamelCase names should be capitalized.
Example: HTTPError.
You can not use keywords as identifier. However, you may use a trailing underscore to
distinguish the name from a keyword.
Example : class_   <---- class identifier whereas class is a keyword by adding trailing underscore it can be used as identifier.

Naming Global Variables :

                                                                        A global variable name should be written in lowercase. A global variable name consisting of two or more words should be separated by an underscore.

def func():
    print(s)
s = "I love Mumbai in the summer!"
func()

I love Mumbai in the summer!

Variable s is defined as the string before we call the function func(). The only statement in func() is the “print s” statement. As there is no local s, the value from the global s will be used.

Naming Classes:

                                            Use UpperCaseCamelCase convention while naming a class. Generally, built-in classes are written in lowercase.
In some cases, if the class is callable (allows you to use round parenthesis) and has proper documentation, then you can name them like functions.
Exception classes normally end in “Error”.

Example-
class Z:
    pass

x = Z()
print(type(x))
<class '__main__.Z'>

Naming Instance Variables:

                                                                                              An underscore should separate instance variables consisting of several words. Variable
    names should be written in lower case. A non-public instance variable identifier starts with one underscore. An instance name that requires mangling starts with two underscores.
        Mangling : Using a double underscore prefix for a class object will “mangle” the attribute, meaning the attribute
name will be modified to avoid naming collisions with attributes from other classes, specifically subclasses.

Naming Modules and Packages:

                                                                                    Modules names should be all in lower case. There names should be short one-word names. But multiple words may be used if required for better readability. And separated by a single underscore.

Naming Functions:

                                                    function's name should consist of letters in lowercase. When using multiple words as function name, they should be separated by underscores to enhance readability.
Keyword def mark the header of the fuction.
A colon (:) to mark the end of the function header.

def merge(list1,list2):
'''merge(list1,list2) returns a list consisting of the original list1
along with any elements of list2 which were not already in list 1'''
    newlist = list1[:]
    for i in list2:
        if i not in newlist:
            newlist.append(i)
           
    return newlist

>>> one = [7,2,9,4,32]
>>> two = [8,2,9,32,4,66]
>>> print merge(one,two)
[7, 2, 9, 4, 32, 8, 32, 66]
>>> print one
[7, 2, 9, 4, 32]

Naming Arguments:

                                                            Always use the word “self” as the first argument in an instance method and “cls” as the first argument in a class method. Generally preferable to use a single trailing underscore over an abbreviation or name.

def greet(name, msg):
    """This function greets to
    the person with the provided message"""
    print("Hello", name + ', ' + msg)

greet("Rohit", "Good evening!")
Hello Rohit, Good evening!

>>> greet("Rohit")    # only one argument
TypeError: greet() missing 1 required positional argument: 'msg'

>>> greet()    # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

Naming Constants:

                                                Constants are written in all uppercase letters with underscores to separate multiple-word names.
Examples: MAX_SIZE


Comments

Post a Comment

Popular posts from this blog

C program that contains a string XOR each character in this string with 0 ,127

Queue in Data Structure(DS)

Implementation of stack Using Array