How to change Pycharm auto-format? - python

I am using pycharm as my editor in python. One problem I have with it is that whenever I press autoformat (command+option+l), it causes some of my code lines to be broken into several lines. For example, this code:
percentage_optimal_arm = self.main_program.compute_percentage_optimal_arm(algorithm_instance.chosen_arm_history,self.k_value_of_arms_list)
breaks to this:
percentage_optimal_arm = self.main_program.compute_percentage_optimal_arm(
algorithm_instance.chosen_arm_history, self.k_value_of_arms_list)
This is really annoying as my screen is big enough to include the whole line and it makes my whole code looks ugly. Is there a way to increase the limit for breaking lines in pycharm?

Change Hard Wrap value at Settings > Editor > Code Style > Python
Default is 120 line spaces. Change it your desired value ex: 180

Related

Python function not working with seemingly correct string path

I have the following code (it changes the string/filepath, replacing the numbers at the end of the filename + the file extension, and replaces that with "#.exr")
I was doing it this way because the name can be typed in all kinds of ways, for example:
r_frame.003.exr (but also)
r_12_frame.03.exr
etc.
import pyseq
import re
#create render sequence list
selected_file = 'H:/test/r_frame1.exr'
without_extention = selected_file.replace(".exr", "")
my_regex_pattern = r"\d+\b"
sequence_name_with_replaced_number = re.sub(my_regex_pattern, "#.exr" ,without_extention)
mijn_sequences = fileseq.findSequencesOnDisk(sequence_name_with_replaced_number)
If I print the "sequence_name_with_replaced_number" value, this results in the console in:
'H:/test/r_frame#.exr'
When I use that variable inside that function like this:
mijn_sequences = fileseq.findSequencesOnDisk(sequence_name_with_replaced_number)
Then it does not work.
But when I manually replace that last line into:
mijn_sequences = fileseq.findSequencesOnDisk('H:/test/r_frame#.exr')
Then it works fine. (it's the seems like same value/string)
But this is not an viable option, the whole point of the code if to have the computer do this for thousands of frames.
Anybody any idea what might be the cause of this?
After this I will do simple for loop going trough al the files in that sequence. The reason I'm doing this workflow is to delete the numbers before the .exr file extensions and replace them with # signs. (but ognoring all the bumbers that are not at the end of the filename, hence that regex above. Again, the "sequence_name_with_replaced_number" variable seems ok in the console. It spits out: 'H:/test/r_frame#.exr' (that's what I need it to be)
I fixed it. the problem as stated was correct, every time I did a cut and past from the variable value in the console and treated it as manual input it worked.
Then I did a len() of both values, and there was a difference by 2! What happend? The console added the ''
But in the generated variable it had those baked in as extra letters. i fixed it by adding cleaned_sequence = sequence_name_with_replaced_number[1:-1] so 'H:/test/r_frame1.exr' (as the console showed me) was not the same as 'H:/test/r_frame1.exr' (what I inserted manually, because I added these marks, in the console there are showed automatically)

auto formatting python code to put parameters on same line

I really hate having spread out code, I am looking at a bunch of long code with parameters and arguments that are taking up way to much space.
def __init__(self,
network,
value_coef,
entropy_coef,
lr=None,
eps=None,
max_grad_norm=None,
conv=False):
Seems the guy who wrote it forced a 50 character line limit, I whole heartedly disagree. I would much rather it looked like this.
def __init__(self, network, value_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, conv=False):
There is also more nonsense like this which I would like to get rid of.
if self.conv:
grid_obs = rollouts.grid_obs[:-1]\
.view(-1, *rollouts.grid_obs.size()[2:])
dest_obs = rollouts.dest_obs[:-1]\
.view(-1, *rollouts.dest_obs.size()[2:])
obs = (grid_obs, dest_obs)
I am using VS code for the python and am an ex Intellij user and am missing all the built in code formatting code tools. Any one got any tips? I have been looking at autopep8 but it seems they are missing that functionality.
First, that's not 50 chars limit but 79 (as per pep8 conventions) and the way you would like to have it wouldn't be pep8 compliant as it's over 100 columns.
So, for the first snippet you can have it the way you don't like it (which is the correct way) or let your formatter know that you want the line-length to be over 79 columns.
For the second snippet you can remove the escape character \ and let the formatter do its job. I don't think it's 'nonsense' as you call it, but feel free to format it differently.
Autopep8 or Black both work very well and they are not missing any functionality.
Provided you installed one or the other, you have to add the proper key/value pair to your settings.json:
"python.formatting.provider": "autopep8" // (or "black")
If you use autopep8, for example, you can specify the line length you want (150 in your case) by adding this to your settings.json file:
"python.formatting.autopep8Args": [
"--line-length=150"
]
The same goes for black. In that case the value would be:
"python.formatting.blackArgs": [
"--line-length=150"
]
Formatting with that parameter will wrap your code to that amount.
You can format code with alt+shift+f (on a Mac) or right click on the editor and "Format Document".

VS Code for Python entering a new line when function call is long

I have a long time problem and it got me angry, so I will ask here. When I have a long function call in VS Code, it automatically enteres a new line somewhere in the parametres.
I have this on one line:
dict_file = os.path.join(path_converted,
'dictionary_'+filename+'.picklelongtestlongtestlongtestlongtestlongtest')
and it adds newLine behind "(path_converted, 'dictionary_' +" and the rest is written on the new line with some indention.
I have pretty big monitor, so I do not want to end these lines so early. Could I somehow turn it off in Settings? I am using FormatOnSave and it is pretty anoying.
Thank you for all answers :))
Andrew
There're the following two settings in VS Code:
"editor.wordWrap": Controls how lines should wrap.
"editor.wordWrapColumn": Controls the wrapping column of the editor when #editor.wordWrap# is wordWrapColumn or bounded.
So there're two solutions to your question, writing it in Settings.json:
Turn off the wordWrap:
"editor.wordWrap":"off",
Still keep wordWrap on but changing the code's max-length:
"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn":130,

