eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have the following code: import seaborn as sns import pandas as pd import numpy as np Data = pd.DataFrame(columns=['x1','x2','x3','label']) for i in range(100): Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'1'] Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'2'] Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'3'] Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'4'] Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'5'] sns.pairplot(Data,vars=['x1','x2','x3'],hue='label',markers=['o','s','s','s','s'],corner=True)  Which gives the following output:  I want to put black borders only around the square markers to make them more visible but I don't know how to do that. I tried to add: grid_kws={fillstyles:['none','full','full','full','full']}  as an argument to sns.pairplot, but I just got the following error: Traceback (most recent call last): File ~/anaconda3/lib/python3.10/site-packages/spyder_kernels/py3compat.py:356 in compat_exec exec(code, globals, locals) File ~/Dokument/Python/MasterProjectCoCalc/SNmasterproject/untitled0.py:21 sns.pairplot(Data,vars=['x1','x2','x3'],hue='label',markers=['o','s','s','s','s'],corner=True,grid_kws={fillstyles:['none','full','full','full','full']}) NameError: name 'fillstyles' is not defined  I also tried to add: plot_kws={'edgecolor':'black'}  to the sns.pairplot function and then I got  but now all the points have a black border. How do I get only black borders around the square markers?

Answer: The scatter dots are stored in ax.collections[0]. To avoid that the colors of later hue values always come on top, seaborn keeps the dots in the order they appear in the dataframe. You can use .set_edgecolors() to set the edge color of each individual dot. For the legend, the dots in stored in its handles as line objects, which you can change via .set_markeredgecolor(...) Here is how the code could look like: import seaborn as sns import pandas as pd import numpy as np Data = pd.DataFrame(columns=['x1', 'x2', 'x3', 'label']) for i in range(100): Data.loc[len(Data.index)] = [np.random.rand(), np.random.rand(), np.random.rand(), '1'] Data.loc[len(Data.index)] = [np.random.rand(), np.random.rand(), np.random.rand(), '2'] Data.loc[len(Data.index)] = [np.random.rand(), np.random.rand(), np.random.rand(), '3'] Data.loc[len(Data.index)] = [np.random.rand(), np.random.rand(), np.random.rand(), '4'] Data.loc[len(Data.index)] = [np.random.rand(), np.random.rand(), np.random.rand(), '5'] g = sns.pairplot(Data, vars=['x1', 'x2', 'x3'], hue='label', markers=['o', 's', 's', 's', 's'], corner=True) edge_colors = ['none' if l == '1' else 'k' for l in Data['label']] for ax in g.axes.flat: if ax is not None and len(ax. Collections) > 0: ax.collections[0].set_edgecolors(edge_colors) for h in g.legend.legend_handles[1:]: h.set_markeredgecolor('k')
Question: I've got a dataframe that I want to format which includes inf and nan. The dict for it is: df = pd.DataFrame({'Foodbank': {0: 'study', 1: 'generation', 2: 'near', 3: 'sell', 4: 'former', 5: 'line', 6: 'ok', 7: 'field', 8: 'last', 9: 'really', 10: 'particularly', 11: 'must', 12: 'drive', 13: 'herself', 14: 'learn'}, '%(LY)': {0: -20.93, 1: -19.23, 2: -26.09, 3: 150.0, 4: 90.24, 5: -23.85, 6: nan, 7: inf, 8: inf, 9: inf, 10: inf, 11: -35.48, 12: nan, 13: nan, 14: -1.3}}) from great_tables import GT GT(df)  It looks like this:  What I want is to have a dash or n/a to highlight it rather than inf which won't mean anything to an audience.

Answer: A possible solution: df['%(LY)'] = df['%(LY)'].replace(np.inf, np.nan)  Output:  Foodbank %(LY) 0 study -20.93 1 generation -19.23 2 near -26.09 3 sell 150.00 4 former 90.24 5 line -23.85 6 ok NaN 7 field NaN 8 last NaN 9 really NaN 10 particularly NaN 11 must -35.48 12 drive NaN 13 herself NaN 14 learn -1.30
Question: In Python Polars, how can I aggregate by concatenating lists, rather than creating a nested list? For example, I'd like to aggregate this dataframe on id import polars as pl df = pl.DataFrame({ 'id': [1, 1], 'name': [["Bob"], ["Mary", "Sue"]], })     id name     1 ["Bob"]   1 ["Mary", "Sue"]    and get this result    id name     1 ["Bob", "Mary", "Sue"]    If I use df.group_by('id').agg("name"), I get a nested list, which I don't want:    id name     1 [["Bob"], ["Mary", "Sue"]]   

