2017-02-16 14 views
1

値が変数にNoneでない場合、返される関数を割り当てたい、または別の値、またはさらに別の値を割り当てる... 関数を一度呼びたいと思う。関数の呼び出しの連鎖から返された値を変数に代入する

私は現在、tryexcept TypeErrorを使用していますが、2つのオプションでしか動作せず、あまりクリーンではありません。

try: 
    value = someFunction()["content"] 
except KeyError: 
    value = someOtherFunction()["content"] 
+0

これは辞書ですよね? –

+0

@WillemVanOnsemはい、特にBeautifulSoupの結果 – david8

+0

は 'someFunction()[" content "]'実際には 'None'ですか、辞書には「content」フィールドはありませんか? – bouletta

答えて

0
value = someFunction()["content"] if ("content" in someFunction() and someFunction()["content"] != None) else someOtherFunction()["content"] 

なお、本someFunctionはあなたがonelinerにdでsomeFunction()を前に、

d = someFunction() 

を追加して、交換したい場合がありますので、潜在的に複数回呼び出されることになるだろうと

+0

まだKeyError例外が発生している可能性があります – Gigapalmer

+0

'value = someFunction()[content"] someFunctionの "content" else do_something' – Gigapalmer

+0

@Gigapalmerそれでは質問に対する私のコメント。もし、 "content"がdictで確実なら、 'KeyError'はありません。そうでなければ私は同意しました – bouletta

1

この作品のようなものはありますか? someFunctionが辞書を返す場合、戻り値の型dictであるため

def try_run(func_list, field, default_value): 
    for f in func_list: 
    try: 
     value = f()[field] 
     return value 
    except (TypeError, KeyError): 
     pass 
    return default_value 

try_run([someFunction, someOtherFunction], 'content', 'no content') 

Sample Code

0

、あなたは1行で同じ動作を実現するためにdict.getを使用することができ、

dict_object = someFunction() 
if 'content' in dict_object.keys() and dict_object['content'] is not None: 
    value = dict_object['content'] 
else: 
    value = someOtherFunction['content'] 
+0

ところで、最初の方が良い方法でした。 dict_object.keys()の '' content 'はdict_object'の '' content 'に比べて少し遅いですが、keys()を呼び出すとキーのリスト全体が返されるためです。 私はdict_object'の中で - > ''content'を好きです – Gigapalmer

3

を使用することができます次のとおりです。

value = someFunction().get("content", someOtherFunction()["content"]) 

あなたが質問に記載されている2つの値だけを扱っている場合は適用されます。複数の機能のチェーンを扱うためには、機能のリストを作成することととして返されるのdictオブジェクト内の「キー」をチェック:これは、外部ライブラリを必要と

my_functions = [func1, func2, func3] 

for func in my_functions: 
    returned_val = func() 
    if 'content' in returned_val: # checks for 'content' key in returned `dict` 
     value = returned_val['content'] 
     break 
1

いますが、使用することができiteration_utilities.first

from iteration_utilities import first 

# The logic that you want to execute for each function (it's the same for each function, right?) 
def doesnt_error(func): 
    try: 
     return func()['content'] 
    except (KeyError, TypeError): 
     return False 

# some sample functions 
func1 = lambda: None 
func2 = lambda: {} 
func3 = lambda: {'content': 'what?'} 

# A tuple containing all functions that should be tested. 
functions = (func1, func2, func3) 

# Get the first result of the predicate function 
# the `retpred`-argument ensures the function is only called once. 
value = first(functions, pred=doesnt_error, retpred=True) 

1これは私が書かれているサードパーティのライブラリからである:iteration_utilities

関連する問題