eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I wrote something like this: settings = { 'methodConfig': [ { 'name': [{}], 'timeout': '0.5s', 'retryPolicy': { 'maxAttempts': 5, 'initialBackoff': '0.1s', 'maxBackoff': '2s', 'backoffMultiplier': 2, 'retryableStatusCodes': [ 'UNAVAILABLE', 'INTERNAL', 'DEADLINE_EXCEEDED', ], }, }, ], } settings_as_json_string = json.dumps(settings) request = Request(...) async with grpc.aio.insecure_channel( host_port, options=(('grpc.service_config', settings),), ) as channel: stub = StubClass(channel=channel) await stub.SomeMethod( request=request, )  On the service side, I specifically slowed down call processing so that it takes about one second. When running the above code, I see that there are no 5 call attempts with a 0.5 second wait each time. There is only one attempt, ending with error DEADLINE_EXCEEDED after about 0.5 seconds. From here I conclude that timeout is not the waiting time for the service response in each attempt, but it is the maximum duration of interaction with the service. A similar behavior is observed when I remove timeout from the config and specify it as argument in the call SomeMethod:  ... await stub.SomeMethod( request=request, timeout=0.5, )  My question is this: Is there a way to specify the timeout of waiting for the service response in each individual attempt? So after 0.5 seconds of waiting and some backoff, there was another attempt, during which we also waited for a response within 0.5 seconds, and so on until the max_attempts was reached.

Answer: There is no per-attempt timeout in the design of the retry functionality in gRPC. The general theory is that any attempt could succeed, and artificially cutting an attempt off early only reduces the chances of achieving any success at all.
Question: Imagine that I have a dataset df with one column containing a dictionary with two list types (list_A and list_B) as value: data = [{"list_A": [2.93, 4.18, 4.18, None, 1.57, 1.57, 3.92, 6.27, 2.09, 3.14, 0.42, 2.09], "list_B": [820, 3552, 7936, None, 2514, 4035, 6441, 15379, 2167, 6147, 3322, 1177]}, {"list_A": [2.51, 3.58, 3.58, None, 1.34, 1.34, 3.36, 5.37, 1.79, 2.69, 0.36, 1.79], "list_B": [820, 3552, 7936, None, 2514, 4035, 6441, 15379, 2167, 6147, 3322, 1177]}, {"list_A": [None, 5.94, 5.94, None, 2.23, 2.23, 5.57, 8.9, 2.97, 4.45, 0.59, 2.97], "list_B": [820, 3552, 7936, None, 2514, 4035, 6441, 15379, 2167, 6147, 3322, 1177]}] # Create a DataFrame with a column named "column_dic" df = pd.DataFrame({"column_dic": [data]})  Now, I want to create an additional column count_first_item that contains the count of non-Null values of the first item ([0]) of the lists that correspond to "List_A". The expected output of this is 2 (2.93 = +1; 2.51 = +1; None = 0).