Answer: Try using explode on your name column. result_df = df.group_by('id').agg(pl.col('name').explode())
Question: I have created 2 recrods, action report and template for pdf, but I have never defined the docs variable in the model, so how can Odoo understand it, or is it defined by default somewhere? So what if I want to define additional variables like "text1" : "hello" to use in the template? Thanks All 

Answer: The docs variable is set while rendering the report,in _get_rendering_context function 1/ You can pass them through data to report_action Example: (from employees summary report) def print_report(self): self.ensure_one() [data] = self.read() data['emp'] = self.env.context.get('active_ids', []) employees = self.env['hr.employee'].browse(data['emp']) datas = { 'ids': [], 'model': 'hr.employee', 'form': data } return self.env.ref('hr_holidays.action_report_holidayssummary').report_action(employees, data=datas)  2/ You can also use a custom report and define additional variables in _get_report_values Example: (from holidays summary report) @api.model def _get_report_values(self, docids, data=None): if not data.get('form'): raise UserError(_("Form content is missing, this report cannot be printed.")) holidays_report = self.env['ir.actions.report']._get_report_from_name('hr_holidays.report_holidayssummary') holidays = self.env['hr.leave'].browse(self.ids) return { 'doc_ids': self.ids, 'doc_model': holidays_report.model, 'docs': holidays, 'get_header_info': self._get_header_info(data['form']['date_from'], data['form']['holiday_type']), 'get_day': self._get_day(data['form']['date_from']), 'get_months': self._get_months(data['form']['date_from']), 'get_data_from_report': self._get_data_from_report(data['form']), 'get_holidays_status': self._get_holidays_status(), }
Question: I have many lists like this synonyms = ["3,2'-DIHYDROXYCHALCONE", '36574-83-1', '36574831', "2',3-Dihydroxychalcone", '(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one', MLS002693861]  from which I need to remove all elements that are comprised of only digits. I can't figure out how to remove element [1] because it's only digits but has random intervening dashes. Of course, this doesn't work since the dashes make the element not a digit: synonym_subset = [x for x in synonym_subset if not (x.isdigit())]  And I can't just remove the dashes because I want the dashes in the other elements to be retained: synonym_subset = [x.replace('-','') for x in synonym_subset]  I could run the above to find the index of the elements to be removed, then remove them that way, but I was hoping for a one-liner. Thanks.

Answer: Try: synonyms = [ "3,2'-DIHYDROXYCHALCONE", "36574-83-1", "36574831", "2',3-Dihydroxychalcone", "(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one", "MLS002693861", ] out = [s for s in synonyms if not all(ch in "0123456789-_" for ch in s)] print(out)  Prints: [ "3,2'-DIHYDROXYCHALCONE", "2',3-Dihydroxychalcone", "(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one", "MLS002693861", ]
Question: For example the array: array = np.array([[1, 1, 4, 2, 1, 8], [1, 1, 8, 2, 1, 16], [1, 1, 40, 2, 1, 80], [1, 2, 40, 2, 1, 80]])  I'd like to essentially remove every third [:, ::2] element of the inner arrays. So the result should be: [[1 1 2 1] [1 1 2 1] [1 1 2 1] [1 2 2 1]]  I could do two selections and concatenate each of the resulting arrays, but that seem super slow.. is there a way to use indexing or some other method that doesn't involve a loop with np.concatenate? My actual array always have inner arrays with sizes divisible by 3, and the 1 dimension is very, very large. So I'm interested in the fastest way to accomplish this. Thank you!

