kcmallard
kcmallard

Reputation: 197

How do I pass parameters into functions using other functions?

I keep getting error: "unhashable type: list" for line (routing_table[key][0] = [[params], func]. I'm attempting to pass a url and function into a route function. This route function should pick out the parameters for other functions by use of regular expressions. The ultimate goal is to read in "/page/<page_id>, then pick out <page_id> and replace that with user input. That user input will then be passed into the function. I don't see why this isn't working.

import re

routing_table = {}

def route(url, func):
   key = url
   key = re.findall(r"(.+?)/<[a-zA-Z_][a-zA-Z0-9_]*>", url)
   if key:
      params = re.findall(r"<([a-zA-Z_][a-zA-Z0-9_]*)>", url)
      routing_table[key][0] = [[params], func]
   else:
      routing_table[url] = func

def find_path(url):
   if url in routing_table:
       return routing_table[url]
   else:
      return None

def index():
   return "This is the main page"

def hello():
   return "hi, how are you?"

def page(page_id = 7):
   return "this is page %d" % page_id

def hello():
   return "hi, how are you?"

route("/page/<page_id>", page)

print(routing_table)

Upvotes: 0

Views: 43

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

I'm not sure why you are using re.findall if you're only interested in the first value found.

Nevertheless, your problem is simply the way you index the result: key is a list, and as the error says, you can't use a list as a dict key. But you've put the [0] outside the first set of brackets, so Python interprets this as you wanting to set the first value of routing_table[key], rather than you wanting to use the first value of key as the thing to set.

What you actually mean is this:

routing_table[key[0]] = [[params], func]

Upvotes: 1

Related Questions