eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I want to upgrade to python 3.10 in my google cloud shell, but I failed to do so. I found two methods online, which were unsuccessful so far.  Using the deadsnakes repo: I tried the following commands:  sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update  But I get an Error The repository 'http://ppa.launchpad.net/deadsnakes/ppa/ubuntu kinetic Release' does not have a Release file.  Install from the source: I followed the tutorial in this link. I am able to install python 3.10. But when my Google Cloud Shell restarts, I am unable to run python3.10. It states -bash: python3.10: command not found. 

Answer: This worked out for me. The default python version remained 3.10.7 even after the shell restarted. # install pyenv to install python on persistent home directory curl https://pyenv.run | bash # add to path echo 'export PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrc echo 'eval "$(pyenv init -)"' >> ~/.bashrc echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc # updating bashrc source ~/.bashrc # install python 3.10.7 and make default pyenv install 3.10.7 pyenv global 3.10.7 # execute python  credit to @ali-khorso and @yungchin. Link to the post
Question: I have a dictionary  {'n11' : {'n12a': {'n13a' : 10 , 'n13b' : "some text"}, 'n12b': {'n13c' : {'n14a': 40} } }, 'n21': {'n22a' : 20 } }  And I want to iterate through the dictionary until I reach a value which is not a dictionary, and replace it with the "full path" to that value.  {'n11' : {'n12a': {'n13a' : 'n11_n12a_n13a' , 'n13b' : 'n11_n12a_n13b'}, 'n12b': {'n13c' : {'n14a': 'n11_n12b_n13c_n14a'} } }, 'n21': {'n22a' : 'n21_n22a' } }  I know how to iterate through a nested dictionary with the following function, but I don't understand how to copy the same structure but with the updated value.  def myprint(d,path=[]): for k, v in d.items(): if isinstance(v, dict): path.append(k) myprint(v,path) else: print('_'.join(path)) output: 'n11_n12a_n13a' 'n11_n12a_n13b' 'n11_n12b_n13c_n14a' 'n21_n22a'  But how do I get it into another dictionary?

Answer: The most efficient way to do this would be using the same recursive function to not generate excess performance overhead. To copy the dictionary you can use copy.deepcopy() and then take that copy through the function, but replace the values instead of just printing the path: import copy data = {'n11': {'n12a': {'n13a': 10, 'n13b': "some text"}, 'n12b': {'n13c': {'n14a': 40}}}, 'n21': {'n22a': 20}} def myreplace(d, path=[]): for k, v in d.items(): if isinstance(v, dict): myreplace(v, path + [k]) else: print('_'.join(path + [k])) d[k] = '_'.join(path + [k]) return d copy_of_data = copy.deepcopy(data) copy_of_data = myreplace(copy_of_data) print(data) print(copy_of_data)  I had to modify the original function slightly to get it working.
Question: settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('USER_EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('USER_PASS')  Error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 4.1.1 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\smtplib.py, line 887, in sendmail Raised during: django.contrib.auth.views.PasswordResetView Python Executable: D:\Django\Tutorial\env\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\\Django\\Tutorial\\django_project', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\Django\\Tutorial\\env', 'D:\\Django\\Tutorial\\env\\lib\\site-packages'] Server time: Fri, 16 Sep 2022 06:10:41 +0000  urls.py:  path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html' ), name='password_reset_complete'), path("", include('blog.urls')),  I am trying to set an email password reset in my Django app but get this unexpected error. What I am trying to do here is I am using Django inbuild views PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView to reset my registered account's password through email. Can you help me with this or provide me with some links so I can reach the core of this error?

Answer: I have solved the issue the issue was with my Gmail account you need to go to the settings > security then create a new app password and then replace the Gmail password in settings.py with your newly created app password. I think your Gmail should also have 2-factor authentication, mine was already on but if you try this I think you should first try to turn on the 2-factor authentication and then try all these steps.
Question: I have df1 df1 = pd.DataFrame({'x':[1,2,3,5], 'y':[2,3,4,6], 'value':[1.5,2.0,0.5,3.0]}) df1 x y value 0 1 2 1.5 1 2 3 2.0 2 3 4 0.5 3 5 6 3.0  and I want to assign the value at x and y coordinates to another dataframe df2 df2 = pd.DataFrame(0.0, index=[x for x in range(0,df1['x'].max()+1)], columns=[y for y in range(0,df1['y'].max()+1)]) df2 0 1 2 3 4 5 6 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 4 0.0 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 0.0 0.0 0.0  by for x, y, value in zip(df1['x'],df1['y'],df1['value']): df2.at[x,y] = value  to give  0 1 2 3 4 5 6 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 1.5 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 2.0 0.0 0.0 0.0 3 0.0 0.0 0.0 0.0 0.5 0.0 0.0 4 0.0 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 0.0 0.0 3.0  However, it is a bit slow because I have a long df1. Do we have a faster method than df.at[x,y]?