Answer: Use list comprehension for get first values of list_A, test non missing values by notna and count Trues by sum: df['count_first_item'] = [pd.notna([y['list_A'][0] for y in x]).sum() for x in df['column_dic']] print (df) column_dic count_first_item 0 [{'list_A': [2.93, 4.18, 4.18, None, 1.57, 1.5... 2  Or use Series.explode, get values of lists by str or Series.str.get, get first values by indexing - str[0] and count non missing values by DataFrameGroupBy.count: df['count_first_item'] = (df['column_dic'].explode().str.get('list_A').str[0] .groupby(level=0).count()) print (df) column_dic count_first_item 0 [{'list_A': [2.93, 4.18, 4.18, None, 1.57, 1.5... 2
Question: I have a pandas dataframe as below and I would like to transpose the df based on the column Names I want transpose all the coumns that has _1,_2,_3 & _4. I have 100+ Values in my df, Below is the example data.  import pandas as pd data = { # One Id Column 'id':[1], #Other columns 'c1':['1c'], 'c2':['2c'], 'c3':['3c'], #IC indicator 'oc_1':[1], 'oc_2':[0], 'oc_3':[1], 'oc_4':[1], #GC Indicator 'gc_1':['T1'], 'gc_2':['T2'], 'gc_3':['T3'], 'gc_4':['T4'], #PF Indicator 'pf_1':['PF1'], 'pf_2':['PF2'], 'pf_3':['PF3'], 'pf_4':['PF4'], #Values 'V1_1':[11], 'V1_2':[12], 'V1_3':[13], 'V1_4':[14], 'S1_1':[21], 'S1_2':[22], 'S1_3':[23], 'S1_4':[24] } df = pd.DataFrame(data)   I need to transpose this df as below output  I tried below code: standard_cols = ['id','c1','c2','c3'] value_cols = ['V1_1','V1_2','V1_3','V1_4','S1_1','S1_2','S1_3','S1_4'] result_cols = standard_cols+['OC','GC','PF','Var','value'] melted_df = pd.melt(df, id_vars=standard_cols + ['oc_1','oc_2','oc_3','oc_4','gc_1','gc_2','gc_3','gc_4','pf_1','pf_2','pf_3','pf_4'], value_vars=value_cols,var_name='Var',value_name='value') print(melted_df) 

Answer: You can first reshape with wide_to_long, then melt: standard_cols = ['id','c1','c2','c3'] value_cols = ['V1','S1'] result_cols = ['OC','GC','PF'] result_cols = [c.lower() for c in result_cols] out = (pd .wide_to_long( df, i=standard_cols, stubnames=result_cols+value_cols, j='j', sep='_') .reset_index() .melt(standard_cols+result_cols+['j'], var_name='VAR', value_name='Value') .assign(VAR=lambda d: d['VAR']+'_'+d.pop('j').astype('str')) ) print(out)  Output:  id c1 c2 c3 oc gc pf VAR Value 0 1 1c 2c 3c 1 T1 PF1 V1_1 11 1 1 1c 2c 3c 0 T2 PF2 V1_2 12 2 1 1c 2c 3c 1 T3 PF3 V1_3 13 3 1 1c 2c 3c 1 T4 PF4 V1_4 14 4 1 1c 2c 3c 1 T1 PF1 S1_1 21 5 1 1c 2c 3c 0 T2 PF2 S1_2 22 6 1 1c 2c 3c 1 T3 PF3 S1_3 23 7 1 1c 2c 3c 1 T4 PF4 S1_4 24
Question: I'm developing a library, and I'm using hypothesis to test it. I usually sketch out a (buggy) implementation of a function, implement tests, then iterate by fixing errors and running tests. Usually these errors are very simple (e.g., a typo), and I don't need simplified test cases to figure out the issue. For example: def foo(value): return vslue + 1 # a silly typo @given(st.integers()) def test_foo(x): assert foo(x) == x + 1  How can I make hypothesis stop generating test cases as soon as it has found a single counterexample? Ideally, this would be using commandline flags to pytest.

Answer: Building on my comment from earlier - did you look at this? https://hypothesis.readthedocs.io/en/latest/settings.html#hypothesis.settings.phases Looks like there's some support for having different "Setting Profiles". I bet you could have one where you eliminate the Shrinking phase. Maybe that's the way to do. Yeah! That's probably it :) That gets you this command line option: pytest tests --hypothesis-profile <profile-name> So, in summary: In your conftest.py: from hypothesis import settings, Phase settings.register_profile("failfast", phases=[Phase.explicit, Phase.reuse, Phase.generate])  And then run it with: pytest tests --hypothesis-profile failfast
Question: I am trying to add subtitles to my Plotly Dash video player, i.e. VTT captions overlay, in Python. I cannot find any examples or instruction on this. from dash import Dash, dcc, html, Input, Output, State import dash_player  And in a html Div somewhere: dash_player.DashPlayer( id='vid1', controls = True, url = "http://86.47.173.33:1935/playlist.m3u8", width='100%', style={'margin-top':'20px','margin-bottom':'20px'}, playing= True, muted= True )  The DashPlayer object has no methods to handle a subtitle track in the documentation. Perhaps this is something that could be handled in CSS? To find some React player examples.

Answer: My strategy in the end was to create a div ('subtitle-container') as a sibling to the DashPlayer in the layout: dash_player.DashPlayer( id='vid', controls = True, url = None, style={'margin-top':'20px','margin-bottom':'20px', 'margin-left':'10px'}, playing= False, muted= False ), html.Div( id='subtitle-container', children=[html.P("subtitle text")], style={} ),  I implemented my own logic to display the subtitles, in the subtitle-container using the DashPlayer's 'current-time' callback.  @app.callback([Output('subtitle-container','children'),Output('subtitle-container', 'style')], [Input('vid', 'currentTime')]) def update_subtitles(current_time): subtitle_text = get_subtitle_for_time(current_time) # Determine whether subtitles are being displayed subtitles_displayed = bool(subtitle_text) # Set the alpha value based on whether subtitles are being displayed alpha_value = 0 if not subtitles_displayed else 0.5 # Update subtitle container style subtitle_style={ 'position':'absolute', 'bottom':'6%', 'left': '25%', 'width':'50%', 'background-color':f'rgba(30,30,30, {alpha_value})', 'padding':'5px', 'whiteSpace':'pre-wrap', 'color':'white', 'text-align':'center' } return subtitle_text, subtitle_style  This callback returns the relevant caption based on the player's current time, to be displayed in the 'subtitle-container'. I also implement logic to determine the style for the subtitle, semi-transparent dark background when caption present, and no background (alpha = 0), when no caption is present. To gather all the captions initially, I parse an SRT file, to produce a list of caption items. Each caption item is a list of 3 items, start time, end time, and caption text. e.g [1185.65, 1193.74, "You're the one who was frowning.\nFrisco. San Francisco. Exactly.'].  The timings have been converted from the original SRT timestamps. Getting the appropriate cue for the player's current time is simply a matter of: def get_subtitle_for_time(current_time): for caption in captions: if current_time <= caption[1]: if current_time >= caption[0]: return caption[2] return ''
Question: The other day, I was trying to teach the principles of Regex to a student - I am far from an expert but wanted to show the principles of it. I have a text file containing all the words of the English language, and I wanted to define a series of rules in regex so that the only word that would come out would be "CONGRATULATIONS". We did it in Python code first, then using the re python library. The two first rules were to find words having O as the second letter, and words ending in IONS. While we first tried to find the words matching a rule and then the other in pure Python, we tried to do it in one go using the regex pattern ^.O[A-Z]*IONS$. We were surprised to see that the two methods differed by one word: IONS. I mean, it totally makes sense, as the regex pattern is looking, by definition, for words of at least 6 characters. But it got us wondering if there was a way to get the words that have O as a second letter, which can also be the O of IONS in one single regex pattern. I know we can totally do it in two steps, first getting the words having an O as the second letter, and then getting the words ending in IONS among these words, but I just wondered if it was possible in one step alone.

Answer: Short answer is: ^([A-Z]O[A-Z]*)?IONS$  Explanation: Using Venn diagram.  Rule 1: words with O as second letter ^.O or `^.O.*$ Rule 2: words that ends with IONS IONS$ or `^.*IONS$  In the intersection of Rule 1 & 2 (there are  3  2 disjoint cases):  case 1 the shortest word is the word IONS, None for 5 letters, second letters are contradicting: "O" in rule 1 while "I" in rule 2 case 2 for 6 letters and above: your pattern suffices.  union of these  3  2 is IONS OR your pattern which is ^(IONS|.O.*IONS)$ or ^(IONS|.O.*IONS)$ but as @InSync commented you can simplify it to ^(.O.*)?IONS$  how & why? since:  A: the word IONS satisfies both rules, satisfying one would would match IONS. Let's keep the stricter rule 2. IONS$  4-letter word: ^IONS$   B: there are 2 cases. We can make rule 1 optional (rule1)?, when matching:  6-letter words^(.O)?IONS$ or 6+letter words ^(.O.*)?IONS$    or even stricter as needed: if 'words' is A-Z only ^([A-Z]O[A-Z]*)?IONS$
Question: I have a list holding many lists of the same structure (Usually, there are much more than two sub-lists inside the list, the example shows two lists for the sake of simplicity). I would like to create the sum or product over all sub-lists so that the resulting list has the same structure as one of the sub-lists. So far I tried the following using the tree_reduce method but I get errors that I don't understand. I could need some guidance on how to use tree_reduce() in such a case. import jax import jax.numpy as jnp list_1 = [ [jnp.asarray([1]), jnp.asarray([2, 3])], [jnp.asarray([4]), jnp.asarray([5, 6])], ] list_2 = [ [jnp.asarray([7]), jnp.asarray([8, 9])], [jnp.asarray([10]), jnp.asarray([11, 12])], ] list_of_lists = [list_1, list_2] reduced = jax.tree_util.tree_reduce(lambda x, y: x + y, list_of_lists, 0, is_leaf=True) # Expected # reduced = [ # [jnp.asarray([8]), jnp.asarray([10, 12])], # [jnp.asarray([14]), jnp.asarray([16, 18])], # ] 

Answer: You can do this with tree_map of a sum over the splatted list: reduced = jax.tree_util.tree_map(lambda *args: sum(args), *list_of_lists) print(reduced)  [[Array([8], dtype=int32), Array([10, 12], dtype=int32)], [Array([14], dtype=int32), Array([16, 18], dtype=int32)]]
Question: I have following code: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://google.com")  This code works well except that it is really slow. I don´t use the ChromeDriver. Just the normal Chrome Browser on my Mac. Why do I have to download the ChromeDriver? It doesn´t speed up the code execution. I've already tried that. Also: Why do I have to close the driver at the end of my programm with driver.close()? The browser closes automatically when the code is finished. Thank you!

Answer: Your code is perfectly fine. selenium version > 4.12.0 There is no need to download the chromedriver manually, Selenium's new in-built tool Selenium Manager will automatically download and manage the drivers for you. https://www.selenium.dev/documentation/selenium_manager/ https://www.selenium.dev/blog/2023/status_of_selenium_manager_in_october_2023/ You do not have to use driver.close() with the above code.
Question: I have been struggling to understand what I am doing wrong with the memory management of this this C++ function for a python module, but I don't have much experience in this regard. Every time I run this function, the memory consumption of the python interpreter increases. The function is supposed to take in two numpy arrays and create new numpy arrays with the desired output. extern "C" PyObject *radec_to_xyz(PyObject *self, PyObject *args) { // Parse the input arguments PyArrayObject *ra_arrobj, *dec_arrobj; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &ra_arrobj, &PyArray_Type, &dec_arrobj)) { PyErr_SetString(PyExc_TypeError, "invalid arguments, expected two numpy arrays"); return nullptr; } // skipping checks that would ensure: // dtype==float64, dim==1, len()>0 and equal for inputs, data or contiguous npy_intp size = PyArray_SIZE(ra_arrobj); // create the output numpy array with the same size and datatype PyObject *x_obj = PyArray_EMPTY(1, &size, NPY_FLOAT64, 0); if (!x_obj) return nullptr; Py_XINCREF(x_obj); // get pointers to the arrays double *ra_array = static_cast<double *>(PyArray_DATA(ra_arrobj)); double *dec_array = static_cast<double *>(PyArray_DATA(dec_arrobj)); double *x_array = static_cast<double *>(PyArray_DATA(reinterpret_cast<PyArrayObject*>(x_obj))); // compute the new coordinates for (npy_intp i = 0; i < size; ++i) { double cos_ra = cos(ra_array[i]); double cos_dec = cos(dec_array[i]); // compute final coordinates x_array[i] = cos_ra * cos_dec; } // return the arrays holding the new coordinates return Py_BuildValue("O", x_obj); }  I suspect that I am getting the reference counts wrong and therefore, the returned numpy arrays don't get garbage collected. I tried changing the reference counts, but this did not help. When I pass the X array as additional argument from the python interpreter instead of allocating it in the function, the memory leak is gone as expected.

Answer: Py_XINCREF(x_obj) is not needed because Py_BuildValue("O", x_obj) will increment the reference count for you. In other words, you're accidentally increasing the reference count too much by 1
Question: I have this image: HI00008918.png I want to apply a logarithmic function (f(x) = (1/a)*log(x + 1), where a = 0.01) on the image... So this is the code: import numpy as np import matplotlib.pyplot as plt import skimage.io as io car = io.imread('HI00008918.png') # plt.imshow(car, cmap='gray', vmin=0, vmax=255) a = 0.01 fnLog = lambda x : (1/a)*np.log(x + 1) # logarithmic function # the original image has white pixels (=0) and black pixels (=255) carLog = fnLog(car) # Applying the function fnLog print(car[0][0][-1]) print(carLog[0][0][-1]) print(fnLog(car[0][0][-1]))  The output: 255 -inf 554.5177444479563  Look at one moment it results in -inf and at others it results in the correct value :( Now I will show the arrays: carLog = [[[277.2 277.2 277.2 -inf] [289. 289. 289. -inf] [304.5 304.5 304.5 -inf] ... [423.5 431.8 429. -inf] [422. 434.5 427.8 -inf] [437. 450. 440.5 -inf]] [[434.5 434.5 434.5 -inf] [433.2 433.2 433.2 -inf] [430.5 430.5 430.5 -inf] ... [422. 430.5 427.8 -inf] [420.2 429. 426.2 -inf] [433.2 444.2 438.2 -inf]]] car = [[[ 15 15 15 255] [ 17 17 17 255] [ 20 20 20 255] ... [148 138 149 255] [138 125 142 255] [148 134 151 255]] [[ 10 10 10 255] [ 14 14 14 255] [ 19 19 19 255] ... 

Answer: It looks like np.log(x + 1) gives -Inf only where x is 255 in an array. Because the array x is uint8, adding 1 to 255 causes overflow, which wraps the result yielding 0. The log of 0 is -Inf. You might want to cast the image to a floating-point type before applying the function: carLog = fnLog(car.astype(np.float32))  When you apply the function to a value extracted from the image, you are working with a Python int, which doesn’t ever overflow.
Question: Address Sanitizer is reporting a memory leak (multiple actually) originating from an embedded python interpreter when testing some python code exposed to c++ using pybind11. I have distilled the code down to nothing other than calling PyInitialize_Ex and then PyFinalizeEx #include <Python.h> int main() { Py_InitializeEx(0); Py_FinalizeEx(); return 0; }  All the memory leaks originate from a call to Py_InitializeEx. Example: Direct leak of 576 byte(s) in 1 object(s) allocated from: #0 0x7f0d55ce791f in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69 #1 0x7f0d55784a87 (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x133a87) #2 0x7f0d55769e4f (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x118e4f) #3 0x7f0d5576a084 (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x119084) #4 0x7f0d5576b0fa (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x11a0fa) #5 0x7f0d557974e6 in PyType_Ready (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x1464e6) #6 0x7f0d5577fea6 (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x12eea6) #7 0x7f0d5584eda5 (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x1fdda5) #8 0x7f0d559697b3 (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x3187b3) #9 0x7f0d558524e8 in Py_InitializeFromConfig (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x2014e8) #10 0x7f0d558548fb in Py_InitializeEx (/lib/x86_64-linux-gnu/libpython3.10.so.1.0+0x2038fb) #11 0x55fe54d040ce in main /home/steve/src/test.cpp:8 #12 0x7f0d54fe7d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58 #13 0x7f0d54fe7e3f in __libc_start_main_impl ../csu/libc-start.c:392 #14 0x55fe54d04124 in _start (/home/steve/src/build/test+0x1124)  Questions:  How can I free up the memory so asan is happy? Failing that, is it safe just to suppress Py_InitializeEx in its entirety? 

Answer: Py_Initialize has a long lasting known issue, whose origin is in C source codes. For C++ programmers I recommend boost.python as a replacement that uses C++ features to simplify interoperability between the 2 languages.
Question: class Meta(type): def __new__(cls, name, bases, dct): new_class = type(name, bases, dct) new_class.attr = 100 # add some to class return new_class class WithAttr(metaclass=Meta): pass print(type(WithAttr)) # <class 'type'>  Why does it print <class 'type'>, but not <class '__main__.Meta'> Am I right that class WithAttr is instance of Meta?

Answer: This is because you're making an explicit call to type(name, bases, dct), which in turn calls type.__new__(type, name, bases, dct), with the type class passed as the first argument to the type.__new__ method, effectively constructing an instance of type rather than Meta. You can instead call type.__new__(cls, name, bases, dct), passing the child class as an argument to contruct a Meta instance. In case __new__ is overridden in a parent class that is a child class of type, call super().__new__ instead of type.__new__ to allow the method resolution order to be followed. Change: new_class = type(name, bases, dct)  to: new_class = super().__new__(cls, name, bases, dct)  Demo: https://ideone.com/KIy2qG
Question: Given a numpy array such as the one below, is it possible to use vectorization to return the associated value in column HHt without using a for loop? ex_arr = [2643, 2644, 2647] for i in ex_arr: h_p = df.at[i, "HHt"]  Example df:      HHt     2643 1   2644 2   2645 3   2646 4   2647 5   2648 6   2649 7   2650 8     Expected result: 1 2 5

Answer: Use DataFrame.loc, if need list or array add Series.to_list or Series.to_numpy: print (df.loc[ex_arr,'HHt'].to_list()) [1, 2, 5] print (df.loc[ex_arr,'HHt'].to_numpy()) [1 2 5]
Question: Using DuckDB Python client, I want to iterate over the results returned from query like import duckdb employees = duckdb.sql("select * from 'employees.csv' ")  Using type(employees) returns 'duckdb.duckdb.DuckDBPyRelation'. I'm able to get the number of rows with len(employees), however for-loop iteration seems to not work. What is the correct way to process each row at a time?

Answer: Apparently, from DuckDB API, something like the following should work.  I unfortunately cannot test it because DuckDB's package won't install for whatever reason. I hope this helps you get in the right path to finding your answer. import duckdb employees = duckdb.sql("select * from 'employees.csv'") rows = employees.fetchall() # Iterate over the rows for row in rows: print(row)
Question: I'm trying to use libgpiod in python on my orangepi model 4B. I installed it with: sudo apt install libgpiod-dev python3-libgpiod  Now I try to use it: from gpiod.line import Direction, Value  But I get an error: ModuleNotFoundError: No module named 'gpiod.line'; 'gpiod' is not a package  If I open python in terminal and import gpiod the autocomplete options for gpiod. are: gpiod.Chip( gpiod.LINE_REQ_FLAG_OPEN_DRAIN gpiod.ChipIter( gpiod.LINE_REQ_FLAG_OPEN_SOURCE gpiod.LINE_REQ_DIR_AS_IS gpiod.Line( gpiod.LINE_REQ_DIR_IN gpiod.LineBulk( gpiod.LINE_REQ_DIR_OUT gpiod.LineEvent( gpiod.LINE_REQ_EV_BOTH_EDGES gpiod.LineIter( gpiod.LINE_REQ_EV_FALLING_EDGE gpiod.find_line( gpiod.LINE_REQ_EV_RISING_EDGE gpiod.version_string( gpiod.LINE_REQ_FLAG_ACTIVE_LOW  If I install gpiod through pip it says module 'gpiod' has no attribute 'Chip' when I try to use gpiod.Chip. What is wrong? Thanks in advance.

Answer: libgpiod-dev includes the the libgpiod C lib and its header files, while python3-libgpiod includes the Python bindings to that lib. So with the command: sudo apt istall libgpiod-dev python3-libgpiod  You're installing the libgpiod lib, C headers and python bindings. This lib is an abstraction layer to use gpio char device in Linux. Examples for controlling gpios with these python bindings can be found here. Try copy-paste one of the examples and run it. Make sure package is installed correctly and you have properly configured char device interface (ls /dev here you must see gpiochipX devices). I just tested it and worked as expected. NOTE: When you use pip install gpiod you can't use gpiod.Chip, but you can use gpiod.chip instead (note that the former is capital). This is because you are using an old version of gpiod python package. You said that you're using gpiod version 1.5.4 so this is the corresponding documentation for that version. As you can see it claims to be a:  It is a pure Python library and has no dependencies on other packages !!  It also includes a link to the proper documentation site where you can see that the examples are using gpiod.chip instead of gpiod.Chip. The new version of gpiod package (2.1.3) is not a pure python package but official bindings to libgpiod. as you can see in the proper doc. This version DOES support the usage of gpiod.Chip as you can see in its examples. So, how to be able yo use gpio.Chip through a pip installation? pip install gpiod==2.1.3  This guarantees you use the new version