What precautions should I take when naming a Python file?

Asked

Viewed 287 times

9

It is quite common to see problems generated because the Python file was named after a library.

# requests.py

import requests

response = requests.get(...)

This code snippet would generate the error:

Attributeerror: partially initialized module 'requests' has no attribute 'get'

So, what are all the precautions I should take when naming a Python file and why?

  • 4

    The idea of the question is to generate a canonical answer on the subject, given that many users have problems with it.

  • This problem is recurrent in both version 2 and 3?

  • @Wallacemaxters Yes, but error message changes.

2 answers

1

Click on this link, look for the theme "Naming Conventions" and you can clarify all your doubts about naming files (modules), classes, methods, variables, etc.

See: Python Naming Conventions - PEP8

Summary (copied):

Naming Conventions

Names to be avoided Never use 'l' (letter "L" lowercase), 'O' (letter "o" uppercase) or 'I' (letter "i" uppercase) as single character variable names.

In some fonts, these characters are indistinguishable from the numerals one (1) and zero (0). When tempted to use 'l', use 'L''.

ASCII compatibility The identifiers used in the standard library must be ASCII compliant, as described in the PEP 3131 policy section .

Package and module names Modules should have short names, all in lower case. Underscores can be used in the module name if it improves readability. Python packages should also have short names, all in lower case, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level interface (for example, more object oriented), the C/C++ module has an initial underline (for example, _socket).

Class names Class names should normally use the Capwords convention (Camelcase).

The naming convention for functions can be used in cases where the interface is documented and mainly used as a callable.

Note that there is a separate convention for embedded names: most embedded names are single words (or two words executed together), with the Capwords convention used only for exception names and embedded constants.

Names of type variables Type variable names entered in PEP 484 should normally use Capwords preferring short names: T, Anystr, Num. It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior accordingly.

Exception names Since the exceptions must be classes, the class nomenclature convention applies here. However, you should use the suffix "Error" in your exception names (if the exception really is an error).

Names of Global Variables (Hopefully these variables are intended for use in only one module) The conventions are almost the same as the functions. Modules that are designed for use through import * must use the mechanism all to avoid exporting global or using the oldest convention of prefixing global ones with an underscore (what you might want to do to indicate that global ones are "non-public module").

Function and variable names Function names should be in lower case letters, with words separated by underscores as needed to improve readability.

Variable names follow the same convention as function names.

Mixedcase is only allowed in contexts where this is already the predominant style (e.g., threading.py), to maintain backward compatibility.

Function and method arguments Always use self as the first argument for instance methods.

Always use cls for the first argument for class methods.

If the name of a function argument conflicts with a reserved keyword, it is usually best to attach a single end underline instead of using an abbreviation or spelling error. Therefore, class_ is better than clss. (Perhaps it is better to avoid these clashes using a synonym.)

Method names and instance variables Use function naming rules: lowercase with underline-separated words as needed to improve readability.

Use an initial underscore only for non-public methods and instance variables.

To avoid name conflicts with subclasses, use two initial underscores to invoke Python’s name mutilation rules.

Python confuses these names with the class name: if the Foo class has an attribute named __a, it cannot be accessed by Foo. __a. (A pushy user can still get access by calling Foo._Foo__a). Generally, double left underscores should be used only to avoid name conflicts with attributes in classes designed to be subclasses.

Note: there is some controversy over the use of __Names.

Constants Constants are usually defined at a module level and written in uppercase letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

I hope I’ve helped!

  • If you saw my comment in the question, you must have seen that the idea is to generate a canonical answer. If the link you mentioned answers completely, could you transcribe the content here? What if the name has blank spaces? It’s valid, but what are the implications? What if the file name is the same as another library? What happens?

  • I have made a summary of the recommendations, but those who wish to delve into the theme can consult the PEP8 recommendations. It is not very smart to repeat already published material that can be obtained just by clicking on a link.

0

When naming a file, that is, a module, the programmer should pay attention to the name itself and its form.

The name of the module SHOULD NOT have the same name as a library that will be used in your program by the fact described in the question.

Already the form of the name, must follow the PEP8 which says which module name should use lower case letter, be short and can use underscore (_) better read the name. On the other hand, package names follow the same rule, but the use of underscore is discouraged.

My first two cents. Know the libraries you will use in your project and NEVER use or name the modules and packages of your project with the name of these libraries.

HOWEVER, If you like to live dangerously, or juggle, perform acrobatics, or if you "don’t get along" (laughs), there’s always a way.

  1. Install the library requests (Pip install requests)
  2. Create a module (file) named after requests.py with the content below
import requests

response = requests.get("http://www.google.com)

print(responses)
  1. Run the file with python requests.py

You will receive a message as below:

Attributeerror: module 'requests' has no attribute 'get'

  1. Now get ready for your double carpal twist modifying the file to.
import importlib.util
import sys

module_name = "requests"
file_path = "/caminho/para/a/biblioteca/lib/python3.7/site-packages/requests/__init__.py"

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)

import requests

response = requests.get("http://www.google.com")

print(response)
  1. The answer will be

<Response [200]>

Note: Note that you can assign ANY name to module_name, soon if you make a triple mortal stretched with fifteen pirouettes you can do the below

import importlib.util
import sys

module_name = "QUALQUER"
file_path = "/caminho/para/a/biblioteca/lib/python3.7/site-packages/requests/__init__.py"

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)

import QUALQUER

response = QUALQUER.get("http://www.google.com")

print(response)
  1. The answer will be

<Response [200]>

If you were bold enough to try all this, congratulations. But I leave my last two cents

IF YOU WANT TO PLAY, THAT’S FINE... BUT PLEASE DON’T DO IT ON A REAL PROJECT

Browser other questions tagged

You are not signed in. Login or sign up in order to post.