Answer: You can avoid create zero df2 and using df.at method by DataFrame.pivot, DataFrame.fillna and DataFrame.reindex: df2 = (df1.pivot('x','y','value') .fillna(0) .reindex(index=range(df1['x'].max()+1), columns=range(df1['y'].max()+1), fill_value=0)) print (df2) y 0 1 2 3 4 5 6 x 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 1.5 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 2.0 0.0 0.0 0.0 3 0.0 0.0 0.0 0.0 0.5 0.0 0.0 4 0.0 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 0.0 0.0 3.0
Question: I have the following script: extras_require={"dev": dev_reqs} x = 3 entry_points={ "console_scripts": ["main=smamesdemo.run.main:main"] }  I want to retrieve the following part as python data, dict and list not Nodes. entry_points={ "console_scripts": ["main=smamesdemo.run.main:main"] }  I have tried the following, but I am not actually able to get the values with this: import ast class CustomNodeTransformer(ast.NodeTransformer): def visit_Assign(self, node): print(node.value.__dict__) return node with open("./setup.py") as f: code = f.read() node = ast.parse(code) CustomNodeTransformer().visit(node) {'keys': [<ast.Constant object at 0x0000029E992962C0>], 'values': [<ast.Name object at 0x0000029E99296260>], 'lineno': 1, 'col_offset': 15, 'end_lineno': 1, 'end_col_offset': 32}  Expected: entry_points={"console_scripts": ["main=smamesdemo.run.main:main"]}  Can anyone help me to achieve this?

Answer: You should use ast.NodeVisitor rather than ast.NodeTransformer since you are not making modifications to nodes. But for the purpose of retrieving a single node, it is simpler to use ast.walk instead to traverse the AST in a flat manner and find the ast.Assign node whose target id is 'entry_points', and then wrap its value in an ast.Expression node for compilation with compile and evaluation with eval into an actual Python dict. Remember to use ast.fix_missing_locations to realign the line numbers and offsets of the node when you plant it into another tree: import ast code = '''extras_require={"dev": dev_reqs} x = 3 entry_points={ "console_scripts": ["main=smamesdemo.run.main:main"] }''' for node in ast.walk(ast.parse(code)): if isinstance(node, ast.Assign) and node.targets[0].id == 'entry_points': expr = ast.Expression(body=node.value) ast.fix_missing_locations(expr) entry_points = eval(compile(expr, filename='', mode='eval')) print(entry_points)  This outputs: {'console_scripts': ['main=smamesdemo.run.main:main']}  Demo: https://replit.com/@blhsing/OrangeredCurlyApplication
Question: I have a json string that I want to read, convert it to an object that I can manipulate, and then convert it back into a json string. I am utilizing the python 3.10 dataclass, and one of the attributes of the class is another class (mySubClass). When I call json.loads(myClass), I get the following error: TypeError: Object of type mySubClass is not JSON serializable. Is there a way I can instantiate the dataclass myClass with everything it needs (including mySubClass), and then have a "post init operation" that will convert myClass.mySubClass into a simple json str? Or am I going about this the wrong way? My original goal was to have the following: import json from dataclasses import dataclass @dataclass mySubClass: sub_item1: str sub_item2: str @dataclass myClass: item1: str item2: mySubClass() ... convert_new_jsonStr_toObj = json.loads(received_json_str, object_hook=lambda d: SimpleNamespace(**d)) ... #: Get new values/do "stuff" to the received json string myClass_to_jsonStr = json.dumps(myClass(item1=convert_new_jsonStr_toObj.item1, item2=mySubClass(sub_item1=convert_new_jsonStr_toObj.sub_item1, sub_item2=convert_new_jsonStr_toObj.sub_item2))) ... #: Final json will look something like: processed_json_str = "{ "item1" : "new_item1", "item2" : { "sub_item1": "new_sub_item1", "sub_item2": "new_sub_item2" }" } #: send processed_json_str back out... #: Note: "processed_json_str" has the same structure as "received_json_str". 

