Note that there are some explanatory texts on larger screens.

plurals
  1. POElegantly Assign Variables of Unknown Length
    primarykey
    data
    text
    <p>(Sorry. The title's pretty unclear. I couldn't come up with a good one.)</p> <p>Say I have a url like so (it's root-relative): </p> <pre><code>"/forums/support/windows/help_i_deleted_sys32/6/" </code></pre> <p>and I'm trying to split this into a class structure like this:</p> <pre><code>class Forum_Spot: def __init__(self, url): parts = url.strip("/").split("/") #parts is now ["forums", "support", "windows", "help...", "6"] self.root = "forums" self.section = "support" self.subsection = "windows" self.thread = "help..." self.post = "6" </code></pre> <p>but say I don't know how long exactly the url will be (it could be "/forums/support/", "/forums/support/windows/", etc) (but I do know it won't be any deeper than 5 levels). Can anybody think of an elegant way to assign these values, letting any parts not assigned be <code>None</code>? (I.e. for "/forums/support/windows/", the thread and post attributes would be None)</p> <p>I know I could do this:</p> <pre><code>class Forum_Spot: def __init__(self, url): parts = url.strip("/").split("/") #parts is now ["forums", "support", "windows", "help...", "6"] if len(parts) &gt; 0: self.root = parts[0] else: self.root = None if len(parts) &gt; 1: self.section = parts[1] else: #etc </code></pre> <p>but this is obviously superinelegant and obnoxiously labor-intensive. Can anybody think of a more elegant solution, keeping the class signature the same? (I could convert the <code>__init__</code> function to take keyword parameters, defaulting to <code>None</code>, but I'd like to be able to just pass in the url and have the class figure it out on its own)</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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