Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"Explicit is better than implicit." You should just document that your users need to use <code>MyList()</code> instead of <code>list()</code>. You and your users will be happier in the long run.</p> <p>Ruby allows what you want, by the way. With Ruby, you can open up global objects and just add new behaviors. I find this scary, and Ruby runs slower than Python, so I'm not actually urging you to switch to Ruby.</p> <p>So, provide <code>MyList()</code>, and provide a way to take an existing list and wrap it in a <code>MyList()</code>.</p> <p>You could write <code>MyList()</code> to just take a bunch of arguments, and make a list very conveniently:</p> <pre><code>class MyList(object): def __init__(self, *args): self.lst = args # add other methods to MyList() here </code></pre> <p>then you could call this with <code>MyList(1, 2, 3, 4)</code> and the instance would have a member called lst with the value: <code>[1, 2, 3, 4]</code></p> <p>But now, if you want to make a <code>MyList</code> instance out of a list, how do you do that? If you do this:</p> <pre><code>new_list = [1, 3, 5] x = MyList(new_list) </code></pre> <p>then you have just set x to: <code>[[1, 3, 5]]</code></p> <p>So I recommend you make <code>MyList()</code> just take a list argument and save it:</p> <pre><code>def ensure_list(seq): try: seq[0] return seq except TypeError: return list(seq) class MyList(object): def __init__(self, seq): self.lst = ensure_list(seq) # add other methods to MyList() here </code></pre> <p>I just edited this answer. Originally, I had a call to <code>list()</code> where I now have put a call to <code>ensure_list()</code>. <code>ensure_list()</code> checks to see if you can index its argument; if you can, it is either a list already or something that can act like a list, and it is returned unchanged. If you can't index it, then <code>ensure_list()</code> calls <code>list(seq)</code> to try to turn it into a list. This will work with iterators and generators, forcing them to expand out to a list.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload