Questions tagged [python-3.x]

DO NOT USE UNLESS YOUR QUESTION IS FOR PYTHON 3 ONLY. Always use alongside the standard [python] tag.

Filter by
Sorted by
Tagged with
3691 votes
24 answers

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] >>> ...
Tomas Sedovic's user avatar
2973 votes
12 answers

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 ...
Rick's user avatar
  • 43.1k
1803 votes
16 answers

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 ...
Nelson's user avatar
  • 27.6k
1621 votes
7 answers

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

What is the Python 3 equivalent of python -m SimpleHTTPServer?
ryanbraganza's user avatar
  • 16.9k
1619 votes
33 answers

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 ...
John Smith Optional's user avatar
1440 votes
5 answers

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 ...
Mark Ransom's user avatar
1268 votes
13 answers

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....
user avatar
1216 votes
15 answers

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 ...
treecoder's user avatar
  • 43.2k
1196 votes
9 answers

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: ...
Michael van Gerwen's user avatar
1141 votes
43 answers

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

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? ...
user2063042's user avatar
  • 10.6k
1011 votes
15 answers

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 ...
Eden Crow's user avatar
  • 14.8k
936 votes
11 answers

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 ...
Krotton's user avatar
  • 9,581
896 votes
8 answers

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 ...
GafferMan2112's user avatar
883 votes
11 answers

"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....
masroore's user avatar
  • 9,678
874 votes
23 answers

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 ...
Prometheus's user avatar
  • 32.5k
777 votes
14 answers

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 ...
MiniQuark's user avatar
  • 46.7k
737 votes
6 answers

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” ...
Chris_Rands's user avatar
  • 39.1k
679 votes
23 answers

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?
deamon's user avatar
  • 89.4k
655 votes
4 answers

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 ...
Yahya Uddin's user avatar
  • 27.1k
644 votes
9 answers

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
Lonnie Price's user avatar
  • 10.3k
637 votes
9 answers

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....
Babak Abdolahi's user avatar
637 votes
11 answers

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....
mozami's user avatar
  • 7,391
615 votes
7 answers

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 ...
friveraa's user avatar
  • 6,265
590 votes
4 answers

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]} >&...
Olivier Grégoire's user avatar
570 votes
10 answers

Import error: No module name urllib2

Here's my code: import urllib2.request response = urllib2.urlopen("") html = print(html) Any help?
user avatar
534 votes
4 answers

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.
Jon's user avatar
  • 11.5k
523 votes
18 answers

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) ...
MadSc13ntist's user avatar
  • 19.9k
486 votes
19 answers

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 ...
Ger's user avatar
  • 9,096
482 votes
21 answers

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 ...
Marcus's user avatar
  • 9,052
479 votes
5 answers

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 ...
Eric's user avatar
  • 5,706
459 votes
11 answers

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!" ^ ...
ncoghlan's user avatar
  • 40.3k
457 votes
10 answers

How to correct TypeError: Unicode-objects must be encoded before hashing?

I have this error: Traceback (most recent call last): File "", line 27, in <module> m.update(line) TypeError: Unicode-objects must be encoded before hashing when I try ...
JohnnyFromBF's user avatar
  • 9,873
454 votes
14 answers

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 ...
Jayesh's user avatar
  • 51.8k
449 votes
9 answers

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 ...
Bo Milanovich's user avatar
449 votes
12 answers

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?
R S's user avatar
  • 11.4k
440 votes
18 answers

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 ...
kev's user avatar
  • 155k
430 votes
12 answers

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) # ...
Max's user avatar
  • 7,957
425 votes
3 answers

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 ...
Hanfei Sun's user avatar
  • 45.4k
422 votes
10 answers

"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 "...
Eric's user avatar
  • 4,293
413 votes
19 answers

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: has a few functions defined in it as ...
blitzmann's user avatar
  • 7,349
412 votes
3 answers

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 "", ...
darkfeline's user avatar
  • 9,464
399 votes
5 answers

Is not required for packages in Python 3.3+

I am using Python 3.5.1. I read the document and the package section here: Now, I have the following structure: /home/wujek/Playground/a/b/...
wujek's user avatar
  • 10.2k
398 votes
6 answers

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?
pkumar's user avatar
  • 4,743
395 votes
21 answers

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/...
if __name__ is None's user avatar
395 votes
2 answers

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: ...
exfizik's user avatar
  • 5,391
392 votes
6 answers

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\", line 110, in <module> ...
Pip's user avatar
  • 4,397
384 votes
13 answers

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 ...
user1985351's user avatar
  • 4,599
380 votes
9 answers

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 ...
Rob Truxal's user avatar
  • 5,906
379 votes
9 answers

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 ...
Matt Joiner's user avatar

2 3 4 5