Answer: You can use boolean indexing: array[:, np.arange(array.shape[1]) % 3 != 2] array([[1, 1, 2, 1], [1, 1, 2, 1], [1, 1, 2, 1], [1, 2, 2, 1]])
Question: I am looking to get a subset of rows based on the row_id/row_number for a dataframe similar to pyarrow.Table.take. For eg: given the below dataframe from datetime import datetime df = pl.DataFrame( { "integer": [1, 2, 3, 4, 5], "date": [ datetime(2022, 1, 1), datetime(2022, 1, 2), datetime(2022, 1, 3), datetime(2022, 1, 4), datetime(2022, 1, 5), ], "float": [4.0, 5.0, 6.0, 7.0, 8.0], } ) print(df) shape: (5, 3) ┌─────────┬─────────────────────┬───────┐ │ integer ┆ date ┆ float │ │ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs] ┆ f64 │ ╞═════════╪═════════════════════╪═══════╡ │ 1 ┆ 2022-01-01 00:00:00 ┆ 4.0 │ │ 2 ┆ 2022-01-02 00:00:00 ┆ 5.0 │ │ 3 ┆ 2022-01-03 00:00:00 ┆ 6.0 │ │ 4 ┆ 2022-01-04 00:00:00 ┆ 7.0 │ │ 5 ┆ 2022-01-05 00:00:00 ┆ 8.0 │ └─────────┴─────────────────────┴───────┘  I am looking for take like function df.take([0, 4]) which gives the below dataframe. shape: (2, 3) ┌─────────┬─────────────────────┬───────┐ │ integer ┆ date ┆ float │ │ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs] ┆ f64 │ ╞═════════╪═════════════════════╪═══════╡ │ 1 ┆ 2022-01-01 00:00:00 ┆ 4.0 │ │ 5 ┆ 2022-01-05 00:00:00 ┆ 8.0 │ └─────────┴─────────────────────┴───────┘  The row numbers are a result of some other process and handed over. Tried using df.select(pl.all().take([take_indices]) and noticed that it was slower than actually running the filter directly. i.e. df.filter(filter_expr). Please note that I am doing this over extremely large datasets (> 100m rows). Edit: Thanks for the answer. using df[[take_indices]] worked. However still curious as to why filter still outperforms the both select.gather as well as square bracket approach. Timings on my datasetwith 50m rows: select.gather: .5s square_bracket: .32s [inline with mozway's timings] filter: .18s

Answer: df[[0,4]] will allow to select the indices 0 and 4. Since take is deprecated, the equivalent to your proposed code would be to use gather: df.select(pl.all().gather([0, 4]))  Output: shape: (2, 3) ┌─────────┬─────────────────────┬───────┐ │ integer ┆ date ┆ float │ │ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs] ┆ f64 │ ╞═════════╪═════════════════════╪═══════╡ │ 1 ┆ 2022-01-01 00:00:00 ┆ 4.0 │ │ 5 ┆ 2022-01-05 00:00:00 ┆ 8.0 │ └─────────┴─────────────────────┴───────┘  Timing on 500k rows: # df.select(pl.all().gather([0, 4])) 145 µs ± 9.43 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) # df[[0,4]] 122 µs ± 14.3 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)  Timing on 5M rows: # df.select(pl.all().gather([0, 4])) 150 µs ± 13.3 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) # df[[0,4]] 117 µs ± 17.7 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
Question: I'm attempting to perform a groupby and aggregate operation on a Pandas DataFrame. Specifically, I want to compute the mean and count for each class group. However, I'm encountering issues accessing the generated columns. Here's an example of the transformation I'm aiming for: import pandas as pd df = pd.DataFrame({ 'Class': ['A', 'B', 'A', 'B', 'C'], 'Val': [25, 30, 35, 40, 15], }) grouped = df.groupby(by='Class').agg({'Val': ['mean', 'count']})  The result I obtain is as follows:  Val mean count Class A 30.0 2 B 35.0 2 C 15.0 1  However, I want to get rid of the "Val" sub-column to achieve this data structure: Class mean count A 30.0 2 B 35.0 2 C 15.0 1 

Answer: You should slice before agg: grouped = df.groupby(by='Class', as_index=False)['Val'].agg(['mean', 'count'])  Output:  Class mean count 0 A 30.0 2 1 B 35.0 2 2 C 15.0 1
Question: I have a pyspark dataframe as below: Mail sno mail_date date1 present abc@abc.com 790 2024-01-01 2024-02-06 yes abc@abc.com 790 2023-12-23 2023-01-01 nis@abc.com 101 2022-02-23 nis@abc.com 101 2021-01-20 2022-07-09 yes  In the final dataframe, I need one record of sno with all the max date values and corresponding max date in mail_date column for present So the final dataframe should be like: Mail sno mail_date date1 present abc@abc.com 790 2024-01-01 2024-02-06 yes nis@abc.com 101 2022-02-23 2022-07-09  I have the following code, windowSpec=Window.partitionBy('Mail','sno') df= df.withColumn('max_mail_date', F.max('mail_date').over(windowSpec))\ .withColumn('max_date1', F.max('date1').over(windowSpec)) df1 = df.withColumn('mail_date', F.when(F.col('mail_date').isNotNull(), F.col('max_mail_date')).otherwise(F.col('mail_date')))\ .drop('max_mail_date').dropDuplicates()  Here, Im not getting the expected values in the present column. Please suggest any changes

Answer: Even thought @DerekO's answer seems correct. I'd like to take another approach on this. I prefer using the groupBy().agg() approach with max and struct. This approach is more efficient in terms of data reduction specially when working with large datasets. So considering the data that you have provided : df_result = df.withColumn( "mail_date_struct", F.struct(F.col("mail_date").alias("max_mail_date"), "present") ).groupBy("Mail", "sno").agg( F.max("mail_date_struct").alias("max_mail_date_struct"), F.max("date1").alias("max_date1") ).select( "Mail", "sno", "max_mail_date_struct.max_mail_date", "max_mail_date_struct.present", "max_date1" ) df_result.show() # +-----------+---+-------------+-------+----------+ # | Mail|sno|max_mail_date|present| max_date1| # +-----------+---+-------------+-------+----------+ # |abc@abc.com|790| 2024-01-01| yes|2024-02-06| # |nis@abc.com|101| 2022-02-23| NULL|2022-07-09| # +-----------+---+-------------+-------+----------+  Considerations : The choice between the approach that I'm suggesting and the window functions approach depends on your specific use case, dataset characteristics and performance considerations. For large datasets where you aim to reduce data volume through aggregation might be more efficient. However, if maintaining the original dataset's structure while computing partition wise metrics is required, window function could be more appropriate although potential at a higher computational cost. Always consider testing both approaches on a subset of your data to understand the performance implications in your specific environment.
Question: I can't wrap my head around how to use aynchio. Can you please just help me fix this issue. Assume I have some IO task which takes 8 seconds that I put in the coroutine task(). I want to run an infinite loop and perform this take every 5 seconds without blocking my code. import asyncio async def task(): print('starting task') await asyncio.sleep(8) print('finished task') async def main(): count = 0 while True: print(count) if count % 5 == 0: print('running task') await task() count += 1 await asyncio.sleep(1) asyncio.run(main())  From my understanding of the docs, when I perform await inside the task coroutine, it should go back to executing main but this does not happen. What am I doing wrong here? My output is 0 running task starting task finished task 1 2 3 4 5 running task starting task finished task 6 7 8 9 10 

Answer: Your issue is you're awaiting the coroutine, which does what it says on the box: It stops anything from proceeding until it completes (to say it doesn't go back to main isn't quite right either. It does, just later than you wanted). Spinning it out to another unawaited task will let it "run in the background" import asyncio async def task(): print('starting task') await asyncio.sleep(8) print('finished task') async def main(): count = 0 while True: print(count) if count % 5 == 0: print('running task') asyncio.create_task(task()) count += 1 await asyncio.sleep(1) asyncio.run(main())  Gives me, which I think is what you want 0 running task starting task 1 2 3 4 5 running task starting task 6 7 finished task 8 9 10 running task starting task 11 12 finished task 13 14
Question: Running pandas 1.5.3. Also attempted on pandas 2.2.1. I am loading in data from a CSV that looks like such: 888|0|TEST ACCOUNT 888|1|Sample Ship-to 802001|0|COMPANY 1 802001|1|COMPANY 1 INC 802001|2|COMPANY 1 BALL K802001|3|COMPANY 1  With columns CUSNO, S2, and NAME, in that order. I have a script that loads in the data, then checks the first column and makes sure it is of int64 in the resulting DataFrame. If not, the script is supposed to convert the column to numeric and drop the rows that have NaN in them. So, before:  CUSNO S2 NAME 0 888 0 TEST ACCOUNT 1 888 1 Sample Ship-to 2 802001 0 COMPANY 1 3 802001 1 COMPANY 1 INC 4 802001 2 COMPANY 1 BALL 5 K802001 3 COMPANY 1  Then run: cl['CUSNO'] = pd.to_numeric(cl.CUSNO, errors='coerce') cl = cl.dropna(axis='index', how='any')  After:  CUSNO S2 NAME 0 888.0 0 TEST ACCOUNT 1 888.0 1 Sample Ship-to 2 802001.0 0 COMPANY 1 3 802001.0 1 COMPANY 1 INC 4 802001.0 2 COMPANY 1 BALL  I want to make CUSNO a column full of int64 or similar types, but when I run company_locations['CUSNO'].dtype it keeps returning float64. (Realistically, I want to get rid of the decimal point at the end of every entry in CUSNO and thought typecasting to int or similar would work best.) I've tried a number of solutions, namely: cl['CUSNO'] = pd.to_numeric(cl.CUSNO, errors='coerce').dropna().astype(int) # replacing the earlier line 1 of the script cl['CUSNO'] = cl.astype({'CUSNO': 'int'}) cl['CUSNO'] = cl['CUSNO'].apply(pd.to_numeric, errors='coerce')  I've tried inplace=True for line 2 in the script above. I've also tried solutions from pandas: to_numeric for multiple columns, Change column type in pandas, and Python - pandas column type casting with "astype" is not working. Perhaps I'm missing something here? Do I have to copy the new DataFrame to a new variable or something?

Answer: I think simple (after dropping the NaNs): df["CUSNO"] = df["CUSNO"].astype(int) print(df)  Prints:  CUSNO S2 NAME 0 888 0 TEST ACCOUNT 1 888 1 Sample Ship-to 2 802001 0 COMPANY 1 3 802001 1 COMPANY 1 INC 4 802001 2 COMPANY 1 BALL
Question: I'm trying to implement conditional logic in Gekko using "if3" but am unsure how to successfully layer 2 conditions at different levels of granularity. "x1" is vector of binary values (0/1) that controls when an alternative rhs value should be used on element i to constrain x2 and x3. "x2" is a vector of floats where I want to make the lower and upper bounds dynamic for element i based on the binary values in "x1" above. If the value for x1 for element i is = 1, I want to use "window_lnuc_min_promo_price" (vector of same length) as the lower bound and "window_lnuc_max_promo_price" as the upper bound. If the value for x1 for element i is = 0, I want to use "min_promo_price" as the lower bound and "max_promo_price" as the upper bound. Similarly, "x3" is a vector of floats where I want to apply the same logic but just to the lower bound using values from "window_lnuc" when element i in x1 is = 1 and values from "lnuc" when it is = 0. Lastly, I want to limit how many times X1 can be = 1 (4 in the example below). This would mean the alternative values are limited to 4 occurrences in total. The problem I think I'm having is that because x1 is a variable with a 0-1 range, the optimizer is changing the default "0" values in "lnuc_weeks" (which I don't want it to do). I want the optimizer to basically keep anything that is 0 in "lnuc_weeks" as is and only select a maximum of 4 values from the elements in "lnuc_weeks" that are = 1 initially. There is probably a better way to write this, but any help/feedback is appreciated. The full solution is a bit long to display for reproducibility of output, but hopefully the above/below sufficiently describe the problem. x1 = m.Array(m.Var,(n), integer=True) #LNUC weeks i = 0 for xi in x1: xi.value = lnuc_weeks[i] xi.lower = 0 xi.upper = 1 i += 1 x2 = m.Array(m.Var,(n)) #Blended SRP i = 0 for xi in x2: xi.value = blended_srp[i] xi.lower = m.if3((x1[i]) - 1, min_promo_price[i], window_lnuc_min_promo_price[i]) xi.upper = m.if3((x1[i]) - 1, max_promo_price[i], window_lnuc_max_promo_price[i]) i += 1 x3 = m.Array(m.Var,(n)) #Blended NUC i = 0 for xi in x3: xi.value = blended_nuc[i] xi.lower = m.if3((x1[i]) - 1, lnuc[i], window_lnuc[i]) xi.upper = 10 i += 1 #Limit max lnuc weeks m.Equation(sum(x1)<=4) 

Answer: The .lower and .upper bounds are defined when the model is initialized and do not change to reflect newly optimized values. To implement these, use an inequality expression. Use a switching point of 0.5 instead of 1 to avoid numerical issues with an integer value >1 or >=1. The solver tolerance is 1e-6 by default so a value of 0.999999 is considered the same as 1.000001 for convergence of equations. i = 0 for xi in x2: xi.value = blended_srp[i] m.Equation(xi >= m.if3((x1[i]) - 0.5, min_promo_price[i], window_lnuc_min_promo_price[i])) m.Equation(xi <= m.if3((x1[i]) - 0.5, max_promo_price[i], window_lnuc_max_promo_price[i])) i += 1  and i = 0 for xi in x3: xi.value = blended_nuc[i] m.Equation(xi >= m.if3((x1[i]) - 0.5, lnuc[i], window_lnuc[i])) xi.upper = 10 i += 1  The select of any four elements with m.Equation(sum(x1)<=4) is correct.
Question: I need to make multiple calls to a web endpoint that is somewhat unreliable, so I have put together a timeout/retry strategy that I issue to a requests.Session() object as an adapter. However, I also need to mount this same endpoint using a client PKCS12 certificate and a public certificate authority (verify), which I can easily perform with the requests_pkcs12 package - this also creates an adapter. So, adapter 1 looks like this, (pieced together with things I found across the internet): # timeout.py from requests.adapters import HTTPAdapter DEFAULT_TIMEOUT = 30 class TimeoutAdapter(HTTPAdapter): def __init__(self, *args, **kwargs): self.timeout = DEFAULT_TIMEOUT if "timeout" in kwargs: self.timeout = kwargs["timeout"] super().__init__(*args, **kwargs) def send(self, request, **kwargs): timeout = kwargs.get("timeout") if timeout is None: kwargs["timeout"] = self.timeout return super().send(request, **kwargs) ## set up adapter if __name__ == "__main__": from urllib3.util.retry import Retry u = 'https://some-webservice.com' s = requests.Session() retry_strategy = Retry( total=10, status_forcelist=[429, 500, 502, 503, 504], backoff_factor=1) s.mount(u, adapter=TimeoutAdapter(max_retries=retry_strategy)  Then, the second adapter looks like this: from requests import Session from requests_pkcs12 import Pkcs12Adapter pki_adapter = Pkcs12Adapter( pkcs12_filename='path/to/cert.p12', pkcs12_password='cert-password') u = 'https://some-webservice.com' s = requests.Session() s.mount(u, adapter=pki_adapter)  Both work lovely by themselves, but how would I go about merging them into a single adapter so that the session uses the PKI to authenticate, but also honors the timeout/retry strategy?

Answer: Assuming you want the default timeout behavior from TimeoutAdapter, then since TimeoutAdapter and Pkcs12Adapter both inherit from HTTPAdapter, you can have the former inherit from the latter (single inheritance). For example: # timeout.py from requests import Session from requests_pkcs12 import Pkcs12Adapter DEFAULT_TIMEOUT = 30 class TimeoutAdapter(Pkcs12Adapter): def __init__(self, *args, **kwargs): self.timeout = DEFAULT_TIMEOUT if "timeout" in kwargs: self.timeout = kwargs["timeout"] super().__init__(*args, **kwargs) def send(self, request, **kwargs): timeout = kwargs.get("timeout") if timeout is None: kwargs["timeout"] = self.timeout return super().send(request, **kwargs) ## set up adapter if __name__ == "__main__": from urllib3.util.retry import Retry retry_strategy = Retry( total=10, status_forcelist=[429, 500, 502, 503, 504], backoff_factor=1) timeout_adapter = TimeoutAdapter( max_retries=retry_strategy, pkcs12_filename='path/to/cert.p12', pkcs12_password='cert-password' ) u = 'https://some-webservice.com' s = requests.Session() s.mount(u, adapter=timeout_adapter)