Answer: If I've understood your question correctly, you can do something like this:: import json import dataclasses @dataclasses.dataclass class mySubClass: sub_item1: str sub_item2: str @dataclasses.dataclass class myClass: item1: str item2: mySubClass # We need a __post_init__ method here because otherwise # item2 will contain a python dictionary, rather than # an instance of mySubClass. def __post_init__(self): self.item2 = mySubClass(**self.item2) sampleData = ''' { "item1": "This is a test", "item2": { "sub_item1": "foo", "sub_item2": "bar" } } ''' myvar = myClass(**json.loads(sampleData)) myvar.item2.sub_item1 = 'modified' print(json.dumps(dataclasses.asdict(myvar)))  Running this produces: {"item1": "This is a test", "item2": {"sub_item1": "modified", "sub_item2": "bar"}}   As a side note, this all becomes easier if you use a more fully featured package like pydantic: import json from pydantic import BaseModel class mySubClass(BaseModel): sub_item1: str sub_item2: str class myClass(BaseModel): item1: str item2: mySubClass sampleData = ''' { "item1": "This is a test", "item2": { "sub_item1": "foo", "sub_item2": "bar" } } ''' myvar = myClass(**json.loads(sampleData)) myvar.item2.sub_item1 = 'modified' print(myvar.json())
Question: The Django docs says that one can use .label, but it does not work in the template. class Model(models.Model): class ModelChoices(models.TextChoices): ENUM = 'VALUE', 'Label' model_choice = models.CharField(choices=ModelChoices.choices)  In the template object.model_choice displays the value ('VALUE'). object.model_choice.label displays nothing. How is it possible to get the label ('Label') in the template?

Answer: You'd use get_{field_name}_display Python modelObj.get_model_choice_display()  Template {{modelObj.get_model_choice_display}}
Question: I have troubles replicating a JupyterLab install on a new PC. It is working fine on my previous one. I am unable to display simple widgets (like a checkbox from ipywidgets or ipyvuetify). I checked that jupyter-widgets is enabled with jupyter labextension list. The results is : jupyter-vue v1.7.0 enabled ok jupyter-vuetify v1.8.4 enabled ok @jupyter-widgets/jupyterlab-manager v5.0.2 enabled ok (python, jupyterlab_widgets)  In the notebook, when i try to display a widget, the cell displays a Javascrip error : [Open Browser Console for more detailed log - Double click to close this message] Failed to load model class 'CheckboxModel' from module '@jupyter-widgets/controls' Error: Module @jupyter-widgets/controls, version ^1.5.0 is not registered, however, 2.0.0 is at f.loadClass (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/134.083e6b37f2f7b2f04b5e.js?v=083e6b37f2f7b2f04b5e:1:74976) at f.loadModelClass (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/150.467514c324d2bcc23502.js?v=467514c324d2bcc23502:1:10721) at f._make_model (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/150.467514c324d2bcc23502.js?v=467514c324d2bcc23502:1:7517) at f.new_model (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/150.467514c324d2bcc23502.js?v=467514c324d2bcc23502:1:5137) at f.handle_comm_open (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/150.467514c324d2bcc23502.js?v=467514c324d2bcc23502:1:3894) at _handleCommOpen (http://localhost:8888/lab/extensions/@jupyter-widgets/jupyterlab- manager/static/134.083e6b37f2f7b2f04b5e.js?v=083e6b37f2f7b2f04b5e:1:73392) at b._handleCommOpen (http://localhost:8888/static/lab/jlab_core.86360d749a1ef5f29afb.js? v=86360d749a1ef5f29afb:2:924842) at async b._handleMessage (http://localhost:8888/static/lab/jlab_core.86360d749a1ef5f29afb.js? v=86360d749a1ef5f29afb:2:926832) 

Answer: That error is consistent with one noted here in an issue report recently. The suggestion there is to change to ipywidgets version 7.7.2 or 7.6.5 to fix this issue. Also, see the note here, too.
Question: I am unclear on whether to use typing or ABC classes for collection type hints in Python. It seems one can use either one, but the name typing suggests that's the preferred one. However, I see several places saying collections.abc should be used instead, not least PEP 585. I am getting the sense that typing was created to support generics but that generics is being extended to the "regular" classes so typing is becoming obsolete. Is that the correct understanding?

Answer: Yes. collections.abc is the correct module going forward. Collections in typing have been deprecated since 3.9
Question: I'm trying to connect a C++ program to python using shared memory but I don't know how to pass the name of the memory segment to python. Here is my C++ code: key_t key = ftok("address", 1); int shm_o; char* msg = "hello there"; int len = strlen(msg) + 1; void* addr; shm_o = shmget(key, 20, IPC_CREAT | 0600); if(shm_o == -1) { std::cout << "Failed: shmget.\n"; return 1; } addr = shmat(shm_o, NULL, 0); if(addr == (void*) -1) { std::cout << "Failed: shmat.\n"; return 1; } std::cout << "Shared memory segment created successfully with id: " << shm_o; memcpy(addr, msg, len); getchar(); return 0;  I'm trying to get python to read from the shared memory segment like so: shm_a = shared_memory.SharedMemory(name="address", create=False, size=20) print(bytes(shm_a.buf[:11]))  but it throws an exception saying there is no file or directory called 'address'. Am I going about this correctly or is there another way to attach python to the shared memory segment? Any help would be much appreciated.

Answer: Taking the liberty to post a working example here for POSIX shared memory segments, which will work across C/C++ and Python on Linux/UNIX-like systems. This will not work on Windows. C++ code to create and write data into a shared memory segment (name provided on command line): #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <iostream> #include <string> int main(int argc, char * argv[]) { if (argc != 2) { std::cerr << "Argument <shmem_name> required" << std::endl; return 1; } const char * shmem_name = argv[1]; size_t shm_size = 4096; int shmem_fd = shm_open(shmem_name, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); if (shmem_fd == -1) { perror("shm_open"); return 1; } std::cout << "Shared Memory segment created with fd " << shmem_fd << std::endl; if (ftruncate(shmem_fd, shm_size) == -1) { perror("ftruncate"); return 1; } std::cout << "Shared Memory segment resized to " << shm_size << std::endl; void * addr = mmap(0, shm_size, PROT_WRITE, MAP_SHARED, shmem_fd, 0); if (addr == MAP_FAILED) { perror("mmap"); return 1; } std::cout << "Please enter some text to write to shared memory segment\n"; std::string text; std::getline(std::cin, text); while (! text.empty()) { strncpy((char *)addr, text.data(), shm_size); std::cout << "Written '" << text << "' to shared memory segment\n"; std::getline(std::cin, text); } std::cout << "Unlinking shared memory segment." << std::endl; shm_unlink(shmem_name) ; }  Python code to read any string from the beginning of the shared memory segment: import sys from multiprocessing import shared_memory, resource_tracker if len(sys.argv) != 2: print("Argument <shmem_name> required") sys.exit(1) shm_seg = shared_memory.SharedMemory(name=sys.argv[1]) print(bytes(shm_seg.buf).strip(b'\x00').decode('ascii')) shm_seg.close() # Manually remove segment from resource_tracker, otherwise shmem segment # will be unlinked upon program exit resource_tracker.unregister(shm_seg._name, "shared_memory")
Question: I am running a couple of services with docker compose. The data-loader service has to wait for the translator, but once the data-loader is running, the healthcheck does not stop executing, even after exiting. translator: build: ./translator container_name: translator command: uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 healthcheck: test: curl -f translator:8000/healthcheck || exit 1 interval: 5s timeout: 5s retries: 5 env_file: - ./translator/.env networks: - fds-network ports: - 8000:8000 restart: always depends_on: - redis volumes: - ./translator:/app/ data-loader: build: context: ./data-loader dockerfile: Dockerfile container_name: data-loader command: python3 app/main.py environment: - "DOCKER=true" - "BASE_LANG=es" - "LOAD_DISEASES=false" depends_on: cassandra-load-keyspace: condition: service_completed_successfully translator: condition: service_healthy env_file: - ./data-loader/.env networks: - fds-network  The endpoint for the healthcheck: @app.get("/healthcheck") async def healthcheck(): return {"status": "ok"}  And this is the console output: cassandra-load-keyspace exited with code 0 data-loader | Dataloader connected to Cassandra data-loader | Dataloader started data-loader | load diseases False data-loader | Skipping disease loading translator | INFO: 172.18.0.4:46638 - "GET /healthcheck HTTP/1.1" 200 OK data-loader exited with code 0 translator | INFO: 172.18.0.4:56822 - "GET /healthcheck HTTP/1.1" 200 OK translator | INFO: 172.18.0.4:56836 - "GET /healthcheck HTTP/1.1" 200 OK translator | INFO: 172.18.0.4:40618 - "GET /healthcheck HTTP/1.1" 200 OK translator | INFO: 172.18.0.4:40624 - "GET /healthcheck HTTP/1.1" 200 OK translator | INFO: 172.18.0.4:51620 - "GET /healthcheck HTTP/1.1" 200 OK translator | INFO: 172.18.0.4:51630 - "GET /healthcheck HTTP/1.1" 200 OK  and so on. If the data-loader service is running it is because the healthcheck was OK, and the number of calls to the endpoint is greater to the number of tries in the condition for the healthcheck, and no more services nor functions call that endpoint, so it must be the healthechk at the compose. What is wrong here?

Answer:  so it must be the healthechk at the compose.  Yes, translator health check is run by docker, which will keep running the health check every 5 seconds interval: 5s, whether there are any dependent services running or not.
Question: I would like to create a new column every time I get 1 in the 'Signal' column that will cast the corresponding value from the 'Value' column (please see the expected output below). Initial data:     Index Value Signal     0 3 0   1 8 0   2 8 0   3 7 1   4 9 0   5 10 0   6 14 1   7 10 0   8 10 0   9 4 1   10 10 0   11 10 0     Expected Output:     Index Value Signal New_Col_1 New_Col_2 New_Col_3     0 3 0 0 0 0   1 8 0 0 0 0   2 8 0 0 0 0   3 7 1 7 0 0   4 9 0 7 0 0   5 10 0 7 0 0   6 14 1 7 14 0   7 10 0 7 14 0   8 10 0 7 14 0   9 4 1 7 14 4   10 10 0 7 14 4   11 10 0 7 14 4     What would be a way to do it?

Answer: You can use a pivot: out = df.join(df # keep only the values where signal is 1 # and get Signal's cumsum .assign(val=df['Value'].where(df['Signal'].eq(1)), col=df['Signal'].cumsum() ) # pivot cumsumed Signal to columns .pivot(index='Index', columns='col', values='val') # ensure column 0 is absent (using loc to avoid KeyError) .loc[:, 1:] # forward fill the values .ffill() # rename columns .add_prefix('New_Col_') )  output:  Index Value Signal New_Col_1 New_Col_2 New_Col_3 0 0 3 0 NaN NaN NaN 1 1 8 0 NaN NaN NaN 2 2 8 0 NaN NaN NaN 3 3 7 1 7.0 NaN NaN 4 4 9 0 7.0 NaN NaN 5 5 10 0 7.0 NaN NaN 6 6 14 1 7.0 14.0 NaN 7 7 10 0 7.0 14.0 NaN 8 8 10 0 7.0 14.0 NaN 9 9 4 1 7.0 14.0 4.0 10 10 10 0 7.0 14.0 4.0 11 11 10 0 7.0 14.0 4.0
Question: I am wondering what's the best way to format a function with multiple arguments. Suppose I have a function with many arguments with potentially long argument names or default values such as for example: def my_function_with_a_long_name(argument1="this is a long default value", argument2=["some", "long", "default", "values"]): pass  Naturally, I would try to make the function more readable. Following the pep8 styling guide https://peps.python.org/pep-0008/ I have multiple options to format such function: I can use a hanging indent with extra indentation of the arguments: def my_function( a="a", b="b", c="c"): pass  I could also put the first argument on the first line and align the following arguments with it: def my_function(a="a", b="b", c="c" ): pass  My linter also accepts the following option, though I'm not sure it is in agreement with pep8: def my_function( a="a", b="b", c="c" ): pass  None of these options looks 100% 'clean' to me. I guess the first option seems cleanest though it bothers me a bit to have the parenthesis on the same line as the last argument. However, putting the parenthesis on an extra line seems to conflict with pep8: def my_function( a="a", b="b", c="c" ): pass  Now I am wondering, while multiple options might be acceptable if we only consider pep8, is there one option that is generally agreed on in the python community? Are there arguments for or against any of these options or does just come down to personal preference? In a collaborative project, which option would you choose and why?

Answer: If pep8 doesn't strictly say that you have to use this style, you're free to choose between correct ones. But why bothering yourself to format it manually? The only important thing is to be consistent in your code. So just leave it to a formatter. That takes care of it. I would suggest Black. Written by a core developer - Łukasz Langa It formats your function to: def my_function_with_a_long_name( argument1="this is a long default value", argument2=["some", "long", "default", "values"], ): pass   Update I still do recommend the formatting style of "Black", but there is a relatively new popular package called Ruff which is almost considered as a drop-in replacement for "Black". (99% compatible) It's super fast and it does other things too. Check the documentation.