Questions tagged [python-3.x]
DO NOT USE UNLESS YOUR QUESTION IS FOR PYTHON 3 ONLY. Always use alongside the standard [python] tag.
341,735
questions
3691
votes
24
answers
4.8m
views
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]
>>> ...
2973
votes
12
answers
357k
views
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.
This being the case, I would have expected ...
1803
votes
16
answers
1.1m
views
Proper way to declare custom exceptions in modern Python?
What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I ...
1621
votes
7
answers
798k
views
What is the Python 3 equivalent of "python -m SimpleHTTPServer"
What is the Python 3 equivalent of python -m SimpleHTTPServer?
1619
votes
33
answers
1.6m
views
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 ...
1440
votes
5
answers
2.6m
views
Best way to convert string to bytes in Python 3?
TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes:
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
Which method is ...
1268
votes
13
answers
1.9m
views
How do I return dictionary keys as a list in Python?
With Python 2.7, I can get dictionary keys, values, or items as a list:
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
With Python >= 3.3, I get:
>>> newdict....
1216
votes
15
answers
846k
views
Should I put #! (shebang) in Python scripts, and what form should it take?
Should I put the shebang in my Python scripts? In what form?
#!/usr/bin/env python
or
#!/usr/local/bin/python
Are these equally portable? Which form is used most?
Note: the tornado project uses ...
1196
votes
9
answers
292k
views
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:
...
1141
votes
43
answers
1.3m
views
How can I represent an 'Enum' in Python?
I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
1057
votes
10
answers
600k
views
What is __pycache__?
From what I understand, a cache is an encrypted file of similar files.
What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? ...
1011
votes
15
answers
1.6m
views
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 ...
936
votes
11
answers
744k
views
What does -> mean in Python function definitions?
I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
The optional 'arrow' block was absent in Python 2 ...
896
votes
8
answers
595k
views
Fixed digits after decimal with f-strings
Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)
For example, let's say ...
883
votes
11
answers
2.2m
views
"TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3
I've very recently migrated to Python 3.5.
This code was working properly in Python 2.7:
with open(fname, 'rb') as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
tmp = line....
874
votes
23
answers
1.1m
views
Using Python 3 in virtualenv
Using virtualenv, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used brew install python3 to install it on my Mac. Now, how do I create a ...
777
votes
14
answers
510k
views
What is the best way to remove accents (normalize) in a Python unicode string?
I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the web an elegant way to do this (in Java):
convert the Unicode string to its long normalized ...
737
votes
6
answers
283k
views
Are dictionaries ordered in Python 3.6+?
Dictionaries are insertion ordered as of Python 3.6. It is described as a CPython implementation detail rather than a language feature. The documentation states:
dict() now uses a “compact” ...
679
votes
23
answers
1.9m
views
How to install pip with Python 3?
I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.
How can I install pip with Python 3?
655
votes
4
answers
375k
views
How to specify multiple return types using type-hints
I have a function in python that can either return a bool or a list. Is there a way to specify the return types using type hints?
For example, is this the correct way to do it?
def foo(id) -> list ...
644
votes
9
answers
1.1m
views
How do I use raw_input in Python 3?
In Python 2:
raw_input()
In Python 3, I get an error:
NameError: name 'raw_input' is not defined
637
votes
9
answers
930k
views
How to use StringIO in Python3?
I am using Python 3.2.1 and I can't import the StringIO module. I use
io.StringIO and it works, but I can't use it with numpy's genfromtxt like this:
x="1 3\n 4.5 8"
numpy.genfromtxt(io....
637
votes
11
answers
609k
views
Getting a map() to return a list in Python 3.x
I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
A: Python 2.6:
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
However, in Python 3....
615
votes
7
answers
612k
views
Error: " 'dict' object has no attribute 'iteritems' "
I'm trying to use NetworkX to read a Shapefile and use the function write_shp() to generate the Shapefiles that will contain the nodes and edges, but when I try to run the code it gives me the ...
590
votes
4
answers
486k
views
Deep copy of a dict in python
I would like to make a deep copy of a dict in python. Unfortunately the .deepcopy() method doesn't exist for the dict. How do I do that?
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>&...
570
votes
10
answers
1.0m
views
Import error: No module name urllib2
Here's my code:
import urllib2.request
response = urllib2.urlopen("http://www.google.com")
html = response.read()
print(html)
Any help?
534
votes
4
answers
260k
views
How can I specify the function type in my type hints?
How can I specify the type hint of a variable as a function type? There is no typing.Function, and I could not find anything in the relevant PEP, PEP 483.
523
votes
18
answers
1.1m
views
List attributes of an object [duplicate]
Is there a way to grab a list of attributes that exist on instances of a class?
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
...
486
votes
19
answers
771k
views
How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?
I would like to include image in a jupyter notebook.
If I did the following, it works :
from IPython.display import Image
Image("img/picture.png")
But I would like to include the images in a ...
482
votes
21
answers
850k
views
How to set Python's default version to 3.x on OS X? [duplicate]
I'm running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default.
Currently:
$ python
version 2.7.5
$ python3.3
version 3.3
How ...
479
votes
5
answers
93k
views
What does a bare asterisk do in a parameter list? What are "keyword-only" parameters?
What does a bare asterisk in the parameters of a function do?
When I looked at the pickle module, I see this:
pickle.dump(obj, file, protocol=None, *, fix_imports=True)
I know about a single and ...
459
votes
11
answers
1.0m
views
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
When I try to use a print statement in Python, it gives me this error:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
...
457
votes
10
answers
555k
views
How to correct TypeError: Unicode-objects must be encoded before hashing?
I have this error:
Traceback (most recent call last):
File "python_md5_cracker.py", line 27, in <module>
m.update(line)
TypeError: Unicode-objects must be encoded before hashing
when I try ...
454
votes
14
answers
338k
views
Extract a subset of key-value pairs from dictionary?
I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to subset such dictionary?
The ...
449
votes
9
answers
430k
views
Download file from web in Python 3
I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I'm using Python 3.2.1
I've ...
449
votes
12
answers
391k
views
What is an alternative to execfile in Python 3?
It seems they canceled in Python 3 all the easy ways to quickly load a script by removing execfile().
Is there an obvious alternative I'm missing?
440
votes
18
answers
445k
views
How to install python3 version of package via pip on Ubuntu?
I have both python2.7 and python3.2 installed in Ubuntu 12.04.
The symbolic link python links to python2.7.
When I type:
sudo pip install package-name
It will default install python2 version of ...
430
votes
12
answers
796k
views
Which is the preferred way to concatenate a string in Python? [duplicate]
Since Python's string can't be changed, I was wondering how to concatenate a string more efficiently?
I can write like it:
s += stringfromelsewhere
or like this:
s = []
s.append(somestring)
# ...
425
votes
3
answers
616k
views
How to convert 'binary string' to normal string in Python3? [duplicate]
For example, I have a string like this(return value of subprocess.check_output):
>>> b'a string'
b'a string'
Whatever I did to it, it is always printed with the annoying b' before the ...
422
votes
10
answers
1.4m
views
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 [duplicate]
I am using Python 3.1 on a Windows 7 machine. Russian is the default system language, and utf-8 is the default encoding.
Looking at the answer to a previous question, I have attempting using the "...
413
votes
19
answers
978k
views
Relative imports - ModuleNotFoundError: No module named x
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:
test.py
config.py
config.py has a few functions defined in it as ...
412
votes
3
answers
169k
views
Python "raise from" usage
What's the difference between raise and raise from in Python?
try:
raise ValueError
except Exception as e:
raise IndexError
which yields
Traceback (most recent call last):
File "tmp.py", ...
399
votes
5
answers
188k
views
Is __init__.py not required for packages in Python 3.3+
I am using Python 3.5.1. I read the document and the package section here: https://docs.python.org/3/tutorial/modules.html#packages
Now, I have the following structure:
/home/wujek/Playground/a/b/...
398
votes
6
answers
358k
views
What's the difference between `raw_input()` and `input()` in Python 3? [duplicate]
What is the difference between raw_input() and input() in Python 3?
395
votes
21
answers
646k
views
Python 3 ImportError: No module named 'ConfigParser'
I am trying to pip install the MySQL-python package, but I get an ImportError.
Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python
Downloading/...
395
votes
2
answers
147k
views
How to specify "nullable" return type with type hints
Suppose I have a function:
def get_some_date(some_argument: int=None) -> %datetime_or_None%:
if some_argument is not None and some_argument == 1:
return datetime.utcnow()
else:
...
392
votes
6
answers
537k
views
NameError: global name 'xrange' is not defined in Python 3
I am getting an error when running a python program:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 110, in <module>
...
384
votes
13
answers
1.2m
views
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
I have some code like:
score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)
I want it to print out Total score for Alice is 100, but instead I get Total score for %s is %s Alice ...
380
votes
9
answers
562k
views
What is the purpose of "pip install --user ..."?
From pip install --help:
--user Install to the Python user install directory for your platform.
Typically ~/.local/, or %APPDATA%\Python on Windows.
(See the Python documentation for ...
379
votes
9
answers
578k
views
What's the correct way to convert bytes to a hex string in Python 3?
What's the correct way to convert bytes to a hex string in Python 3?
I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without ...