9

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.

2
  • 2
    Why not just use None to represent an absent value? Commented Oct 12, 2013 at 21:25
  • When you say optional. Is what you really mean is the maybe monad ? Commented Oct 12, 2013 at 21:28

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

c++ optional and None default value has a real different semantics. Supposing the value I want to store in an optional variable can already hold the None type, how can I check if this optional variable has been set ?
@etham Well, ideally you'd fix your overly complicated data model. But if you insisted on it, you could simply use (for instance) a one-element tuple to wrap the value.
You are right. A language with too much features prevent us from having a nice design. I fixed my data model ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.