Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Could not read the parquet files: Arrow type extension<arrow.json> does not have a datasets dtype equivalent.
Error code:   FileSystemError

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

question_id
int64
score
int64
creation_date
int64
tags
string
instruction
string
output
string
231,767
13,124
1,224,800,471
["python","iterator","generator","yield"]
What does the "yield" keyword do in Python? What functionality does the yield keyword in Python provide? For example, I'm trying to understand this code1: def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild ...
To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables. Iterables When you create a list, you can read its items one by one. Reading its items one by one is called iteration: >>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i)...
419,163
8,430
1,231,301,460
["python","namespaces","program-entry-point","python-module","idioms"]
What does if __name__ == "__main__": do? What does this do, and why should one include the if statement? if __name__ == "__main__": print("Hello, World!") If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my module when I ...
Short Answer It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script: If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter scrip...
89,228
6,286
1,221,701,730
["python","shell","terminal","subprocess","command"]
How do I execute a program or call a system command? How do I call an external command within Python as if I had typed it in a shell or command prompt?
Use subprocess.run: import subprocess subprocess.run(["ls", "-l"]) Another common way is os.system but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run is generally more flexible (you can get the s...
522,563
5,669
1,233,960,474
["python","loops","list"]
How can I access the index value in a 'for' loop? How do I access the index while iterating over a sequence with a for loop? xs = [8, 23, 45] for x in xs: print("item #{} = {}".format(index, x)) Desired output: item #1 = 8 item #2 = 23 item #3 = 45
Use the built-in function enumerate(): for idx, x in enumerate(xs): print(idx, x) It is non-Pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable. Check out PEP 279 for more.
952,914
5,505
1,244,147,405
["python","list","multidimensional-array","flatten"]
How do I make a flat list out of a list of lists? I have a list of lists like [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]? If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please s...
A list of lists named xss can be flattened using a nested list comprehension: flat_list = [ x for xs in xss for x in xs ] The above is equivalent to: flat_list = [] for xs in xss: for x in xs: flat_list.append(x) Here is the corresponding function: def flatten(xss): return [x for xs in xss for x in xs] This is the fast...
509,211
4,704
1,233,700,262
["python","slice","sequence"]
How slicing in Python works How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? See Why are slice and range upper-bound exclusive? to learn why xs[0:2] == [xs[0], xs[1]], not [..., xs[2]]. See Make a new list conta...
The syntax is: a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array There is also the step value, which can be used with any of the above: a[start:stop:step] # start through not past stop, by ...
16,476,924
4,246
1,368,169,489
["python","pandas","dataframe","loops"]
How can I iterate over rows in a Pandas DataFrame? I have a pandas dataframe, df: c1 c2 0 10 100 1 11 110 2 12 120 How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example: for row in df.rows: print(row['c1'], row['c2']) I ...
DataFrame.iterrows is a generator which yields both the index and row (as a Series): import pandas as pd df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # make sure indexes pair with number of rows for index, row in df.iterrows(): print(row['c1'], row['c2']) 10 100 11 110 12 120 Obl...
423,379
4,047
1,231,393,502
["python","global-variables","scope"]
How can I use a global variable in a function? How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? Failing to use the global keyword where appropriate often causes UnboundLocalError. The precise rules for this are explained...
You can use a global variable within other functions by declaring it as global within each function that assigns a value to it: globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print(globvar) # No need for global declaration to read value of...
415,511
3,992
1,231,217,663
["python","datetime","time"]
How do I get the current time in Python? How do I get the current time in Python?
Use datetime: >>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> str(now) '2009-01-06 15:08:24.078915' For just the clock time without the date: >>> now.time() datetime.time(15, 8, 24, 78915) >>> str(now.time()) '15:08:24.078915' To save typing, you can imp...
606,191
3,885
1,236,082,981
["python","string","python-3.x"]
Convert bytes to a string in Python 3 I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 fil...
Decode the bytes object to produce a string: >>> b"abcde".decode("utf-8") 'abcde' The above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!
1,436,703
3,831
1,253,161,665
["python","magic-methods","repr"]
What is the difference between __str__ and __repr__? What is the difference between __str__ and __repr__ in Python?
Alex Martelli summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained ob...
17,071,871
3,632
1,371,058,925
["python","pandas","dataframe","indexing","filter"]
How do I select rows from a DataFrame based on column values? How can I select rows from a DataFrame based on values in some column in Pandas? In SQL, I would use: SELECT * FROM table WHERE column_name = some_value
To select rows whose column value equals a scalar, some_value, use ==: df.loc[df['column_name'] == some_value] To select rows whose column value is in an iterable, some_values, use isin: df.loc[df['column_name'].isin(some_values)] Combine multiple conditions with &: df.loc[(df['column_name'] >= A) & (df['column_name'] ...
3,437,059
3,585
1,281,322,370
["python","string","substring","contains"]
Does Python have a string 'contains' substring method? I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains("blah"): continue
Use the in operator: if "blah" not in somestring: continue Note: This is case-sensitive.
6,996,603
3,543
1,312,895,142
["python","file-io","directory","delete-file"]
How can I delete a file or folder in Python? How can I delete a file or folder in Python?
Use one of these methods: pathlib.Path.unlink() removes a file or symbolic link. pathlib.Path.rmdir() removes an empty directory. shutil.rmtree() deletes a directory and all its contents. On Python 3.3 and below, you can use these methods instead of the pathlib ones: os.remove() removes a file. os.unlink() removes a sy...
1,132,941
3,509
1,247,680,837
["python","language-design","default-parameters","least-astonishment"]
"Least Astonishment" and the Mutable Default Argument def foo(a=[]): a.append(5) return a Python novices expect this function called with no parameter to always return a list with only one element: [5]. The result is different and astonishing: >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5, 5, 5] >...
Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code. As soon as you think of it this way, then it completely makes sense: a function is an object being evaluated on its defini...
36,901
3,498
1,220,195,075
["python","syntax","parameter-passing","variadic-functions","argument-unpacking"]
What does ** (double star/asterisk) and * (star/asterisk) do for parameters? What do *args and **kwargs mean in these function definitions? def foo(x, y, *args): pass def bar(x, y, **kwargs): pass See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about ...
The *args and **kwargs are common idioms to allow an arbitrary number of arguments to functions, as described in the section more on defining functions in the Python tutorial. The *args will give you all positional arguments as a tuple: def foo(*args): for a in args: print(a) foo(1) # 1 foo(1, 2, 3) # 1 # 2 # 3 The **k...
2,612,802
3,368
1,270,889,386
["python","list","clone","mutable"]
How do I clone a list so that it doesn't change unexpectedly after assignment? While using new_list = my_list, any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it? For example: >>> my_list = [1, 2, 3] >>> new_list = my_list >>> new_list.append(4) >>...
new_list = my_list doesn't actually create a second list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment. To actually copy the list, you have several options: You can use the built-in list.copy() method (available since...
1,720,421
3,238
1,258,009,449
["python","list","concatenation"]
How do I concatenate two lists in Python? How do I concatenate two lists in Python? Example: listone = [1, 2, 3] listtwo = [4, 5, 6] Expected outcome: >>> joinedlist [1, 2, 3, 4, 5, 6]
Use the + operator to combine the lists: listone = [1, 2, 3] listtwo = [4, 5, 6] joinedlist = listone + listtwo Output: >>> joinedlist [1, 2, 3, 4, 5, 6] NOTE: This will create a new list with a shallow copy of the items in the first list, followed by a shallow copy of the items in the second list. Use copy.deepcopy() ...
252,703
3,109
1,225,432,536
["python","list","data-structures","append","extend"]
What is the difference between Python's list methods append and extend? What's the difference between the list methods append() and extend()?
.append() appends a single object at the end of the list: >>> x = [1, 2, 3] >>> x.append([4, 5]) >>> print(x) [1, 2, 3, [4, 5]] .extend() appends multiple objects that are taken from inside the specified iterable: >>> x = [1, 2, 3] >>> x.extend([4, 5]) >>> print(x) [1, 2, 3, 4, 5]
11,277,432
3,013
1,341,088,079
["python","dictionary","unset"]
How can I remove a key from a Python dictionary? I want to remove a key from a dictionary if it is present. I currently use this code: if key in my_dict: del my_dict[key] Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply? See Delete an element from a di...
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop(): my_dict.pop('key', None) This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is rai...
2,720,014
2,887
1,272,360,205
["python","pip","pypi"]
How to upgrade all Python packages with pip Is it possible to upgrade all Python packages at one time with pip? Note: that there is a feature request for this on the official issue tracker.
There isn't a built-in flag yet. Starting with pip version 22.3, the --outdated and --format=freeze have become mutually exclusive. Use Python, to parse the JSON output: pip --disable-pip-version-check list --outdated --format=json | python -c "import json, sys; print('\n'.join([x['name'] for x in json.load(sys.stdin)]...
72,899
2,856
1,221,575,267
["python","list","sorting","dictionary","data-structures"]
How can I sort a list of dictionaries by a value of the dictionary in Python? How do I sort a list of dictionaries by a specific key's value? Given: [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] When sorted by name, it should become: [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name')) For completeness, add reverse=Tru...
379,906
2,778
1,229,651,546
["python","parsing","floating-point","type-conversion","integer"]
How do I parse a string to a float or int? How can I convert an str to a float? "545.2222" -> 545.2222 Or an str to a int? "31" -> 31 For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it. Please instead use How can I read inputs as numbers? to close duplicate ...
>>> a = "545.2222" >>> float(a) 545.22220000000004 >>> int(float(a)) 545
1,602,934
2,675
1,256,151,909
["python","dictionary"]
Check if a given key already exists in a dictionary I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: if 'key1' in dict.keys(): print "blah" else: print "boo" I think this is not the best way to accomplish this task. Is there a better way to test for a ...
in tests for the existence of a key in a dict: d = {"key1": 10, "key2": 23} if "key1" in d: print("this will execute") if "nonexistent key" in d: print("this will not") Use dict.get() to provide a default value when the key does not exist: d = {} for i in range(100): key = i % 10 d[key] = d.get(key, 0) + 1 To provide a...
610,883
2,534
1,236,177,959
["python","class","object","attributes","attributeerror"]
How can I check if an object has an attribute? How do I check if an object has some attribute? For example: >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' How do I tell if a has the attribute prope...
Try hasattr(): if hasattr(a, 'property'): a.property See zweiterlinde's answer, which offers good advice about asking forgiveness! It is a very Pythonic approach! The general practice in Python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or tra...
12,943,819
2,053
1,350,509,923
["python","json","formatting","pretty-print"]
How to prettyprint a JSON file? How do I pretty-print a JSON file in Python?
Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by: >>> import json >>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> parsed = json.loads(your_json) >>> print(json.dumps(parsed, indent=4)) [ "foo", { "bar": [ "baz", null, 1.0, 2 ] } ] To parse a file, use json.l...
354,038
2,022
1,228,853,022
["python","casting","floating-point","type-conversion","integer"]
How do I check if a string represents a number (float or int)? How do I check if a string represents a numeric value in Python? def is_number(s): try: float(s) return True except ValueError: return False The above works, but it seems clunky. Editor's note: If what you are testing comes from user input, it is still a s...
Which, not only is ugly and slow I'd dispute both. A regex or other string parsing method would be uglier and slower. I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/except doesn't introduce much overhead because the most common exception is caught without an exten...
7,225,900
1,990
1,314,589,984
["python","pip","virtualenv","requirements.txt"]
How can I install packages using pip according to the requirements.txt file from a local directory? Here is the problem: I have a requirements.txt file that looks like: BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3 ......
This works for me: pip install -r requirements.txt --no-index --find-links file:///tmp/packages --no-index - Ignore package index (only look at --find-links URLs instead). -f, --find-links <URL> - If <URL> is a URL or a path to an HTML file, then parse for links to archives. If <URL> is a local path or a file:// URL th...
14,132,789
1,899
1,357,185,040
["python","python-import","relative-path","python-packaging","relative-import"]
Relative imports for the billionth time I've been here: PEP 328 – Imports: Multi-Line and Absolute/Relative Modules, Packages Python packages: relative imports Python relative import example code does not work Relative imports in Python 2.5 Relative imports in Python Python: Disabling relative import and plenty of URL...
Script vs. Module Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. Just knowing what directory a file is in does not determine what package Python thinks it is in. That depends, additionally, on how you load t...
16,981,921
1,885
1,370,600,810
["python","python-3.x","python-import"]
Relative imports in Python 3 I want to import a function from another file in the same directory. Usually, one of the following works: from .mymodule import myfunction from mymodule import myfunction ...but the other one gives me one of these errors: ImportError: attempted relative import with no known parent package ...
unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that? It's quite common to have a layout like this... main.py mypackage/ __init__.py mymodule.py myothermodule.py ...with a mymodule.py like this... #!/usr/bin/env python3 # E...
67,631
1,872
1,221,517,855
["python","python-import","python-module"]
How can I import a module dynamically given the full path? How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. See also: How to import a module given its name as string?
Let's have MyClass in module.name module defined at /path/to/file.py. Below is how we import MyClass from this module For Python 3.5+ use (docs): import importlib.util import sys spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) sys.modules["mod...
5,574,702
1,817
1,302,137,950
["python","printing","stderr"]
How do I print to stderr in Python? There are several ways to write to stderr: print >> sys.stderr, "spam" # Python 2 only. sys.stderr.write("spam\n") os.write(2, b"spam\n") from __future__ import print_function print("spam", file=sys.stderr) What are the differences between these methods? Which method should be prefe...
I found this to be the only one short, flexible, portable and readable: import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) The optional function eprint saves some repetition. It can be used in the same way as the standard print function: >>> print("Test") Test >>> eprint("Test") Test >>> ep...
6,760,685
1,809
1,311,158,877
["python","singleton","decorator","base-class","metaclass"]
What is the best way of implementing a singleton in Python? I have multiple classes which would become singletons (my use case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate. Best methods: Method 1: A decorator def singleton(...
You just need a decorator, different depending on the python version. Notice how foo gets printed only once. Python 3.2+ Implementation: from functools import lru_cache @lru_cache(maxsize=None) class CustomClass(object): def __init__(self, arg): print(f"CustomClass initialised with {arg}") self.arg = arg Usage c1 = Cus...
678,236
1,789
1,237,912,863
["python","string","path"]
How do I get the filename without the extension from a path in Python? How do I get the filename without the extension from a path in Python? "/path/to/some/file.txt" → "file"
Python 3.4+ Use pathlib.Path.stem >>> from pathlib import Path >>> Path("/path/to/file.txt").stem 'file' >>> Path("/path/to/file.tar.gz").stem 'file.tar' Python < 3.4 Use os.path.splitext in combination with os.path.basename: >>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0] 'file' >>> os.path.splitext(os....
582,336
1,758
1,235,491,286
["python","performance","optimization","time-complexity","profiling"]
How do I profile a Python script? Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to __main__. What is a good way to profile how long a Python progr...
Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations. You can call it from within your code, or from the interpreter, like this...
4,700,614
1,723
1,295,107,803
["python","matplotlib","seaborn","legend"]
How to put the legend outside the plot I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. I want to keep the legend box outside the plot area (I want the legend...
You can make the legend text smaller by specifying set_size of FontProperties. Resources: Legend guide matplotlib.legend matplotlib.pyplot.legend matplotlib.font_manager set_size(self, size) Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, and None. Real Python: Python Pl...
60,208
1,716
1,221,266,190
["python","switch-statement"]
Replacements for switch statement in Python? I want to write a function in Python that returns different fixed values based on the value of an input index. In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this...
Python 3.10 (2021) introduced the match-case statement, which provides a first-class implementation of a "switch" for Python. For example: def f(x): match x: case 'a': return 1 case 'b': return 2 case _: return 0 # 0 is the default case if x is not found The match-case statement is considerably more powerful than this ...
1,471,994
1,656
1,253,801,812
["python","pypi","setup.py","python-packaging"]
What is setup.py? What is setup.py and how can it be configured or used?
setup.py is a Python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules. This allows you to easily install Python packages. Often it's enough to write: $ pip install ...
1,747,817
1,612
1,258,452,473
["python","dictionary","list-comprehension","dictionary-comprehension"]
Create a dictionary with comprehension Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values: d = {... for k, v in zip(keys, values)}
Use a dict comprehension (Python 2.7 and later): {key: value for key, value in zip(keys, values)} Alternatively, use the dict constructor: pairs = [('a', 1), ('b', 2)] dict(pairs) # → {'a': 1, 'b': 2} dict((k, v + 10) for k, v in pairs) # → {'a': 11, 'b': 12} Given separate lists of keys and values, use the dict constr...
961,632
1,595
1,244,370,158
["python","string","integer"]
Convert integer to string in Python How do I convert an integer to a string? 42 ⟶ "42" For the reverse, see How do I parse a string to a float or int?. Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise. See Converting a float to a string withou...
>>> str(42) '42' >>> int('42') 42 Links to the documentation: int() str() str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.
8,858,008
1,533
1,326,493,078
["python","file","file-handling","python-os"]
How do I move a file in Python? How can I do the equivalent of mv in Python? mv "path/to/current/file.foo" "path/to/new/destination/for/file.foo"
os.rename(), os.replace(), or shutil.move() All employ the same syntax: import os import shutil os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo") os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo") shutil.move("path/to/current/file.foo", "path/to/new/destination/fo...
9,942,594
1,518
1,333,109,201
["python","unicode","beautifulsoup","python-2.x","python-unicode"]
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; it sometime...
Read the Python Unicode HOWTO. This error is the very first example. Do not use str() to convert from unicode to encoded text / bytes. Instead, use .encode() to encode the string: p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip() or work entirely in unicode.
3,768,895
1,510
1,285,156,339
["python","json","serialization"]
How to make a class JSON serializable How to make a Python class serializable? class FileItem: def __init__(self, fname): self.fname = fname Attempt to serialize to JSON: >>> import json >>> x = FileItem('/foo/bar') >>> json.dumps(x) TypeError: Object of type 'FileItem' is not JSON serializable
Do you have an idea about the expected output? For example, will this do? >>> f = FileItem("/foo/bar") >>> magic(f) '{"fname": "/foo/bar"}' In that case you can merely call json.dumps(f.__dict__). If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization. ...
31,684,375
1,508
1,438,108,143
["python","dependencies","python-import","requirements.txt"]
Automatically create file 'requirements.txt' Sometimes I download the Python source code from GitHub and don't know how to install all the dependencies. If there isn't any requirements.txt file I have to create it by hand. Given the Python source code directory, is it possible to create requirements.txt automatically ...
Use Pipenv or other tools is recommended for improving your development flow. pip3 freeze > requirements.txt # Python3 pip freeze > requirements.txt # Python2 If you do not use a virtual environment, pigar will be a good choice for you.
1,952,464
1,469
1,261,570,435
["python","iterable"]
Python: how to determine if an object is iterable? Is there a method like isiterable? The only solution I have found so far is to call: hasattr(myObj, '__iter__') but I am not sure how foolproof this is.
Checking for __iter__ works on sequence types, but it would fail on e.g. strings in Python 2. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too): try: some_object_iterator = iter(some_object) except TypeError as te: print(some_object, 'is not iterable') The...
17,330,160
1,427
1,372,279,635
["python","properties","decorator","python-decorators","python-internals"]
How does the @property decorator work in Python? I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the documentation:...
The property() function returns a special descriptor object: >>> property() <property object at 0x10ff07940> It is this object that has extra methods: >>> property().getter <built-in method getter of property object at 0x10ff07998> >>> property().setter <built-in method setter of property object at 0x10ff07940> >>> pro...
8,369,219
1,411
1,322,930,874
["python","string"]
How can I read a text file into a string variable and strip newlines? I have a text file that looks like: ABC DEF How can I read the file into a single-line string without newlines, in this case creating a string 'ABCDEF'? For reading the file into a list of lines, but removing the trailing newline character from each...
You could use: with open('data.txt', 'r') as file: data = file.read().replace('\n', '') Or if the file content is guaranteed to be one line: with open('data.txt', 'r') as file: data = file.read().rstrip()
11,248,073
1,409
1,340,897,804
["python","pip","virtualenv","python-packaging"]
How do I remove all packages installed by pip? How do I uninstall all packages installed by pip from my currently activated virtual environment?
I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv: pip freeze | xargs pip uninstall -y In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below): pip freeze --e...
2,802,726
1,405
1,273,496,284
["python","if-statement","syntax","conditional-operator"]
Putting a simple if-then-else statement on one line How do I write an if-then-else statement in Python so that it fits on one line? For example, I want a one line version of: if count == N: count = 0 else: count = N + 1 In Objective-C, I would write this as: count = count == N ? 0 : count + 1;
That's more specifically a ternary operator expression than an if-then, here's the python syntax value_when_true if condition else value_when_false Better Example: (thanks Mr. Burns) 'Yes' if fruit == 'Apple' else 'No' Now with assignment and contrast with if syntax fruit = 'Apple' isApple = True if fruit == 'Apple' el...
33,533,148
1,383
1,446,675,474
["python","pycharm","python-typing"]
How do I type hint a method with the type of the enclosing class? I have the following code in Python 3: class Position: def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other: Position) -> Position: return Position(self.x + other.x, self.y + other.y) But my editor (PyCharm) says that the re...
I guess you got this exception: NameError: name 'Position' is not defined This is because in the original implementation of annotations, Position must be defined before you can use it in an annotation. Python 3.14+: It'll just work Python 3.14 has a new, lazily evaluated annotation implementation specified by PEP 749 a...
2,709,821
1,360
1,272,226,948
["python","class","oop","self"]
What is the purpose of the `self` parameter? Why is it needed? Consider this example: class MyClass: def func(self, name): self.name = name I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a parameter? Why do we need to use self in the method's code? Some other ...
The reason you need to use self is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically but not received automatically, the first parameter of methods is the instance the method is ca...
715,417
1,358
1,238,787,860
["python","string","boolean"]
Converting from a string to boolean in Python How do I convert a string into a boolean in Python? This attempt returns True: >>> bool("False") True
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this: s == 'True' Or to checks against a whole bunch of values: s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] Be cautious when using the following: >>> bool("foo") True >>> bool("...
534,839
1,342
1,234,309,881
["python","uuid","guid","uniqueidentifier"]
How to create a GUID/UUID in Python How do I create a GUID/UUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() or uuid4(). Note that uuid1() may compromise privacy since it creat...
1,504,717
1,332
1,254,411,614
["python","string","comparison","identity","equality"]
Why does comparing strings using either '==' or 'is' sometimes produce a different result? Two string variables are set to the same value. s1 == s2 always returns True, but s1 is s2 sometimes returns False. If I open my Python interpreter and do the same is comparison, it succeeds: >>> s1 = 'text' >>> s2 = 'text' >>> ...
is is identity testing, and == is equality testing. What happens in your code would be emulated in the interpreter like this: >>> a = 'pub' >>> b = ''.join(['p', 'u', 'b']) >>> a == b True >>> a is b False So, no wonder they're not the same, right? In other words: a is b is the equivalent of id(a) == id(b)
845,058
1,323
1,241,950,925
["python","text-files","line-count"]
How to get the line count of a large file cheaply in Python How do I get a line count of a large file in the most memory- and time-efficient manner? def file_len(filename): with open(filename) as f: for i, _ in enumerate(f): pass return i + 1
You can't get any better than that. After all, any solution will have to read the entire file, figure out how many \n you have, and return that result. Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't u...
739,993
1,322
1,239,453,258
["python","module","pip"]
How do I get a list of locally installed Python modules? How do I get a list of Python modules installed on my computer?
Solution Do not use with pip > 10.0! My 50 cents for getting a pip freeze-like list from a Python script: import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) As a (too long) one lin...
7,604,966
1,319
1,317,344,466
["python","integer"]
Maximum and Minimum values for ints How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE. See also: What is the maximum float in Python?.
Python 3 In Python 3, this question doesn't apply. The plain int type is unbounded. However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is ...
1,823,058
1,309
1,259,622,703
["python","number-formatting"]
How to print a number using commas as thousands separators How do I print an integer with commas as thousands separators? 1234567 ⟶ 1,234,567 It does not need to be locale-specific to decide between periods and commas.
Locale-agnostic: use _ as the thousand separator f'{value:_}' # For Python ≥3.6 Note that this will NOT format in the user's current locale and will always use _ as the thousand separator, so for example: 1234567 ⟶ 1_234_567 English style: use , as the thousand separator '{:,}'.format(value) # For Python ≥2.7 f'{value:...
1,663,807
1,305
1,257,197,184
["python","list","for-loop","iterator"]
How do I iterate through two lists in parallel? I have two iterables, and I want to go over them in pairs: foo = [1, 2, 3] bar = [4, 5, 6] for (f, b) in iterate_together(foo, bar): print("f:", f, " | b:", b) That should result in: f: 1 | b: 4 f: 2 | b: 5 f: 3 | b: 6 One way to do it is to iterate over the indices: for...
Python 3 for f, b in zip(foo, bar): print(f, b) zip stops when the shorter of foo or bar stops. In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest. Python 2 I...
472,000
1,296
1,232,689,043
["python","oop","python-internals","slots"]
Usage of __slots__? What is the purpose of __slots__ in Python — especially with respect to when I would want to use it, and when not?
TLDR The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results: faster attribute access. space savings in memory. The space savings is from: Storing value references in slots instead of __dict__. Denying __dict__ and __we...
403,421
1,290
1,230,741,692
["python","list","sorting","reverse"]
How do I sort a list of objects based on an attribute of the objects? I have a list of Python objects that I want to sort by a specific attribute of each object: [Tag(name="toe", count=10), Tag(name="leg", count=2), ...] How do I sort the list by .count in descending order?
To sort the list in place: orig_list.sort(key=lambda x: x.count, reverse=True) To return a new list, use sorted: new_list = sorted(orig_list, key=lambda x: x.count, reverse=True) Explanation: key=lambda x: x.count sorts by count. reverse=True sorts in descending order. More on sorting by keys.
8,270,092
1,283
1,322,229,081
["python","string","trim","removing-whitespace"]
Remove all whitespace in a string I want to eliminate all the whitespace from a string, on both ends, and in between words. I have this Python code: def my_handle(self): sentence = ' hello apple ' sentence.strip() But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?
If you want to remove leading and ending whitespace, use str.strip(): >>> " hello apple ".strip() 'hello apple' If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace): >>> " hello apple ".replace(" ", "") 'helloappl...
129,507
1,276
1,222,286,435
["python","unit-testing","exception"]
How do you test that a Python function throws an exception? How does one write a unit test that fails only if a function doesn't throw an expected exception?
Use TestCase.assertRaises from the unittest module, for example: import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc)
3,462,143
1,270
1,281,555,490
["python","performance","list","set","set-difference"]
Get difference between two lists with Unique Entries I have two lists in Python: temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list: temp3 = ['Three', 'Four'] Are the...
To get elements which are in temp1 but not in temp2 (assuming uniqueness of the elements in each list): In [5]: list(set(temp1) - set(temp2)) Out[5]: ['Four', 'Three'] Beware that it is asymmetric : In [5]: set([1, 2]) - set([2, 3]) Out[5]: set([1]) where you might expect/want it to equal set([1, 3]). If you do want se...
12,453,580
1,260
1,347,859,945
["python","string","list","concatenation"]
How to concatenate (join) items in a list to a single string How do I concatenate a list of strings into a single string? For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"? For handling a few strings in separate variables, see How do I append one string to another in Python?. For th...
Use str.join: >>> words = ['this', 'is', 'a', 'sentence'] >>> '-'.join(words) 'this-is-a-sentence' >>> ' '.join(words) 'this is a sentence'
4,028,904
1,257
1,288,136,599
["python","cross-platform","home-directory"]
What is a cross-platform way to get the home directory? I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux: os.getenv("HOME") However, this does not work on Windows. What is the correct cross-platform way to do this ?
On Python 3.5+ you can use pathlib.Path.home(): from pathlib import Path home = Path.home() # example usage: with open(home / ".ssh" / "known_hosts") as f: lines = f.readlines() to get a pathlib.PosixPath object. Use str() to convert to a string if necessary. On older Python versions, you can use os.path.expanduser. fr...
1,185,524
1,254
1,248,641,678
["python","string","whitespace","trim","strip"]
How do I trim whitespace? Is there a Python function that will trim whitespace (spaces and tabs) from a string? So that given input " \t example string\t " becomes "example string".
For whitespace on both sides, use str.strip: s = " \t a string example\t " s = s.strip() For whitespace on the right side, use str.rstrip: s = s.rstrip() For whitespace on the left side, use str.lstrip: s = s.lstrip() You can provide an argument to strip arbitrary characters to any of these functions, like this: s = s....
2,793,324
1,216
1,273,304,908
["python","list"]
Is there a simple way to delete a list element by value? I want to remove a value from a list if it exists in the list (which it may not). a = [1, 2, 3, 4] b = a.index(6) del a[b] print(a) The above gives the error: ValueError: list.index(x): x not in list So I have to do this: a = [1, 2, 3, 4] try: b = a.index(6) del...
To remove the first occurrence of an element, use list.remove: >>> xs = ['a', 'b', 'c', 'd'] >>> xs.remove('b') >>> print(xs) ['a', 'c', 'd'] To remove all occurrences of an element, use a list comprehension: >>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b'] >>> xs = [x for x in xs if x != 'b'] >>> print(xs) ['a', 'c',...
20,638,006
1,215
1,387,293,891
["python","dictionary","pandas","dataframe"]
Convert list of dictionaries to a pandas DataFrame How can I convert a list of dictionaries into a DataFrame? I want to turn [{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': "february"}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month': 'june'}] into mon...
If ds is a list of dicts: df = pd.DataFrame(ds) Note: this does not work with nested data.
16,923,281
1,166
1,370,364,416
["python","pandas","dataframe","csv","file-io"]
Writing a pandas DataFrame to CSV file I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using: df.to_csv('out.csv') And getting the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) Is there any way to ge...
To delimit by a tab you can use the sep argument of to_csv: df.to_csv(file_name, sep='\t') To use a specific encoding (e.g. 'utf-8') use the encoding argument: df.to_csv(file_name, sep='\t', encoding='utf-8') In many cases you will want to remove the index and add a header: df.to_csv(file_name, sep='\t', encoding='utf-...
626,759
1,164
1,236,613,285
["python","list","tuples"]
What's the difference between lists and tuples? What are the differences between lists and tuples, and what are their respective advantages and disadvantages?
Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order. Using this distinction makes code more explicit an...
1,773,805
1,161
1,258,758,976
["python","yaml"]
How can I parse a YAML file in Python How can I parse a YAML file in Python?
The easiest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml: import yaml with open("example.yaml") as stream: try: print(yaml.safe_load(stream)) except yaml.YAMLError as exc: print(exc) yaml.load() also exists, but yaml.safe_load() should always be preferred ...
9,233,027
1,152
1,328,899,437
["python","python-3.x","unicode","file-io","decode"]
UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error: Traceback (most recent call last): File "SCRIPT L...
The file in question is not using the CP1252 encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1 and UTF-8. Since 0x90 doesn't actually mean anything in Latin-1, UTF-8 (where 0x90 is a continuation byte) is more likely. You specify the encoding when you open the fil...
20,180,543
1,142
1,385,324,701
["python"]
How do I check the versions of Python modules? I installed the Python modules construct and statlib using setuptools: sudo apt-get install python-setuptools sudo easy_install statlib sudo easy_install construct How do I check their versions from the command line?
Use pip instead of easy_install. With pip, list all installed packages and their versions via: pip freeze On most Linux systems, you can pipe this to grep (or findstr on Windows) to find the row for the particular package you're interested in. Linux: pip freeze | grep lxml lxml==2.3 Windows: pip freeze | findstr lxml l...
9,733,638
1,128
1,331,884,009
["python","json","python-requests","cherrypy"]
How can I POST JSON data with Python's Requests library? I need to POST JSON content from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET hard-coded JSON content from the server (the code is not shown), but when I try to POST JSON content to ...
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call: >>> import requests >>> r = requests.post('http://httpbin.org/post', json={"key": "value"}) >>> r.status_code 200 >>> r.json() {'args': {}, 'data': '{"key": "value"}', 'f...
32,490,629
1,072
1,441,840,825
["python","date","datetime","formatting","python-datetime"]
Getting today's date in YYYY-MM-DD in Python? Is there a nicer way than the following to return today's date in the YYYY-MM-DD format? str(datetime.datetime.today()).split()[0]
Use strftime: >>> from datetime import datetime >>> datetime.today().strftime('%Y-%m-%d') '2021-01-26' To also include a zero-padded Hour:Minute:Second at the end: >>> datetime.today().strftime('%Y-%m-%d %H:%M:%S') '2021-01-26 16:50:03' To get the UTC date and time: >>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') '...
308,999
1,058
1,227,279,220
["python","decorator","functools"]
What does functools.wraps do? In a comment on this answer to another question, someone said that they weren't sure what functools.wraps was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?
When you use a decorator, you're replacing one function with another. In other words, if you have a decorator def logged(func): def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging then when you say @logged def f(x): """does some math""" return x + x *...
2,186,525
1,051
1,265,134,790
["python","path","filesystems","glob","fnmatch"]
How to use glob() to find files recursively? I would like to list all files recursively in a directory. I currently have a directory structure like this: src/main.c src/dir/file1.c src/another-dir/file2.c src/another-dir/nested/files/file3.c I've tried to do the following: from glob import glob glob(os.path.join('src'...
There are a couple of ways: pathlib.Path().rglob() Use pathlib.Path().rglob() from the pathlib module, which was introduced in Python 3.5. from pathlib import Path for path in Path('src').rglob('*.c'): print(path.name) glob.glob() If you don't want to use pathlib, use glob.glob(): from glob import glob for filename in ...
1,937,622
1,050
1,261,355,161
["python","datetime","date"]
Convert date to datetime in Python Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given date? The opposite conversion is easy: datetime has a .date() method. Do I really have to manually call datetime(d.year, d.month, d.day)?
You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight. from datetime import date from datetime import datetime dt = datetime.combine(date.today(), datetime.min.time())
11,707,586
1,046
1,343,547,891
["python","pandas","printing","column-width"]
How do I expand the output display to see more columns of a Pandas DataFrame? Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas DataFrame. When the DataFrame is five columns (labels) wide, I get the descriptive sta...
(For Pandas versions before 0.23.4, see at bottom.) Use pandas.set_option(optname, val), or equivalently pd.options.<opt.hierarchical.name> = val. Like: import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) Pandas will try to autodetect...
3,964,681
1,041
1,287,450,553
["python","file-io"]
Find all files in a directory with extension .txt in Python How can I find all the files in a directory having the extension .txt in python?
You can use glob: import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file) or simply os.listdir: import os for file in os.listdir("/mydir"): if file.endswith(".txt"): print(os.path.join("/mydir", file)) or if you want to traverse directory, use os.walk: import os for root, dirs, files in os.walk("...
1,896,918
1,036
1,260,720,623
["python","unit-testing"]
Running unittest with typical test directory structure The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory: new_project/ antigravity/ antigravity.py test/ test_antigravity.py setup.py etc. My question is simply What's the usual way of...
The best solution in my opinion is to use the unittest command line interface which will add the directory to the sys.path so you don't have to (done in the TestLoader class). For example for a directory structure like this: new_project ├── antigravity.py └── test_antigravity.py You can just run: $ cd new_project $ pyt...
432,842
1,033
1,231,677,283
["python","logical-operators"]
How do you get the logical xor of two variables in Python? How do you get the logical xor of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or an empty string): str1 = raw_input("Enter string one:") str2 = ...
If you're already normalizing the inputs to booleans, then != is xor. bool(a) != bool(b)
323,972
1,030
1,227,797,753
["python","multithreading","python-multithreading","kill","terminate"]
Is there any way to kill a Thread? Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases: the thread is holding a critical resource that must be closed properly the thread has created several other threads that must be killed as well. The nice way of handling this, if you can afford it (if ...
477,486
1,028
1,232,878,843
["python","floating-point","range"]
How do I use a decimal step value for range()? How do I iterate between 0 and 1 by a step of 0.1? This says that the step argument cannot be zero: for i in range(0, 1, 0.1): print(i)
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result. Use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). li...
209,513
1,016
1,224,178,083
["python","string","hex"]
Convert hex string to integer in Python How do I convert a hex string to an integer? "0xffff" ⟶ 65535 "ffff" ⟶ 65535
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell: x = int("deadbeef", 16) With the 0x prefix, Python can distinguish hex and decimal automatically: >>> print(int("0xdeadbeef", 0)) 3735928559 >>> print(int("10", 0)) 10 (You must specify 0 as the base in order to invoke thi...
899,103
1,006
1,243,014,738
["python","file","list","file-io","newline"]
Writing a list to a file with Python, with newlines How do I write a list to a file? writelines() doesn't insert newline characters, so I need to do: f.writelines([f"{line}\n" for line in lines])
Use a loop: with open('your_file.txt', 'w') as f: for line in lines: f.write(f"{line}\n") For Python <3.6: with open('your_file.txt', 'w') as f: for line in lines: f.write("%s\n" % line) For Python 2, one may also use: with open('your_file.txt', 'w') as f: for line in lines: print >> f, line If you're keen on a single ...
1,854
1,003
1,217,906,598
["python","operating-system","cross-platform","platform-agnostic"]
How to identify which OS Python is running on What do I need to look at to see whether I'm on Windows or Unix, etc.?
>>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' The output of platform.system() is as follows: Linux: Linux Mac: Darwin Windows: Windows See: platform — Access to underlying platform’s identifying data
15,221,473
1,001
1,362,479,358
["python","upgrade","virtualenv","pip","package-managers"]
How do I update/upgrade pip itself from inside my virtual environment? I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version. What's the command for that? Do I need to use distr...
pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package: pip install --upgrade pip On Windows the recommended command is: py -m pip install --upgrade pip
1,247,486
996
1,249,688,611
["python","list-comprehension","map-function"]
List comprehension vs map Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more Pythonic than the other?
map may be microscopically faster in some cases (when you're not making a lambda for the purpose, but using the same function in map and a list comprehension). List comprehensions may be faster in other cases and most (not all) Pythonistas consider them more direct and clearer. An example of the tiny speed advantage of...
4,617,034
985
1,294,330,603
["python","file-io"]
How can I open multiple files using "with open" in Python? I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement: try: with open('a', 'w') as a and open('b', 'w') as b: do_something() except IOError as e: p...
As of Python 2.7 (or 3.1 respectively) you can write with open('a', 'w') as a, open('b', 'w') as b: do_something() (Historical note: In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked docume...
6,392,739
983
1,308,352,770
["python","syntax"]
What does the "at" (@) symbol do in Python? What does the @ symbol do in Python?
An @ symbol at the beginning of a line is used for class and function decorators: PEP 318: Decorators Python Decorators - Python Wiki The most common Python decorators are: @property @classmethod @staticmethod An @ in the middle of a line is probably matrix multiplication: @ as a binary operator.
682,504
979
1,238,000,421
["python","class","constructor"]
What is a clean "pythonic" way to implement multiple constructors? I can't find a definitive answer for this. As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve this problem? Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways o...
Actually None is much better for "magic" values: class Cheese: def __init__(self, num_holes=None): if num_holes is None: ... Now if you want complete freedom of adding more parameters: class Cheese: def __init__(self, *args, **kwargs): # args -- tuple of anonymous arguments # kwargs -- dictionary of named arguments sel...
9,542,738
972
1,330,740,214
["python","list","find"]
Find a value in a list I use the following to check if item is in my_list: if item in my_list: print("Desired item is in list") Is "if item in my_list:" the most "pythonic" way of finding an item in a list? EDIT FOR REOPENING: the question has been considered duplicate, but I'm not entirely convinced: here this questi...
As for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != ...
4,690,600
970
1,295,004,830
["python","exception","logging","except","python-logging"]
python exception message capturing import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging...
You have to define which type of exception you want to catch. So write except Exception as e: instead of except, e: for a general exception. Other possibility is to write your whole try/except code this way: try: with open(filepath,'rb') as f: con.storbinary('STOR '+ filepath, f) logger.info('File successfully uploaded...
10,377,998
966
1,335,754,681
["python","iterator","directory"]
How can I iterate over files in a given directory? I need to iterate through all .asm files inside a given directory and do some actions on them. How can this be done in a efficient way?
Python 3.6 version of the above answer, using os - assuming that you have the directory path as a str object in a variable called directory_in_str: import os directory = os.fsencode(directory_in_str) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.endswith(".asm") or filename.endswith(".py")...
End of preview.

StackOverflow Python QA Dataset

Status License

Description

This dataset contains high-quality Python questions and answers scraped from StackOverflow. It is designed for instruct-tuning Large Language Models (LLMs) or for question-answering tasks.

  • Source: StackOverflow
  • Selection Criteria:
    • Tag: python
    • Score: > 10
    • Must have an accepted answer
  • Content: Pairs of instructions (Question) and outputs (Accepted Answer).

Dataset Structure

The dataset consists of the following fields:

  • question_id: The unique identifier for the question on StackOverflow.
  • score: The vote score of the question.
  • tags: A list of tags associated with the question.
  • creation_date: The timestamp of when the question was asked.
  • instruction: The full question title and body, cleaned of HTML.
  • output: The full body of the accepted answer, cleaned of HTML.

Sample Entry

{
  "question_id": 12345,
  "score": 50,
  "tags": ["python", "list-comprehension"],
  "instruction": "How do I create a list... \n\n I have a loop that...",
  "output": "You can use a list comprehension:\n\n [x for x in iterable]"
}

Created by Atif



Downloads last month
218