title: JSONSchema local self-reference (recursion)
body: <p><strong>How can I reference a schema (<code>B</code> in this case) from itself no matter where it is nested?</strong></p>
  
  <p>I would like to be able to validate against schema <code>A</code> <strong>and</strong> against schema <code>B</code>. E.g.</p>
  
  <pre><code>from jsonschema import validate
  validate(a, A)
  validate(b, B)
  </code></pre>
  
  <p>Why? For unit tests and for speed improvements (if one of the <code>B</code>'s fails I don't need to validate <code>A</code>).</p>
  
  <p>Schema <code>A</code> references schema <code>B</code> and <code>B</code> references itself (see examples below).</p>
  
  <p>I have tried the following:</p>
  
  <p><strong>a)</strong> Using <code>definitions</code> in <code>A</code> works only if validating against <code>A</code>. Validating B fails with <code>jsonschema.exceptions.RefResolutionError: Unresolvable JSON pointer: 'definitions/b'</code>. Which makes sense because the definition only exists on <code>A</code>.</p>
  
  <pre><code>from jsonschema import validate
  
  B = {
      "anyOf": [
          {
              "type": "object"
          },
          {
              "type": "array",
              "items": {"$ref": "#/definitions/b"}
          }
      ]
  }
  
  A = {
      "definitions": {
          "b": B
      },
      "type": "array",
      "items": {"$ref": "#/definitions/b"}
  }
  
  validate([], A)
  validate([], B)  # RefResolutionError
  </code></pre>
  
  <p><strong>b)</strong> Using <code>"$id": "http://example.org/B"</code> in <code>B</code> and reference itself with: <code>{"$ref": "http://example.org/B"}</code> makes an actual (unnecessary http request) to a URL that does not exist. There is no need to make that request as the information is present in the document. Attempts using a non-url such as just <code>#B</code> fails with <code>jsonschema.exceptions.RefResolutionError: unknown url type</code>.</p>
  
  <pre><code>from jsonschema import validate
  
  B = {
      "$id": "http://example.org/schema/B",
      "anyOf": [
          {
              "type": "object"
          },
          {
              "type": "array",
              "items": {"$ref": "http://example.org/schema/B"}
          }
      ]
  }
  
  A = {
      "type": "array",
      "items": {"$ref": "http://example.org/schema/B"}
  }
  
  validate([{}], A)  # RefResolutionError: HTTP Error 404: Not Found
  validate([{}], B)  # RefResolutionError: HTTP Error 404: Not Found
  </code></pre>