Python index like MATLAB's end/2 - python

MATLAB has a very convenient syntax for getting half of a list:
x(1:end/2)
The syntax I know for python to do this is
x[:len(x)/2]
This is fine in this case, because len(x) is easy to write. But this syntax becomes more than a pain when the name of the list is long (as they sometimes need to be), and even more so when there is a list of similar long names.
I know this is a real shot in the dark, but does python have any syntax option like MATLAB's?

There is no specialized syntax. If you need to do it a lot, write a function:
def half_list(l):
return l[:len(l)/2]

No, lists in python don't have the concept end( a somewhat similar concept is the index -1).
An easy (but not recommended) solution to your problem is:
l = longnamelist
l[:len(l)/2]
or to copy/paste the long name... (some editors have a shortcut for copying a word, this makes copy/paste of a long name very easy.)

Related

Is there something similar to __END__ of perl in python? [duplicate]

Am I correct in thinking that that Python doesn't have a direct equivalent for Perl's __END__?
print "Perl...\n";
__END__
End of code. I can put anything I want here.
One thought that occurred to me was to use a triple-quoted string. Is there a better way to achieve this in Python?
print "Python..."
"""
End of code. I can put anything I want here.
"""
The __END__ block in perl dates from a time when programmers had to work with data from the outside world and liked to keep examples of it in the program itself.
Hard to imagine I know.
It was useful for example if you had a moving target like a hardware log file with mutating messages due to firmware updates where you wanted to compare old and new versions of the line or keep notes not strictly related to the programs operations ("Code seems slow on day x of month every month") or as mentioned above a reference set of data to run the program against. Telcos are an example of an industry where this was a frequent requirement.
Lastly Python's cult like restrictiveness seems to have a real and tiresome effect on the mindset of its advocates, if your only response to a question is "Why would you want to that when you could do X?" when X is not as useful please keep quiet++.
The triple-quote form you suggested will still create a python string, whereas Perl's parser simply ignores anything after __END__. You can't write:
"""
I can put anything in here...
Anything!
"""
import os
os.system("rm -rf /")
Comments are more suitable in my opinion.
#__END__
#Whatever I write here will be ignored
#Woohoo !
What you're asking for does not exist.
Proof: http://www.mail-archive.com/python-list#python.org/msg156396.html
A simple solution is to escape any " as \" and do a normal multi line string -- see official docs: http://docs.python.org/tutorial/introduction.html#strings
( Also, atexit doesn't work: http://www.mail-archive.com/python-list#python.org/msg156364.html )
Hm, what about sys.exit(0) ? (assuming you do import sys above it, of course)
As to why it would useful, sometimes I sit down to do a substantial rewrite of something and want to mark my "good up to this point" place.
By using sys.exit(0) in a temporary manner, I know nothing below that point will get executed, therefore if there's a problem (e.g., server error) I know it had to be above that point.
I like it slightly better than commenting out the rest of the file, just because there are more chances to make a mistake and uncomment something (stray key press at beginning of line), and also because it seems better to insert 1 line (which will later be removed), than to modify X-many lines which will then have to be un-modified later.
But yeah, this is splitting hairs; commenting works great too... assuming your editor supports easily commenting out a region, of course; if not, sys.exit(0) all the way!
I use __END__ all the time for multiples of the reasons given. I've been doing it for so long now that I put it (usually preceded by an exit('0');), along with BEGIN {} / END{} routines, in by force-of-habit. It is a shame that Python doesn't have an equivalent, but I just comment-out the lines at the bottom: extraneous, but that's about what you get with one way to rule them all languages.
Python does not have a direct equivalent to this.
Why do you want it? It doesn't sound like a really great thing to have when there are more consistent ways like putting the text at the end as comments (that's how we include arbitrary text in Python source files. Triple quoted strings are for making multi-line strings, not for non-code-related text.)
Your editor should be able to make using many lines of comments easy for you.

Assignment with line continuation - Python

