Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional variables in Python

Tags:

python

do you guys know if there exists a Python equivalent to boost::optional in C++ (or std::optional since C++11: http://en.cppreference.com/w/cpp/utility/optional), i.e. a library that handles semantically optional variables?

I know how to implement it myself or use the other solutions (like foo = (bar, True) which I find ugly and unreadable). Just curious if there is an existing solution.

like image 442
Michał Góral Avatar asked Oct 12 '13 21:10

Michał Góral


1 Answers

Optional variables, a limited form of algebraic typing, are primarily useful in statically typed languages. In dynamically typed languages like Python, there's no real need for them. As arshajii said, you can use None (or, if you prefer, any other sentinel you'd like) to represent an absent value. You then just check whether the variable has the expected type or not.

like image 157
Sneftel Avatar answered Oct 29 '22 13:10

Sneftel