Python: Preserve last line in console for specific output

I have a program that does lots of printing. For UX, I want to have the line at the bottom of the console screen always display the same piece of information - a summary of how many jobs are done, and how many remain X done, Y remaining (X and Y are constantly changing throughout the program's runtime).
I tried using curses, however, I only need to control one line and I could not find a way to limit curses's screen scope.
I also tried using blessings:
with t.location(0, t.height - 1):
print 'This is at the bottom.'
but it only worked when there wasn't enough stdout to reach the last line in the console.
I am using python 2.7
Try this:
def print_with_fixed_bottom(message):
fixed = 'This is at the bottom.'
print '\r{: <{width}}\n{}'.format(message, fixed, width=len(fixed)), # comma is important

Separate functions in python?

I'm not sure if function is the word I am looking for. In fact I don't really know what I'm saying but I have some code and it's not quite doing it what I want to. Basically I want to copy and paste this code I've got and email it to someone. I want them to be able to simply copy and paste it into their Terminal and perform calculations.:
## SCSAC.py
def round(x, base=5):
return int(base * round(float(x)/base))
option = 'yes'
while (option == 'yes'):
x=float(raw_input('How many accumulated orders do you have from retailers: '));
y=float(raw_input('How many units are in the inventory: '));
z=float(raw_input('How many accumulated orders have you placed: '));
print 'Place an order of %s units' % round(((x / 25 + y / 10 + z / 25) + 115));
print ;
option=raw_input("Do you wish to calculate another order? (Enter 'yes' to continue or any other key to quit):: ");
print
Whenever I type this code in line for line, it works perfectly. That's because there are basically 3 seperate things happening here.
I define "round" which rounds a value to the nearest 5.
I define an option to loop the program upon completion
I define the actual program, and in that I round the answer and conclude with the option to loop. You may notice 2 print's that don't print anything, but they are only there to have blank lines.
When I copy and paste it, I get a syntax error.
I am not a programmer and I have just been playing with this all day. I just want to know how I can edit this code so it is copy/paste-able and will run the way it is supposed to.
Try using IPython instead of the regular Python interpret at the shell. With IPython, you can type %cpaste, and then paste a whole chunk of code, which it will execute for you step by step, saving the intermediate variables into working memory.
If you insist on pasting it in the regular interpreter, then do it line by line, and take special care for the indentations. The indentations are usually where paste syntax errors come from.
Even better, use Emacs. Then you can just save the pasted code into a file, like test.py, type M-x shell, and then python test.py to quickly run it. Or, if you saved it to a file like test.py then in IPython you can also type %run "test.py" and it will run the code and again store intermediate variables into working memory.
If you're copy/pasting this after making changes more than once or twice, just save it to a file and run it like a script.
You can save the code in a file, and run it using Python.
You can add #!/usr/bin/env python to the beginning of the file, so it can run on *nix systems (if you have execute permission).
Or, you can do python SCSAC.py and run your code. This works on all systems (AFAIK). You can email the file to your person, and she can run it using Python. This seems to be the easiest way to do it.

Categories