python one-line if statement calling function if true - python

I'm using argparse.
def help():
parser.print_help()
sys.exit(0)
help() if (args.lock and args.unlock)
This gives me a syntax error. What is wrong with my if statement?

You are using a conditional expression: true_result if condition else false_result. A conditional expression requires an else part, because it has to produce a value; i.e. when the condition is false, there has to be an expression to produce the result in that case.
Don't use a conditional expression when all you want is a proper if statement:
if args.lock and args.unlock: help()

Related

How can I handle this PEP8 warning?

I have a two-line code like this:
if validated_data.get('is_shipped') == False: # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)
I am using Pycharm and the PEP8 check is on. So there is an underline below validated_data.get('is_shipped') == False which shows me Expression can be simplified. Replace boolean expression with ``not validated_data.get('is_shipped')`` . But, the truth is, I only want to run code in if statement when is_shipped is explicitly passed as False, and not when is_shipped is None. So, how can I handle this PEP8 check warning?
You hit the solution in your question: use the explicit is operator:
if validated_data.get('is_shipped') is False:
This makes your condition an explicit identity, rather than the "truthy" boolean evaluation.
Here x == False is equivalent to not x, and I don't know why do you want to only use x == False and PEP8 suggests that:
if not validated_data.get('is_shipped'): # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)

Raising errors in the context of python ternary operators

So let's say that I have all the necessary variables defined and I want to throw an error while assigning a variable with the conditional all in one line:
isTestData,isTrainingData,testData,trainingData=True,False,str,int
def whoops():
raise
a = testData() if isTestData else TrainingData() if isTrainingData else whoops()
I'm wondering if there is some builtin function or syntax with raise that I'm not getting... Is defining whoops necessary to get this behavior with a one liner?
The basic syntax of ternary operator(one liner) in python is:
<expr1> if <conditional_expr> else <expr2>
Which requires all the entities enclosed in <> to be an expression.
Note:
Expressions can only contain identifiers, operators and literals.
Statements are everything that can make a line/lines of python code.
Its important to note that all the expressions are statements but
not vice-versa.
In your case, you can't use raise directly in ternary operator(one liner) because it makes a statement.

How to run a function in a single line if statement

I have this if statement i am trying to convert into a single line to be used in a terminal shell, but cannot seem to get it to work.
Essentially the code sort of looks like this:
import module
if condition:
module.runCustomMethod()
else:
pass
so i tried to write this like so:
import module;module.runCustomeMethod() if condition == True else pass
but no matter how i arrange it, it always gives me a syntax error. how would i go about running a method in this way?
What you're trying to do is pretty ugly, and there are better ways to do it, but…
import module;module.runCustomeMethod() if condition == True else pass
The problem here is that pass is a statement, and Python expressions can never contain statements.
Since you're not using the value of the expression, you can replace that pass with any expression that's harmless to evaluate:
import module;module.runCustomeMethod() if condition == True else None
Now there's no SyntaxError in your code. Although it's still not going to work, because that condition isn't defined anywhere, so it's just going to raise a NameError instead. But if that isn't a problem in your real code, this will work.
As a side note, you almost always just want if condition, not if condition == True. Only use that if you specifically only want to accept True and reject other truthy values like 1.
If you're doing this in a sh script, the cleanest solution is probably this:
python <<EOF
import module
if condition:
module.runCustomeMethod()
EOF

Ternary using pass keyword python

I have a working conditional statement:
if True:
pass
else:
continue
that I would like to turn it into a ternary expression:
pass if True else continue
However, Python does not allow this. Can anyone help?
Thanks!
pass and continue are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.
Nevertheless, you can still shorten the condition you brought like this:
if False: continue
Point 1: Are your sure your condition is right? Because if True will always be True and code will never go to else block.
Point 2: pass and continue are not expressions or values, but a action instead You can not use these is one line. Instead if you use, 3 if x else 4 <-- it will work
Ternary expression are used to compute values; neither pass nor continue are values.

What are valid statements inside a python eval()?

I have tried
eval('print("hello world")')
eval('return 0')
which are both incorrect. Why are they invalid and what rules should I follow when using eval() (other than as little as possible)?
In Python, eval() evaluates expressions (something that results in a value). Both print and return are defined as statements (however in Python 3, print is actually a function call, which is an expression). In the case of executing statements, you need to use the exec statement instead.
eval() is used to evaluate a value of a varaible as a variable.
example:
var="Hello World!"
code="var"
print eval(code)
output should be:
Hello World!

Categories