Questions tagged [pep8]
Coding conventions and style guidelines for Python. Not to be confused with the PEP/8 assembly language.
822
questions
1
vote
1
answer
34
views
Python SQLAlchemy 2.0 non required field types using dataclass_transform
I have just installed SQLAlchemy 2.0 on a new project and I am trying to make my models as type-safe as possible.
By using @typing_extensions.dataclass_transform, I have been able to achieve most of ...
0
votes
0
answers
27
views
How to disable autopep8 rule for entire file?
Say, I want to format following python file with autopep8:
## Double '#' at the start of this line will be removed due to E265/E266
# extra space after '=' will be removed due to E222
a = 1
But I ...
0
votes
1
answer
38
views
Why are PIL and its Image module capitalized? [closed]
PEP8 standard is for modules to be lower-case
PIL being a top-level module in all caps isn't so bad, but to name a module Image and then have a class in that module called Image seems unnecessarily ...
3
votes
3
answers
57
views
Does anything supercede PEP 8?
Trying to go from a script kiddie to a semi-respectable software engineer and need to learn how to write clean, digestible code. The book I'm reading pointed me towards PEP 8 - I know this is the ...
-2
votes
1
answer
27
views
flake8 & pycodestyle/pep8 not showing E721 errors
Versions
λ python --version
Python 3.10.6
λ flake8 --version
5.0.4 (mccabe: 0.7.0, pycodestyle: 2.9.1, pyflakes: 2.5.0) CPython 3.10.6 on Linux
# and on Windows
## Edit: after update
λ flake8 --...
-3
votes
1
answer
32
views
what is pep 8? How does it help in programming? What are the set of rules regarding that?
what is the Full form and what it is used for?
I was going through basics of python when I came across this term. what does it mean by maximum readability?
1
vote
1
answer
47
views
Phython: missing-function-docstring (pylance)
Im getting the message from pylace at my function. What to do?
def retangulo(larg, comp):
area = larg * comp
print(f'A área de um terreno {larg} x {comp} é {area}.')
docstringpylint(...
0
votes
2
answers
39
views
accessing python dict values with line-breaking (PEP-8) [duplicate]
I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode)
example:
class GoFirstSpider():
def __init__(...
-1
votes
1
answer
46
views
PEP-8 break up for loop
I am trying to figure out a way to break a long for loop to make it PEP-8 valid.
(I'm using flake8 vscode extension).
This is the code:
for result_row in soup.find_all('div', {"class": "...
-3
votes
1
answer
47
views
dict.get or list check, which is faster?
If I want to get a bot with an ID, which is faster between:
storage = {
'bots': [
{ 'id': 123, 'auth': '81792367' },
{ 'id': 345, 'auth': '86908472' },
{ 'id': 543, 'auth': ...
2
votes
2
answers
40
views
Pandas subset selection and Pep8
I am using Spyder IDE with code style warnings enabled.
Selecting a subset from a Pandas dataframe via df[df['Col1'].isna() == False] triggers the following code style warning.
The code analysis ...
0
votes
0
answers
52
views
Adding pep8-naming to VSCode
I am trying to get PEP8-naming working on my VSCode (Version: 1.72.2 (Universal)) without luck.
I have flake8, isort and mypy enabled in my code and this all works as expected. I have installed pep8-...
-1
votes
2
answers
48
views
elegant way to code if/elif/else statement
indepgroupl = ['numerical', 'categorical']
depgroupl = ["numerical", "categorical", "factors", "count"]
for i in indepgroupl:
for j in ...
1
vote
0
answers
111
views
Specific noqa doesn't seem work (PyCharm)?
In both cases:
print("test")
import cmprsk.cmprsk as cmprsk # noqa: E402
a = cmprsk.import_R
and
print("test")
import cmprsk.cmprsk as cmprsk # noqa: E501
a = cmprsk....
0
votes
1
answer
30
views
E501 line too long (Break up a Directory)
I have a function which effectively converts a file's contents to a UTF-8 format and writes it to a new file using os.system. It all works, no problems there. My issue is just when running pylama, I ...
0
votes
1
answer
26
views
How can I move a string with calculations and brackets according to PEP8
I have
spent_calories = ((cc1 * self.weight + (mean_speed * 2.0 // self.height) * cc2 * self.weight) * self.duration * H_IN_M)
and I need to translate part of the expression but a new line. I tried ...
-1
votes
1
answer
50
views
PEP8 best docstring practice when function has multiple different return [duplicate]
I have the following function:
def eg_fun(eg:int):
"""example function
"""
if eg > 2:
return 2, 4
else:
return 'no', None
In the ...
0
votes
3
answers
57
views
Python question about overridden/redifined imported function as Class method
In https://github.com/biopython/biopython/blob/518c4be6ae16f1e00bfd55781171da91282b340a/Bio/SeqUtils/ProtParam.py I have this importing statement:
from Bio.SeqUtils import molecular_weight
and then in ...
0
votes
1
answer
25
views
Why do maximum line lengths sometimes end with 9?
In some conventions, PEP-8 for example, I see maximum line widths recommended to be set to values ending with 9, such as 79, 99, 119. Why not rounded to 10, like 80, 100, 120?
I feel like it's an off-...
2
votes
1
answer
141
views
What's the 'cleanest' way to indent multiple function arguments considering pep8?
I am wondering what's the best way to format a function with multiple arguments.
Suppose I have a function with many arguments with potentially long argument names or default values such as for ...
0
votes
1
answer
119
views
Overusing default arguments in Python [closed]
The following function demonstrates a coworker's coding style:
def one_week_after(date=datetime.date(2011,3,8)):
return date+datetime.timedelta(days=7)
Every argument of every function they write ...
0
votes
0
answers
30
views
What is the correct way to write such a python.pandas code?
I'm really trying to learn PEP-8 standards. But they are very difficult for me when it comes to pandas. The proper length of a one line is 79 chars, but my command requires 533 characters, so I've ...
1
vote
0
answers
116
views
What is the correct way to alias pyspark.sql.functions? Is it import pyspark.sql.functions as F or as f?
I understand that according to PEP8 rules, we should import modules and packages using lower case letters. In that case, we should be importing using: import pyspark.sql.functions as f.
Package and ...
0
votes
0
answers
86
views
Is there a standard way to write on top of each python file which pycodestyle errors and warnings are ignored?
I have a python file and I have disabled some pycodestyles errors(in the code editor) like
pycodestyle: error E501 - line too long (111 > 79 characters)
Is there a standard way to add this info in ...
0
votes
0
answers
52
views
Best Autopep8 alternative in VS Code
Autopep8 is no longer being maintained. What is the best pep8 code auto format extension? Could the 'Trunk' extension be the answer?
2
votes
3
answers
305
views
Python: space before and after operators like =, +, -, etc
Following the PEP 8 rules for Python, you should use spaces before and after operators, for example, x = 1 + 2. I follow this convention, and I don't like it without spaces.
Currently, I'm working on ...
0
votes
0
answers
101
views
Enforce one function argument per line in Python
Currently, Flake8 permits having multiple parameters on a single line when defining a function. For example:
from typing import Any, Callable
def _some_default_function(x: Any) -> Any:
return ...
2
votes
2
answers
541
views
Run autopep8 on all python files except migrations doable?
Am wondering is there a way to run autopep8 command on all python files exept the migrations? To fix all pep8 errors.
Instead of doing the command
autopep8 --in-place --aggressive --aggressive <...
0
votes
0
answers
49
views
numpydoc: Can I omit the type declaration in the docstring when I use type hints?
When using type hints in the function signature, do I need to specify the parameter types in the docstring, too, if I were to comply with numpydoc style?
def add(a: float, b: int) -> float:
&...
-1
votes
1
answer
71
views
Python - Line too long, how can I break this? [closed]
I have this line of code:
self.order_total = self.lineitems.aggregate(Sum('lineitem_total'))['lineitem_total__sum'] or 0
It is too long for pep8 validation. I had a look at the docs (https://peps....
0
votes
0
answers
20
views
PyCharm Inspections: modify or add special exceptions [duplicate]
Problem: PyCharm Inspections is close, but I need to add a special exception, not disable it entirely
Motivating Example:
In my Python code, I have a personal style preference. Only in tests/*_test.py ...
4
votes
2
answers
508
views
Is underscore needed between the word and number in a variable name?
I have 2 variables, city1 and city2 as shown below:
city1 = "New York"
city2 = "Los Angeles"
According to Function and Variable Names in PEP 8 – Style Guide for Python Code, an ...
1
vote
0
answers
27
views
"import x" vs "from x import y" [duplicate]
I'm a complete newbie to Python and I would like to know which option is better.
I'm talking about using all package and access to its names by "." and using a specific name from a package ...
-1
votes
1
answer
98
views
Use of None and self keywords in method construction [duplicate]
I'm analyzing some old code that I've inherited, and I have a question about the use of "self" and "None" keywords, specifically in the following example:
def run(self) -> None:
...
0
votes
2
answers
50
views
Is using magic methods in high level Python code is allowed by PEP8?
Is using magic methods in high level Python code is allowed by PEP8 ? For example, does PEP8 allows for:
ab = {'a', 'b'}
ab.__len__()
?
I often write code in editors when it's much easier to write ...
1
vote
1
answer
126
views
PEP8 conformance for type annotated return types in overlength lines
I use Python's type annotations to specify the return type of a function. In this example the last line with the return type is to long.
def cut_by_row_keep_group(data: pandas.DataFrame,
...
0
votes
0
answers
73
views
Best practice creating pandas columns within a custom function
Assumed I have a pandas data frame and a notebook cell where I add a column:
df[col_3] = df[col1]+df[col2]
What is the best (most efficient, most pep8-like and/or simplest, most readable) way to ...
-2
votes
1
answer
3k
views
PEP8 "No newline at end of file"
I'm having trouble understanding what "No newline at end of file" means exactly.
I've got
if __name__ == "__main__":
app.run(
host=os.environ.get("IP", "...
2
votes
1
answer
651
views
Python black style discrepancy
I am using black to format my python code. I observed the following behavior. I admit that it is a very specific case but it goes on my nerves.
Let's suppose I have the following code:
@pytest.mark....
0
votes
0
answers
15
views
E501 line too long (92>79 characters) - spyder [duplicate]
I am using spyder.
I have this line of code which is inside a function and a for loop, so 8 white spaces of preceeding indentation.
df_BONDFV['FV_BID'] = df_BONDFV['2_MSG'].str.split('=').str[...
4
votes
1
answer
3k
views
How do I configure black to use different formatting rules for different file extensions?
I use black for format normal .py files as well as Jupyter Notebook files (.ipynb). For notebooks, I want a shorter line-length.
Is it possible to specify different formatting rules for different file ...
1
vote
1
answer
388
views
pep8 E501: line to long
My question is how do i rewrite this code smaller so i dont get an "Line too long (82 > 79 characters) (E501)" PEP8 error.
i tried:
if (gameBoard[0][0] == "X" and gameBoard[0][1]...
0
votes
2
answers
52
views
Python readibility of long statement
I have a call to a function which returns a lot of elements, and the way to respect PEP8 is to do the following, but I don't find it very readable:
colonne_dernier_attribut, ...
0
votes
1
answer
66
views
A Python function uses constants. When are they defined? What is the usual practice?
A Python function defines some "constant" variables to be more readable and robust. Let's write one example.
def definite_calculus(x, y):
"""This is a very specific ...
0
votes
1
answer
54
views
when using python logging.Formatter() can I use a pep8 style or does it have to be on one line
I'm learning how to use the python logging module and wanted to know if it's possible to split the code below so the variables are easily readable and identified:
formatter_f = logging.Formatter('%(...
1
vote
1
answer
90
views
Python line continuation of function with many returns
I'm working on a python code which has some functions that return many values as a tuple. I'm working on updating the line continuation to bring the line lengths down to a reasonable length. Is there ...
0
votes
1
answer
469
views
Python Annotate Two Exact Strings for Function Parameter
Say I have a function foo, that takes in a parameter a. I would like to annotate the function to indicate that a should only accept 2 strings - 'string1' and 'string2'
What I currently have is (python&...
4
votes
0
answers
415
views
Where to use camelCase in Python according to PEP 8?
Recently I have started working on machine learning with Python, however I'm very new to this language. I know that "Readability counts", so I have been trying to get myself familiar with ...
-3
votes
1
answer
962
views
Logic behind why python variables should be lowercase in functions but outside functions not necessarily
Is there any logic why it is acceptable to have variables with capital letters (e.g. myName = "Jason") inside if __name__ == "__main__": but not inside def main():?
EDIT : as ...
3
votes
2
answers
119
views
PEP 8: E128 sometimes requires spaces and sometimes does not
This post's answer suggests PEP 8: E128 requires spaces on the lines following the first one when they're all wrapped inside parentheses. However, with an if statement this doesn't seem to be the case....