What is the preferred style for assigning values to variables when the variables are nested several levels deep, have fairly long names, and are being assigned fairly long values/expressions.
For example:
if this:
if that:
if here:
if there:
big_variable['big_key']['big_value'] = another_big_variable_that_pushes_line_over_79_characters
other_thing = something
The character-limit breaches are only in the single digits, but I want to clean up my code so that it follows PEP 8 as faithfully as possible. I've done the following, but I am still fairly new to python, and I'm not sure if it's the sort of thing that would make an experienced python programmer cringe:
if this:
if that:
if here:
if there:
big_variable['big_key']['big_value'] = \
another_big_variable_that_pushes_line_over_79_characters
other_thing = something
I get the impression that the line continuation character is somewhat taboo; but I can't really think of a cleaner solution than the one I have if I'm working with these big dictionaries and I can't make a clean break in the middle of the variable name.
I don't think there is any problem with line continuation in Python. But sometimes I prefer this:
big_variable['big_key']['big_value'] =(
another_big_variable_that_pushes_line_over_79_characters
)
It is useful in long expressions, too.
Line continuation is a bit taboo, but not the end of the world. We must always strive to write code such that some other programmer down the line can understand what we were doing.
Using the line continuation character \ is but one tool in our arsenal for achieving this goal of legibility.
Naming conventions are another issue. As da Vinci said "Simplicity is the ultimate sophistication." If you can make variable names small AND understandable, then you are sophisticated ;-). It's too easy to just say var1, var2, var3 etc. Coming up with good names is a skill, which takes effort.
Would you rather see a variable named ChiefExecutiveOfficerOfCompanysName or CEOName?
If you can combine if statements, then your code can become even more legible. Chances are, if you have some big hierarchy of if...else-if, then you're doing something wrong (this is a code smell). For example, you might change this:
if this:
if that:
if here:
if there:
Into this:
if this and that and here and there:
Or toss such gross logic into an evaluator function like so:
if EvaluateConditions(<args>):
Breaking code up into logical pieces, and putting those pieces into functions is another way to make things readable (we only have so much RAM, and we'd like to fit entire functions in it... humans aren't very good at paging)
Avoid copying and pasting code with slight changes by using parameterized functions, or some good design patterns

How can I create inline comments (without using backslash to continue on another line)?

Sorry in advance if this is something really easy, I'm very new to Python. This seems like it should be something very simple, but I am having a frustratingly hard time finding an answer online.
I'm writing a Python script in a preliminary, pseudo sort of fashion at the moment, and don't have all variable defined yet. I want to be able to have comments in the middle of a line to symbolize where the variable will go, but without commenting out the entire rest of the line to the right.
To visualize what I mean, this is how what I want is done in C/C++:
int some_variable = /*some_variable_that_doesnt_exist_yet*/ + an_existing_variable;
Basically I need to be able to comment the middle of a line without commenting the left or right sides of said comment. Is there any way to do this?
I know there's a way to do it like this (or something similar to this):
some_variable = #some_variable_that_doesnt_exist_yet
\+ an_existing_variable
...but I'd rather not do it that way if possible, just for ease of reading.
Unfortunately no. But you can always break things into multiple lines and comment in between. Parentheses come in handy for that.
my_var = (#some_variable +
some_other_var)
As with any language switch you will need to learn new habits that fit the features of the language. Python does not have the feature you desire, you could use some horrendous hack to force something that looks a bit similar in but I rather suggest you don't.
Some options are: document the TODO on a neighbouring line, perhaps using docstrings; don't sweat it and figure you'll add it later when your tests start requiring it; or use the fact that variables are lightweight and just create them with dummy values that leave the final calculation unchanged.
Inline comments do not exist in python.
The closest that I know of is the use of strings:
int some_variable = "some_variable_that_doesnt_exist_yet +" and an_existing_variable;
But that is terrible, and you should never do that.
You can't: According to the documentation, comments in Python start with the hash character (#) and extend to the end of the physical line. See An Informal Introduction to Python.
Why not use something like:
name = "Use this for something later"
:
:
name = 27
Python does not have inline or block comments like this. You can add a string (or any other expression), as suggested by others, but you will have to make sure to (consistently) replace all of those placeholders, which is extremely error prone
If it's only the value of the variable that is missing or unclear, and not the variable itself, how about this:
variable_to_be_defined = None # TODO define me!
some_other_variable = variable_to_be_defined + an_existing_variable

