I just started to use Python, and I know Python requires indentation, unlike any like language. But when I copy and paste a block of source code from other source, the code is mostly messy and I have to do the tab/backspace/home again and again for each line.
My current major setup are the Visual Studio Code with Python extension, and I use Emacs mainly for formatter and when I need to edit on Linux. https://www.emacswiki.org/emacs/ReformatBuffer
In old days, I can either use Visual Studio or Emacs to format the whole file in seconds.
Now with Python, you have to do it manually, which is a waste of time. I tried several IDEs (Spyder, etc) and packages (yapf). The idea beind IDE is that they help you when you type, but not trying to reindent everything.
For example, Spyder has a fix indentation function but it only fix tab/space. https://github.com/spyder-ide/spyder/issues/5565
While yapf only works when there is no indentation errors in the code.
My idea is that, unlike C/C++ and other language, there is a not an "end" in Python statement, so it is impossible for the tool to know whether the current line is the last of the block?
Because I used several languages and sometimes I just copy some from one to another and make some changes/replacements. For example (in IDL language)
boundary = read_binary(boundary_file, data_type = 4, data_dims = [ncolumn, nrow])
;;==========================================================================================================
nan_index = WHERE( boundary EQ missing_value, nan_count)
good_index = WHERE( boundary NE missing_value, good_count)
IF nan_count EQ 0 THEN BEGIN
RETURN
ENDIF ELSE BEGIN
boundary[ nan_index ] = 0
boundary[ good_index ] = 1
ENDELSE
:do something else
sFilename_rock = 'something'
And I want to translate to python after copy/paste, after the replacement:
def test
import numpy as np
sFilename_boundary = 'some_file'
ifs = open(sFilename_boundary, 'rb')
aBoundary = np.fromfile(ifs, '<f4')
aBoundary.shape = (nrow, ncolumn)
ifs.close()
#==========================================================================================================
nan_index = np.where(aBoundary == 1)
nan_count = len(nan_index)
if nan_count == 0 :
pass
else:
boundary[ nan_index ] = 0
boundary[ good_index ] = 1
#something else
sFilename_rock = 'something'
In this case, the whole code structure becomes nosense to me and I have to manually correct them one by one using yapf.
Please advise a solution, thanks.