0

I have this error "UnboundLocalError: local variable 'names' referenced before assignment" when I try define the variables cookies in my class, whats is wrong in this code?

    response = self.__send_http_request(req_prepared)

    status_code = response.status_code

    if (status_code >= 200) and (status_code <= 299):
        for cookie in response.cookies: 
            names = cookie.name
            values = cookie.value
            domains = cookie.domain
            
        return self.get_starships_response(
            status_code = response.status_code,
            request = req,
            name = names,
            value = values,
            domain = domains
        )
    else:
        ...
  • 1
    Scoping rules are strange inside classes. Consider doing this outside of a class. See https://stackoverflow.com/questions/40848736/variable-scope-in-generators-in-classes – mousetail Sep 12 '21 at 20:57
  • 1
    What happens if `response.cookies` is empty? – Craig Sep 12 '21 at 20:59
  • You would get this error if there were no cookies in `response.cookies`. Try adding `names = None` or something similar before running `for cookie in response.cookies...`. – Sylvester Kruin Sep 12 '21 at 20:59
  • `response.cookies` is not empty I try that outside of classe and work normaly – João Galdino Sep 12 '21 at 21:02
  • Consider what happens if `response.cookies` is empty. Then `names = cookie.name` doesn't get executed. What do you then expect your `return` statement to pass as `name=` to the function it is calling? – BoarGules Sep 12 '21 at 21:03
  • 1
    If you are certain that `response.cookies` contains something every time this code is called, then you should 1) update your question with the full error trace, and 2) provide a [mre]. – Craig Sep 12 '21 at 21:09
  • 4
    1. No, the class is not the problem. 2. This question isn't about HTTP requests or cookies, so replace that stuff with simple python objects and make a [mcve] with the same structure that gives the same error, then we can tell you exactly what's happening. 3. It sure looks like response.cookies is empty. What we can guarantee is that no iterations are happening inside your for loop. 4. What is the code supposed to do when there are multiple cookies? This only returns a response based on the last cookie, not all of them. – Alex Hall Sep 12 '21 at 21:09
  • @mousetail I try `gen = (response.cookies for _ in range(3))`, but it returns the cookie object ` ` I want acess the attributes`name, value and domain` – João Galdino Sep 12 '21 at 21:12

0 Answers0