How to remove a range of bytes from a bytes object in python?

I am pretty new to python and sometimes things that seems pretty easy become lot complicated than expected
I am currently using a bytes buffer to read from a socket:
data = self.socket.recv(size)
and then process part of that buffer and need remove it
The thing is that I've been looking for a way to do that and didn't find a clue in the whole evening, I am pretty sure that I am not getting any fair results because of the words involved, or maybe it's not possible
I tried with "del" but got an error saying that it's not supported
Am I doing it the wrong way? Maybe someone could lead me the right way? :)
bytes doesn't support item deletion because it's immutable. To "modify" strings and string-like objects you need to take a copy, so to remove olddata[start:end] do:
newdata = olddata[:start] + olddata[end:]
Of course that's a fair amount of copying, not all of which is necessary, so you might prefer to rework your code a bit for performance. You could use bytearray (which is mutable). Or perhaps you could find a way to work through the buffer (using an index or iterating over its elements), instead of needing to shorten it after each step.
I think I found the proper way, just looking from another perspective:
self.data = self.data[Index:]
just copying what I need to itself again
Python'sstruct.unpackis often a viable alternative to slicing, and sometimes preferable. While that's unclear in this case, FWIW here's how it could be applied to your problem:
import struct
def remove_bytes(buffer, start, end):
fmt = '%ds %dx %ds' % (start, end-start, len(buffer)-end) # 3 way split
return b''.join(struct.unpack(fmt, buffer))
data = b'abcdefghijk'
print( remove_bytes(data, 2, 4) ) # b'abefghijk'

Python style for `chained` function calls

More and more we use chained function calls:
value = get_row_data(original_parameters).refine_data(leval=3).transfer_to_style_c()
It can be long. To save long line in code, which is prefered?
value = get_row_data(
original_parameters).refine_data(
leval=3).transfer_to_style_c()
or:
value = get_row_data(original_parameters)\
.refine_data(leval=3)\
.transfer_to_style_c()
I feel it good to use backslash \, and put .function to new line. This makes each function call has it own line, it's easy to read. But this sounds not preferred by many. And when code makes subtle errors, when it's hard to debug, I always start to worry it might be a space or something after the backslash (\).
To quote from the Python style guide:
Long lines can be broken over multiple lines by wrapping expressions
in parentheses. These should be used in preference to using a
backslash for line continuation. Make sure to indent the continued
line appropriately. The preferred place to break around a binary
operator is after the operator, not before it.
I tend to prefer the following, which eschews the non-recommended \ at the end of a line, thanks to an opening parenthesis:
value = (get_row_data(original_parameters)
.refine_data(level=3)
.transfer_to_style_c())
One advantage of this syntax is that each method call is on its own line.
A similar kind of \-less structure is also often useful with string literals, so that they don't go beyond the recommended 79 character per line limit:
message = ("This is a very long"
" one-line message put on many"
" source lines.")
This is a single string literal, which is created efficiently by the Python interpreter (this is much better than summing strings, which creates multiple strings in memory and copies them multiple times until the final string is obtained).
Python's code formatting is nice.
What about this option:
value = get_row_data(original_parameters,
).refine_data(leval=3,
).transfer_to_style_c()
Note that commas are redundant if there are no other parameters but I keep them to maintain consistency.
The not quoting my own preference (although see comments on your question:)) or alternatives answer to this is:
Stick to the style guidelines on any project you have already - if not stated, then keep as consistent as you can with the rest of the code base in style.
Otherwise, pick a style you like and stick with that - and let others know somehow that's how you'd appreciate chained function calls to be written if not reasonably readable on one-line (or however you wish to describe it).

Categories