python-3.xpsycopg3

Trying to form a Multirange with two Range objects


According to the docs,

https://access.crunchydata.com/documentation/psycopg3/3.1.4/

The psycopg3 Range is:

Range objects are immutable, hashable, and support the in operator (checking if an element is within the range).

However in Python I would like to concatenate two Range into a psycopg3 Multirange. I know the Range (as opposed to small case 'r' range) has limited functionality in Python.

How can I do that?

Note this is valid where foo is a psycopg3 MultiRange object.

foo.append(newrange) 

I am allowed to tack on a Range object at the end of a MultiRange object.

Here is an attempt to tack one Range object after another to create a MultiRange.

```from itertools import chain 
t = Range(300,400) 
newrange = Range(2900,4300)
print("Newrange data and type", newrange, type(newrange))
mt = chain(t, newrange) 
print(mt, type(mt))
print(sorted(mt))   # same error if I try 'list' instead of 'sorted' 
```

Output:

```Newrange data and type [2900, 4300) <class 'psycopg.types.range.Range'>
  
   <itertools.chain object at 0x7fd30892fd60> <class 'itertools.chain'>
   Traceback (most recent call last):
   File "range_agg_test.py", line 95, in <module>
   print(sorted(mt))
   TypeError: 'Range' object is not iterable```

Is there any way to accomplish the creation of a MultiRange given 2 Ranges?


Solution

  • After some fumbling I realized I needed to initialize a new MultiRange object as follows

    newbie = Multirange() 
    newbie.append(newrange)
    newbie.append(t) 
    

    If the business domain requires the MultiRange be strictly ascending, as is usual, it is up to the developer to make sure newrange and t are in the right order, because the append statements do not check.