text
stringlengths 185
26.5k
|
---|
<s>[INST] How to calculate the angle between a line and the horizontal axis? In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis?
I think an image describes best what I want:
Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate this angle? The origin is in the topleft and only the positive quadrant is used.
[/INST] First find the difference between the start point and the end point.
deltaY = P2_y - P1_y
deltaX = P2_x - P1_x
Then calculate the angle.
angleInDegrees = arctan(deltaY / deltaX) * 180 / PI
If your language includes an atan2 function it becomes the following instead:
angleInDegrees = atan2(deltaY, deltaX) * 180 / PI
An implementation in Python using radians (provided by Eric Leschinski, who edited my answer):
from math import *
def angle_trunc(a):
while a < 0.0:
a += pi * 2
return a
def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
deltaY = y_landmark - y_orig
deltaX = x_landmark - x_orig
return angle_trunc(atan2(deltaY, deltaX))
angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
All tests pass. See https://en.wikipedia.org/wiki/Unit_circle
</s> |
<s>[INST] Convert list to tuple in Python I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
l = [4,5,6]
tuple(l)
But if I do that I get this error message:
TypeError: 'tuple' object is not callable
How can I fix this problem?
[/INST] It should work fine. Don't use tuple, list or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
</s> |
<s>[INST] No module named MySQLdb I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
[/INST] You need to use one of the following commands. Which one depends on what OS and software you have and use.
easy_install mysql-python (mix os)
pip install mysql-python (mix os)
apt-get install python-mysqldb (Linux Ubuntu, ...)
cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
yum install MySQL-python (Linux Fedora, CentOS ...)
For Windows, see this answer: Install mysql-python (Windows)
</s> |
<s>[INST] Python "extend" for a dictionary Which is the best way to extend a dictionary with another one? For instance:
>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}
I'm looking for any operation to obtain this avoiding for loop:
{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }
I wish to do something like:
a.extend(b) # This does not work
[/INST] a.update(b)
Python Standard Library Documentation
</s> |
<s>[INST] How to convert strings into integers in Python? I have a tuple of tuples from a MySQL query like this:
T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:
T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
I tried to achieve it with eval but didn't get any decent result yet.
[/INST] int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:
print int("1") + 1
The above prints 2.
If you know the structure of your list (that it simply contains lists, only one level), you could do this:
T2 = [map(int, x) for x in T1]
</s> |
<s>[INST] How do I sort a list of strings in Python? What is the best way of creating an alphabetically sorted list in Python?
[/INST] Basic answer:
mylist = ["b", "C", "A"]
mylist.sort()
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:
for x in sorted(mylist):
print x
However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):
sorted(mylist, key=cmp_to_key(locale.strcoll))
And finally, if you need, you can specify a custom locale for sorting:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
</s> |
<s>[INST] Chain-calling parent constructors in python Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.
class A(object):
def __init__(self):
print "Constructor A was called"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Constructor B was called"
class C(B):
def __init__(self):
super(C,self).__init__()
print "Constructor C was called"
c = C()
This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.
Now, I've tried using self.__class__ as a first argument to super(), but, obviously it doesn't work - if you put it in the constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor again (this ends in an infinite recursion).
There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.
[/INST] The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".
</s> |
<s>[INST] Python: Find in list I have come across this delightful:
item = someSortOfSelection()
if item in myList:
doMySpecialFunction(item)
but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string).
is it the most 'pythonic' way of finding an item in a list: if x in l:?
[/INST] As for your first question: that code is perfectly fine and should work if item equals one of the elements inside myList. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:
3 in [1, 2, 3] # => True
Filtering a collection
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.
Finding the first occurrence
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
Finding the location of an item
For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index always returns the lowest index:
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate() instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
</s> |
<s>[INST] Difference between __getattr__ vs __getattribute__ I am trying to understand when to use __getattr__ or __getattribute__. The documentation mentions __getattribute__ applies to new-style classes. What are new-style classes?
[/INST] A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.
__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.
New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.
You almost certainly want __getattr__.
</s> |
<s>[INST] C-like structures in Python Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
[/INST] Use a named tuple, which was added to the collections module in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's named tuple recipe if you need to support Python 2.4.
It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")
The newly created type can be used like this:
m = MyStruct("foo", "bar", "baz")
Or you can use named arguments:
m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz")
</s> |
<s>[INST] Separation of business logic and data access in django I am writing a project in Django and I see that 80% of the code is in the file models.py. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
I find it ugly that my model level (which was supposed to be
responsible only for the work with data from a database) is also
sending email, walking on api to other services, etc.
Also, I find it unacceptable to place business logic in the view, because
this way it becomes difficult to control. For example, in my
application there are at least three ways to create new
instances of User, but technically it should create them uniformally.
I do not always notice when the methods and
properties of my models become non-deterministic and when they develop
side effects.
Here is a simple example. At first, the User model was like this:
class User(db.Models):
def get_present_name(self):
return self.name or 'Anonymous'
def activate(self):
self.status = 'activated'
self.save()
Over time, it turned into this:
class User(db.Models):
def get_present_name(self):
# property became non-deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
def activate(self):
# method now has a side effect (send message to user)
self.status = 'activated'
self.save()
send_mail('Your account is activated!', 'â¦', [self.email])
What I want is to separate entities in my code:
Entities of my database, database level: What contains my application?
Entities of my application, business logic level: What can make my application?
What are the good practices to implement such an approach that can be applied in Django?
[/INST] It seems like you are asking about the difference between the data model and the domain model â the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data.
Furthermore, I've interpreted the 3rd part of your question as: how to notice failure to keep these models separate.
These are two very different concepts and it's always hard to keep them separate. However, there are some common patterns and tools that can be used for this purpose.
About the Domain Model
The first thing you need to recognize is that your domain model is not really about data; it is about actions and questions such as "activate this user", "deactivate this user", "which users are currently activated?", and "what is this user's name?". In classical terms: it's about queries and commands.
Thinking in Commands
Let's start by looking at the commands in your example: "activate this user" and "deactivate this user". The nice thing about commands is that they can easily be expressed by small given-when-then scenario's:
given an inactive user
when the admin activates this user
then the user becomes active
and a confirmation e-mail is sent to the user
and an entry is added to the system log
(etc. etc.)
Such scenario's are useful to see how different parts of your infrastructure can be affected by a single command â in this case your database (some kind of 'active' flag), your mail server, your system log, etc.
Such scenario's also really help you in setting up a Test Driven Development environment.
And finally, thinking in commands really helps you create a task-oriented application. Your users will appreciate this :-)
Expressing Commands
Django provides two easy ways of expressing commands; they are both valid options and it is not unusual to mix the two approaches.
The service layer
The service module has already been described by @Hedde. Here you define a separate module and each command is represented as a function.
services.py
def activate_user(user_id):
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
Using forms
The other way is to use a Django Form for each command. I prefer this approach, because it combines multiple closely related aspects:
execution of the command (what does it do?)
validation of the command parameters (can it do this?)
presentation of the command (how can I do this?)
forms.py
class ActivateUserForm(forms.Form):
user_id = IntegerField(widget = UsernameSelectWidget, verbose_name="Select a user to activate")
# the username select widget is not a standard Django widget, I just made it up
def clean_user_id(self):
user_id = self.cleaned_data['user_id']
if User.objects.get(pk=user_id).active:
raise ValidationError("This user cannot be activated")
# you can also check authorizations etc.
return user_id
def execute(self):
"""
This is not a standard method in the forms API; it is intended to replace the
'extract-data-from-form-in-view-and-do-stuff' pattern by a more testable pattern.
"""
user_id = self.cleaned_data['user_id']
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
Thinking in Queries
You example did not contain any queries, so I took the liberty of making up a few useful queries. I prefer to use the term "question", but queries is the classical terminology. Interesting queries are: "What is the name of this user?", "Can this user log in?", "Show me a list of deactivated users", and "What is the geographical distribution of deactivated users?"
Before embarking on answering these queries, you should always ask yourself two questions: is this a presentational query just for my templates, and/or a business logic query tied to executing my commands, and/or a reporting query.
Presentational queries are merely made to improve the user interface. The answers to business logic queries directly affect the execution of your commands. Reporting queries are merely for analytical purposes and have looser time constraints. These categories are not mutually exclusive.
The other question is: "do I have complete control over the answers?" For example, when querying the user's name (in this context) we do not have any control over the outcome, because we rely on an external API.
Making Queries
The most basic query in Django is the use of the Manager object:
User.objects.filter(active=True)
Of course, this only works if the data is actually represented in your data model. This is not always the case. In those cases, you can consider the options below.
Custom tags and filters
The first alternative is useful for queries that are merely presentational: custom tags and template filters.
template.html
<h1>Welcome, {{ user|friendly_name }}</h1>
template_tags.py
@register.filter
def friendly_name(user):
return remote_api.get_cached_name(user.id)
Query methods
If your query is not merely presentational, you could add queries to your services.py (if you are using that), or introduce a queries.py module:
queries.py
def inactive_users():
return User.objects.filter(active=False)
def users_called_publysher():
for user in User.objects.all():
if remote_api.get_cached_name(user.id) == "publysher":
yield user
Proxy models
Proxy models are very useful in the context of business logic and reporting. You basically define an enhanced subset of your model.
models.py
class InactiveUserManager(models.Manager):
def get_query_set(self):
query_set = super(InactiveUserManager, self).get_query_set()
return query_set.filter(active=False)
class InactiveUser(User):
"""
>>> for user in InactiveUser.objects.all():
⦠assert user.active is False
"""
objects = InactiveUserManager()
class Meta:
proxy = True
Query models
For queries that are inherently complex, but are executed quite often, there is the possibility of query models. A query model is a form of denormalization where relevant data for a single query is stored in a separate model. The trick of course is to keep the denormalized model in sync with the primary model. Query models can only be used if changes are entirely under your control.
models.py
class InactiveUserDistribution(models.Model):
country = CharField(max_length=200)
inactive_user_count = IntegerField(default=0)
The first option is to update these models in your commands. This is very useful if these models are only changed by one or two commands.
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
A better option would be to use custom signals. These signals are of course emitted by your commands. Signals have the advantage that you can keep multiple query models in sync with your original model. Furthermore, signal processing can be offloaded to background tasks, using Celery or similar frameworks.
signals.py
user_activated = Signal(providing_args = ['user'])
user_deactivated = Signal(providing_args = ['user'])
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
user_activated.send_robust(sender=self, user=user)
models.py
class InactiveUserDistribution(models.Model):
# see above
@receiver(user_activated)
def on_user_activated(sender, **kwargs):
user = kwargs['user']
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
Keeping it clean
When using this approach, it becomes ridiculously easy to determine if your code stays clean. Just follow these guidelines:
Does my model contain methods that do more than managing database state? You should extract a command.
Does my model contain properties that do not map to database fields? You should extract a query.
Does my model reference infrastructure that is not my database (such as mail)? You should extract a command.
The same goes for views (because views often suffer from the same problem).
Does my view actively manage database models? You should extract a command.
Some References
Django documentation: proxy models
Django documentation: signals
Architecture: Domain Driven Design
</s> |
<s>[INST] What is a monkey patch? I am trying to understand, what is a monkey patch?
Is that something like methods/operators overloading or delegating?
Does it have anything common with these things?
[/INST] No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.
For instance, consider a class that has a method get_data. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data method with a stub that returns some fixed data.
Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.
</s> |
<s>[INST] Tabs versus spaces in Python programming I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.
How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?
Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
[/INST] Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'.
1 tab == 1 indent level, full stop
The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code :p
(personally I use 4 char width tab... but some would prefer 3 or 8 space, or even use variable width fonts !!)
</s> |
<s>[INST] What do the python file extensions, .pyc .pyd .pyo stand for? What do these python file extensions mean?
.pyc
.pyd
.pyo
What are the differences between them and how are they generated from a *.py file?
[/INST]
.py: This is normally the input source code that you've written.
.pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
.pyo: This is a *.pyc file that was created while optimizations (-O) was on.
.pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll
Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in â.pyoâ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact â.pyoâ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
A program doesn't run any faster when it is read from a â.pycâ or â.pyoâ file than when it is read from a â.pyâ file; the only thing that's faster about â.pycâ or â.pyoâ files is the speed with which they are loaded.
When a script is run by giving its name on the command line, the bytecode for the script is never written to a â.pycâ or â.pyoâ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a â.pycâ or â.pyoâ file directly on the command line.
</s> |
<s>[INST] Can I use Python as a Bash replacement? I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.
I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?
[/INST] Any shell has several sets of features.
The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.
And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.
The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.
The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.
Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.
The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.
Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".
The best thing is that you can do this in steps.
Replace AWK and PERL with Python. Leave everything else alone.
Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.
</s> |
<s>[INST] How do I execute a program from python? os.system fails due to spaces in path I have a python script that needs to execute an external program, but for some reason fails.
If I have the following script:
import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
Then it fails with the following error:
'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
If I escape the program with quotes:
import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
Then it works. However, if I add a parameter, it stops working again:
import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.
Also note, moving the program to a non-spaced path is not an option either.
Edit This does not work either:
import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
Note the swapped single/double quotes.
with or without a parameter to notepad here, it fails with the error message
The filename, directory name, or volume label syntax is incorrect.
[/INST] subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
</s> |
<s>[INST] Adding new column to existing DataFrame in Python pandas I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
I would like to add a new column, 'e', to the existing data frame and do not change anything in the data frame. (The series always got the same length as a dataframe.) I tried different versions of join, append, merge, but I did not get it as what I want, only errors at the most.
The series and data frame is already given and the above code is only to illustrate it with an example.
I am sure there is some easy way to that, but I can't figure it out.
[/INST] Use the original df1 indexes to create the series:
df1['e'] = Series(np.random.randn(sLength), index=df1.index)
Edit 2015
Some reported to get the SettingWithCopyWarning with this code.
However, the code still runs perfect with the current pandas version 0.16.1.
>>> sLength = len(df1['a'])
>>> df1
a b c d
6 -0.269221 -0.026476 0.997517 1.294385
8 0.917438 0.847941 0.034235 -0.448948
>>> df1['e'] = p.Series(np.random.randn(sLength), index=df1.index)
>>> df1
a b c d e
6 -0.269221 -0.026476 0.997517 1.294385 1.757167
8 0.917438 0.847941 0.034235 -0.448948 2.228131
>>> p.version.short_version
'0.16.1'
The SettingWithCopyWarning aims to inform of a possibly invalid assignment on a copy of the Dataframe. It doesn't necessarily say you did it wrong (it can trigger false positives) but from 0.13.0 it let you know there are more adequate methods for the same purpose. Then, if you get the warning, just follow its advise: Try using .loc[row_index,col_indexer] = value instead
>>> df1.loc[:,'f'] = p.Series(np.random.randn(sLength), index=df1.index)
>>> df1
a b c d e f
6 -0.269221 -0.026476 0.997517 1.294385 1.757167 -0.050927
8 0.917438 0.847941 0.034235 -0.448948 2.228131 0.006109
>>>
In fact, this is currently the more efficient method as described in pandas docs
</s> |
<s>[INST] Why do some functions have underscores "__" before and after the function name? This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention?
Also, could someone name and explain which functions tend to have the underscores, and why (__init__, for instance)?
[/INST] From the Python PEP 8 -- Style Guide for Python Code (http://www.python.org/dev/peps/pep-0008/):
the following special forms using leading or trailing underscores are
recognized (these can generally be combined with any case convention):
_single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an
underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__,
__import__ or __file__. Never invent such names; only use them as documented.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
</s> |
<s>[INST] How do I fix 'ImportError: cannot import name IncompleteRead'? When I try to install anything with pip or pip3, I get:
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2476, in load_entry_point
return ep.load()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2190, in load
['__name__'])
File "/usr/lib/python3/dist-packages/pip/__init__.py", line 61, in <module>
from pip.vcs import git, mercurial, subversion, bazaar # noqa
File "/usr/lib/python3/dist-packages/pip/vcs/mercurial.py", line 9, in <module>
from pip.download import path_to_url
File "/usr/lib/python3/dist-packages/pip/download.py", line 25, in <module>
from requests.compat import IncompleteRead
ImportError: cannot import name 'IncompleteRead'
I have a Ubuntu 14.10 system.
How can I fix this problem?
[/INST] While this previous answer might be the reason, this snipped worked for me as a solution (in Ubuntu 14.04):
First remove the package from the package manager:
# apt-get remove python-pip
And then install the latest version by side:
# easy_install pip
(thanks to @Aufziehvogel, @JunchaoGu)
</s> |
<s>[INST] How can I parse a YAML file in Python How can I parse a YAML file in Python?
[/INST] The easiest and pureist method without relying on C headers is PyYaml:
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as exc:
print(exc)
Err.. that's it... how many lines of code would that take me in Java... any ideas? : ) more info here:
http://pyyaml.org/wiki/PyYAMLDocumentation
</s> |
<s>[INST] How to avoid .pyc files? Can I run the python interpreter without generating the compiled .pyc files?
[/INST] From "Whatâs New in Python 2.6 - Interpreter Changes":
Python can now be prevented from
writing .pyc or .pyo files by
supplying the -B switch to the Python
interpreter, or by setting the
PYTHONDONTWRITEBYTECODE environment
variable before running the
interpreter. This setting is available
to Python programs as the
sys.dont_write_bytecode variable, and
Python code can change the value to
modify the interpreterâs behaviour.
Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc files by introducing a special __pycache__ subfolder, see What's New in Python 3.2 - PYC Repository Directories.
</s> |
<s>[INST] What does the at (@) symbol do in Python I'm looking at some Python code which used the @ symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the @ symbol is included.
[/INST] Preamble
I admit it took more than a few moments to fully grasp this concept for me, so I'll share what I've learned to save others the trouble.
The name decorator - the thing we define using the @ syntax before a function definition - was probably the main culprit here.
Example
class Pizza(object):
def __init__(self):
self.toppings = []
def __call__(self, topping):
# when using '@instance_of_pizza' before a function def
# the function gets passed onto 'topping'
self.toppings.append(topping())
def __repr__(self):
return str(self.toppings)
pizza = Pizza()
@pizza
def cheese():
return 'cheese'
@pizza
def sauce():
return 'sauce'
print pizza
# ['cheese', 'sauce']
What this shows is that the function/method/class you're defining after a decorator is just basically passed on as an argument to the function/method immediatelly after the @ sign.
First sighting
The microframework Flask introduces decorators from the very beginning in the following format:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
This in turn translates to:
rule = "/"
view_func = hello
# they go as arguments here in 'flask/app.py'
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
pass
Realizing this finally allowed me to feel at peace with flask.
</s> |
<s>[INST] Typical Angular.js workflow and project structure (with Python Flask) I am pretty new to this whole MV* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in Angular.js and then hooking up the back-end to it?
Or the other way around by first building the back-end in Django, Flask, Rails and then attaching an Angular.js app to it? Is there a "right" way of doing it, or is it just a personal preference in the end?
I am also not sure whether to structure my project according to the Flask or Angular.js? community practices.
For example, Flask's minitwit app is structured like so:
minitwit
|-- minitwit.py
|-- static
|-- css, js, images, etc...
`-- templates
|-- html files and base layout
Angular.js tutorial app is structured like this:
angular-phonecat
|-- app
`-- css
`-- img
`-- js
`-- lib
`-- partials
`-- index.html
|-- scripts
`-- node.js server and test server files
I could picture a Flask app by itself, and it's fairly easy to see Angular.js app like ToDo List by itself but when it comes to using both of these technologies I don't understand how they work together. It almost seems like I don't need a server-side web-framework when you already have Angular.js, a simple Python web server will suffice. In the Angular to-do app for example they use MongoLab to talk to the database using Restful API. There was no need having a web framework on the back-end.
Maybe I am just awfully confused, and Angular.js is nothing more than a fancy jQuery library so I should use just like I would use jQuery in my Flask projects (assuming I change Angular's template syntax to something that doesn't conflict with Jinja2). I hope my questions make some sense. I mainly work on the back-end and this client-side framework is an unknown territory for me.
[/INST] I would start out by organizing the Flask app in the standard structure as follows:
app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- templates
And as btford mentioned, if you are doing an Angular app, you'll want to focus on using Angular client-side templates and stay away from server-side templates. Using render_template('index.html') will cause Flask to interpret your angular templates as jinja templates, so they won't render correctly. Instead, you'll want to do the following:
@app.route("/")
def index():
return send_file('templates/index.html')
Note that using send_file() means that the files will be cached, so you might want to use make_response() instead, at least for development:
return make_response(open('templates/index.html').read())
Afterwards, build out the AngularJS part of your app, modifying the app structure so that it looks like this:
app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- app.js, controllers.js, etc.
|-- lib
|-- angular
|-- angular.js, etc.
|-- partials
|-- templates
|-- index.html
Make sure your index.html includes AngularJS, as well as any other files:
<script src="static/lib/angular/angular.js"></script>
At this point, you haven't yet constructed your RESTful API, so you can have your js controllers return predefined sample data (only a temporary setup). When you're ready, implement the RESTful API and hook it up to your angular app with angular-resource.js.
EDIT: I put together an app template that, though a little more complex that what I've described above, illustrates how one could build an app with AngularJS + Flask, complete with communication between AngularJS and a simple Flask API. Here it is if you want to check it out: https://github.com/rxl/angular-flask
</s> |
<s>[INST] Should Python import statements always be at the top of a module? PEP 08 states:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?
Isn't this:
class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
more efficient than this?
from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
[/INST] Module importing is quite fast, but not instant. This means that:
Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once.
Putting the imports within a function will cause calls to that function to take longer.
So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you did profile to see where best to improve performance, right??)
The best reasons I've seen to perform lazy imports are:
Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.
In the __init__.py of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use bzrlib's lazy-loading framework.
</s> |
<s>[INST] Pythonic way to avoid "if x: return x" statements I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.
def check_all_conditions():
x = check_size()
if x:
return x
x = check_color()
if x:
return x
x = check_tone()
if x:
return x
x = check_flavor()
if x:
return x
return None
This seems like a lot of baggage code. Instead of each 2-line if statement, I'd rather do something like:
x and return x
But that is invalid Python. Am I missing a simple, elegant solution here? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times.
[/INST] Alternatively to Martijn's fine answer, you could chain or. This will return the first truthy value, or None if there's no truthy value:
def check_all_conditions():
return check_size() or check_color() or check_tone() or check_flavor() or None
Demo:
>>> x = [] or 0 or {} or -1 or None
>>> x
-1
>>> x = [] or 0 or {} or '' or None
>>> x is None
True
</s> |
<s>[INST] Get unique values from a list in python I want to get the unique values from the following list:
[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
The output which I require is:
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']
I tried the following code:
output = []
for x in trends:
if x not in output:
output.append(x)
print output
but it didn't work. Any help would be appreciated.
[/INST] First declare your list properly, separated by commas
You can get the unique values by converting the list to a set
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
myset = set(mylist)
print myset
If you use it further as a list, you should convert it back to list by doing
mynewlist = list(myset)
Another possibility, probably faster would be to use a set from the beginning, instead of a list. Then your code should be
output = set()
for x in trends:
output.add(x)
print output
As it has been pointed out, the sets do not maintain the original order. If you need so, you should look up about the ordered set
</s> |
<s>[INST] How can I fill out a Python string with spaces? I want to fill out a string with spaces. I know that the following works for zero's:
>>> print "'%06d'"%4
'000004'
But what should I do when I want this?:
'hi '
of course I can measure string length and do str+" "*leftover, but I'd like the shortest way.
[/INST] You can do this with str.ljust(width[, fillchar]):
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
>>> 'hi'.ljust(10)
'hi '
</s> |
<s>[INST] How to set the current working directory in Python? How to set the current working directory in Python?
[/INST] Try os.chdir
os.chdir(path)
        Change the current working directory to path. Availability: Unix, Windows.
</s> |
<s>[INST] Can I get JSON to load into an OrderedDict in Python? Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.
But can it be used as an output? If so how? In my case I'd like to load into an OrderedDict so I can keep the order of the keys in the file.
If not, is there some kind of workaround?
[/INST] Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.
>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>>
You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:
>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
"foo": 1,
"bar": 2
}
>>>
Using json.load is done in the same way:
>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
</s> |
<s>[INST] TypeError: 'str' does not support the buffer interface plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
The above python code is giving me following error:
Traceback (most recent call last):
File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 33, in <module>
compress_string()
File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 15, in compress_string
outfile.write(plaintext)
File "C:\Python32\lib\gzip.py", line 312, in write
self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface
[/INST] If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it).
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
Also do not use variable names like string or file while those are names of module or function.
EDIT @Tom
Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:
plaintext = 'Polish text: Ä
ÄÄÅÅóÅźżÄÄÄÅÅÃÅŹŻ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
outfile_content = infile.read().decode('UTF-8')
print(outfile_content)
</s> |
<s>[INST] Understanding dict.copy() - shallow or deep? While reading up the documentation for dict.copy(), it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
The m.copy() method makes a shallow
copy of the items contained in a
mapping object and places them in a
new mapping object.
Consider this:
>>> original = dict(a=1, b=2)
>>> new = original.copy()
>>> new.update({'c': 3})
>>> original
{'a': 1, 'b': 2}
>>> new
{'a': 1, 'c': 3, 'b': 2}
So I assumed this would update the value of original (and add 'c': 3) also since I was doing a shallow copy. Like if you do it for a list:
>>> original = [1, 2, 3]
>>> new = original
>>> new.append(4)
>>> new, original
([1, 2, 3, 4], [1, 2, 3, 4])
This works as expected.
Since both are shallow copies, why is that the dict.copy() doesn't work as I expect it to? Or my understanding of shallow vs deep copying is flawed?
[/INST] By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
In contrast, a deep copy will copy all contents by value.
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
So:
a = b: Reference assignment, Make a and b points to the same object.
a ---,
v
{1: L}
^ |
b ---' '----> [1,2,3]
a = b.copy(): Shallow copying, a and b will become two isolated objects, but their contents still share the same reference
a ---> {1: L}
|
>---> [1,2,3]
|
b ---> {1: M}
a = copy.deepcopy(b): Deep copying, a and b's structure and content become completely isolated.
a ---> {1: L}
â-----> [1,2,3]
b ---> {1: M}
â-----> [1,2,3]
</s> |
<s>[INST] mysql_config not found when installing mysqldb python interface I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,
python setup.py install
I get the following error report related to the mysql_config command.
sh: mysql_config: command not found
Traceback (most recent call last):
File "setup.py", line 15, in <module>
metadata, options = get_config()
File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
Has anyone else encountered this error and if so how did you resolve it/what can I do to successfully install mysqldb?
[/INST] mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command 'mysql_config', so you need to install that first.
Can you confirm that you did or did not install mysql itself, by running "mysql" from the shell? That should give you a response other than "mysql: command not found".
Which linux distribution are you using? Mysql is pre-packaged for most linux distributions. For example, for debian / ubuntu, installing mysql is as easy as
sudo apt-get install mysql-server
mysql-config is in a different package, which can be installed from (again, assuming debian / ubuntu):
sudo apt-get install libmysqlclient-dev
if you are using mariadb, the drop in replacement for mysql, then run
sudo apt-get install libmariadbclient-dev
</s> |
<s>[INST] How to make an unaware datetime timezone aware in python What I need to do
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.
What I've Tried
First, to demonstrate the problem:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
First, I tried astimezone:
>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>
It's not terribly surprising this failed, since it's actually trying to do a conversion. Replace seemed like a better choice (as per Python: How to get a value of datetime.today() that is "timezone aware"?):
>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>
But as you can see, replace seems to set the tzinfo, but not make the object aware. I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.
Also, I've tried this in both python 2.6 and python 2.7, with the same results.
Context
I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.
[/INST] In general, to make a naive datetime timezone-aware, use the localize method:
import datetime
import pytz
unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)
now_aware = pytz.utc.localize(unaware)
assert aware == now_aware
For the UTC timezone, it is not really necessary to use localize since there is no daylight savings time calculation to handle:
now_aware = unaware.replace(tzinfo=pytz.UTC)
works. (.replace returns a new datetime; it does not modify unaware.)
</s> |
<s>[INST] How to Python prettyprint a JSON file I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.
[/INST] The json module already implements some basic pretty printing with the indent parameter:
>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
To parse a file, use json.load:
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
</s> |
<s>[INST] How to get the position of a character in Python? How can I get the position of a character inside a string in python?
[/INST] There are two string methods for this, find and index.
Example:
>>> myString = "Position of a character"
>>> myString.index('s')
2
The difference is that find returns -1 when what you're looking for isn't found. index throws an exception.
Function str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
And:
Function str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
</s> |
<s>[INST] Django - How to rename a model field using South? I would like to change a name of specific fields in a model:
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
should change to:
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.ForeignKey(Bar)
What's the easiest way to do this using South?
[/INST] You can use the db.rename_column function.
class Migration:
def forwards(self, orm):
# Rename 'name' field to 'full_name'
db.rename_column('app_foo', 'name', 'full_name')
def backwards(self, orm):
# Rename 'full_name' field to 'name'
db.rename_column('app_foo', 'full_name', 'name')
The first argument of db.rename_column is the table name, so it's important to remember how Django creates table names:
Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model's database table name is constructed by joining the model's "app label" -- the name you used in manage.py startapp -- to the model's class name, with an underscore between them.
In the case where you have a multi-worded, camel-cased model name, such as ProjectItem, the table name will be app_projectitem (i.e., an underscore will not be inserted between project and item even though they are camel-cased).
</s> |
<s>[INST] Reading binary file in Python and looping over each byte In Python, how do I read in a binary file and loop over each byte of that file?
[/INST] f = open("myfile", "rb")
try:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
By suggestion of chrispy:
with open("myfile", "rb") as f:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it:
from __future__ import with_statement
In 2.6 this is not needed.
In Python 3, it's a bit different. We will no longer get raw characters from the stream in byte mode but byte objects, thus we need to alter the condition:
with open("myfile", "rb") as f:
byte = f.read(1)
while byte != b"":
# Do stuff with byte.
byte = f.read(1)
Or as benhoyt says, skip the not equal and take advantage of the fact that b"" evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.
with open("myfile", "rb") as f:
byte = f.read(1)
while byte:
# Do stuff with byte.
byte = f.read(1)
</s> |
<s>[INST] How to declare an array in Python? How do I declare an array in Python?
I can't find any reference to arrays in the documentation.
[/INST] variable = []
Now variable refers to an empty list*.
Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.
*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.
</s> |
<s>[INST] Using module 'subprocess' with timeout Here's the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
communicate is used to wait for the process to exit:
stdoutdata, stderrdata = proc.communicate()
The subprocess module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, communicate may take forever to run.
What is the simplest way to implement timeouts in a Python program meant to run on Windows and Linux?
[/INST] I don't know much about the low level details; but, given that in
python 2.6 the API offers the ability to wait for threads and
terminate processes, what about running the process in a separate
thread?
import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)
The output of this snippet in my machine is:
Thread started
Process started
Process finished
Thread finished
0
Thread started
Process started
Terminating process
Thread finished
-15
where it can be seen that, in the first execution, the process
finished correctly (return code 0), while the in the second one the
process was terminated (return code -15).
I haven't tested in windows; but, aside from updating the example
command, I think it should work since I haven't found in the
documentation anything that says that thread.join or process.terminate
is not supported.
</s> |
<s>[INST] pip install lxml error this is my error :
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml2 and libxslt are installed **
Using build configuration of libxslt
Installing collected packages: lxml
Running setup.py install for lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml2 and libxslt are installed **
Using build configuration of libxslt
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:4: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml2 and libxslt are installed **
Using build configuration of libxslt
running install
running build
running build_py
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:4: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
what can i do ,
thanks
updated:
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
Using build configuration of libxslt 1.1.26
Building against libxml2/libxslt in the following directory: /usr/lib
Installing collected packages: lxml
Running setup.py install for lxml
Building lxml version 2.3.
Building without Cython.
Using build configuration of libxslt 1.1.26
Building against libxml2/libxslt in the following directory: /usr/lib
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:4: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
Building lxml version 2.3.
Building without Cython.
Using build configuration of libxslt 1.1.26
Building against libxml2/libxslt in the following directory: /usr/lib
running install
running build
running build_py
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:4: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
the log :
------------------------------------------------------------
/home/zjm1126/zjm_test/mysite/bin/pip run on Thu Mar 3 17:07:27 2011
Downloading/unpacking mysql-python
Running setup.py egg_info for package mysql-python
running egg_info
creating pip-egg-info/MySQL_python.egg-info
writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
warning: manifest_maker: standard file '-c' not found
reading manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'MANIFEST'
warning: no files found matching 'ChangeLog'
warning: no files found matching 'GPL'
writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
Installing collected packages: mysql-python
Running setup.py install for mysql-python
Running command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6
running install
running build
running build_py
creating build
creating build/lib.linux-i686-2.6
copying _mysql_exceptions.py -> build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb
creating build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-i686-2.6
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
In file included from _mysql.c:29:
pymemcompat.h:10: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
running install
running build
running build_py
creating build
creating build/lib.linux-i686-2.6
copying _mysql_exceptions.py -> build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb
creating build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-i686-2.6
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
In file included from _mysql.c:29:
pymemcompat.h:10: fatal error: Python.h: 没æé£ä¸ªæä»¶æç®å½
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Exception information:
Traceback (most recent call last):
File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/basecommand.py", line 130, in main
self.run(options, args)
File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/commands/install.py", line 228, in run
requirement_set.install(install_options, global_options)
File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 1043, in install
requirement.install(install_options, global_options)
File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 559, in install
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/__init__.py", line 249, in call_subprocess
% (command_desc, proc.returncode))
InstallationError: Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
[/INST]
** make sure the development packages of libxml2 and libxslt are installed **
Assuming you are running a Debian-based distribution
sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev
If you're installing for Python 3 on Debian-based distributions, you'll want to install python3-dev too.
</s> |
<s>[INST] Importing modules from parent folder I am running Python 2.5.
This is my folder tree:
ptdraft/
nib.py
simulations/
life/
life.py
(I also have __init__.py in each folder, omitted here for readability)
How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.
Note: The main module being run is in the ptdraft folder.
[/INST] You could use relative imports (python >= 2.5):
from ... import nib
(Whatâs New in Python 2.5) PEP 328: Absolute and Relative Imports
EDIT: added another dot '.' to go up two packages
</s> |
<s>[INST] pip install from github repo branch Seems to be rather straightforward but I just can't get it right. Trying to pip install a repo's specific branch. Googling tells me to
pip install https://github.com/user/repo.git@branch
The branch's name is issue/34/oscar-0.6 so I did pip install https://github.com/tangentlabs/django-oscar-paypal.git@/issue/34/oscar-0.6 but its returning a 404.
How do I install this branch?
[/INST] Prepend the url prefix git+ (See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /.
</s> |
<s>[INST] Circular (or cyclic) imports in Python What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python?
[/INST] There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.
Imports are pretty straightforward really. Just remember the following:
'import' and 'from xxx import yyy' are executable statements. They execute
when the running program reaches that line.
If a module is not in sys.modules, then an import creates the new module
entry in sys.modules and then executes the code in the module. It does not
return control to the calling module until the execution has completed.
If a module does exist in sys.modules then an import simply returns that
module whether or not it has completed executing. That is the reason why
cyclic imports may return modules which appear to be partly empty.
Finally, the executing script runs in a module named __main__, importing
the script under its own name will create a new module unrelated to
__main__.
Take that lot together and you shouldn't get any surprises when importing
modules.
</s> |
<s>[INST] How do I watch a file for changes using Python? I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.
What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotification function but have no idea how to ask it to watch a specific file.
If anyone's done anything like this I'd be really grateful to hear how...
[Edit] I should have mentioned that I was after a solution that doesn't require polling.
[Edit] Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.
[/INST] Did you try using Watchdog?
Python API library and shell utilities to monitor file system events.
Directory monitoring made easy with
A cross-platform API.
A shell tool to run commands in response to directory changes.
Get started quickly with a simple example in Quickstart...
</s> |
<s>[INST] How do I resize an image using PIL and maintain its aspect ratio? Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
[/INST] Define a maximum size.
Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).
The proper size is oldsize*ratio.
There is of course also a library method to do this: the method Image.thumbnail.
Below is an (edited) example from the PIL documentation.
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
</s> |
<s>[INST] What does the Python Ellipsis object do? While idly surfing the namespace I noticed an odd looking object called "Ellipsis", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?
D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
[/INST] This came up in another question recently. I'll elaborate on my answer from there:
Ellipsis is an object that can appear in slice notation. For example:
myList[1:2, ..., 0]
Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numeric python extension, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4x4 array, the top left area would be defined by the slice [:2,:2]:
>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> a[:2,:2] # top left
array([[1, 2],
[5, 6]])
Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[...,0] is the same as a[:,:,0] and for 4d, a[:,:,:,0], similarly, a[0,...,0] is a[0,:,:,0] (with however many colons in the middle make up the full number of dimensions in the array).
Interestingly, in python3, the Ellipsis literal (...) is usable outside the slice syntax, so you can actually write:
>>> ...
Ellipsis
Other than the various numeric types, no, I don't think it's used. As far as I'm aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn't require this, but the literal "..." support for slices did.
</s> |
<s>[INST] Python access to first element in dictionary If dict is not empty, the way I use to access first element in dict is:
dict[dict.keys()[0]]
Is there any better way to do this?
[/INST] Non-destructively you can:
dict.itervalues().next()
On Python 3 this becomes
next (iter (dict.values()))
If you want it to work in both Python 2 & 3, you can use the six library:
six.next(six.itervalues(dict))
though at this point it is quite cryptic and I'd rather prefer your code.
If you want to remove any item, do:
key, value = dict.popitem()
Note that "first" is not an appropriate term here. This is "any" item, because dict is not an ordered type.
</s> |
<s>[INST] Python List vs. Array - when to use? If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing something obvious?
[/INST] Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your array time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays.
The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data, all of the same type, and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl). It's also a good way to represent a mutable string (array('B', bytes)) until that actually becomes available in Python 3.0.
However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.
To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.
</s> |
<s>[INST] How to find out if a Python object is a string? How can I check if a Python object is a string (either regular or Unicode)?
[/INST] Python 2
Use isinstance(obj, basestring) for an object-to-test obj.
Docs.
</s> |
<s>[INST] How do I disable log messages from the Requests library? By default, the Requests library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them?
[/INST] I found out how to configure requests's logging level, it's done via the standard logging module. I decided to configure it to not log messages unless they are at least warnings:
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
If you wish to apply this setting for the urllib3 library (typically used by requests) too, add the following:
logging.getLogger("urllib3").setLevel(logging.WARNING)
</s> |
<s>[INST] Why is "except: pass" a bad programming practice? I often see comments on other Stack Overflow questions about how the use of except: pass is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code.
try:
something
except:
pass
Why is using an except: pass block bad? What makes it bad? Is it the fact that I pass on an error or that I except any error?
[/INST] The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users.
This is way too much. In your head, you're thinking "I want to ignore this network error". If something unexpected goes wrong, then your code silently continues and breaks in completely unpredictable ways that no one can debug.
That's why you should limit yourself to ignoring specifically only some errors and let the rest pass.
</s> |
<s>[INST] Why doesn't Python have multiline comments? OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
"""Hello, I am a
multiline comment"""
and
'''Hello, I am a
multiline comment'''
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
[/INST] I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".
Guido has tweeted about this,
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
</s> |
<s>[INST] Install a Python package into a different directory using pip? I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that.
So how do I modify the command
pip install package_name
to make pip install the package somewhere other than the default site-packages?
[/INST] Use:
pip install --install-option="--prefix=$PREFIX_PATH" package_name
You might also want to use --ignore-installed to force all dependencies to be reinstalled using this new prefix. You can use --install-option to multiple times to add any of the options you can use with python setup.py install (--prefix is probably what you want, but there are a bunch more options you could use).
</s> |
<s>[INST] What are Class methods in Python for? I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
[/INST] Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.
If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.
</s> |
<s>[INST] How can I check for Python version in a program that uses new language features? If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.
I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:
import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
When run under 2.4, I want this result
$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
and not this result:
$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
(Channeling for a coworker.)
[/INST] You can test using eval:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with is available in Python 2.5, just add from __future__ import with_statement .
EDIT: to get control early enough, you could split it do different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
</s> |
<s>[INST] How do I calculate number of days betwen two dates using Python? If I have two dates (ex. '8/18/2008' and '9/26/2008') what is the best way to get the difference measured in days?
[/INST] If you have two date objects, you can just subtract them.
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print delta.days
The relevant section of the docs:
https://docs.python.org/library/datetime.html
</s> |
<s>[INST] How can I install packages in my $HOME folder with pip? Is it possible? When installing pip, install the python packages inside my $HOME folder. (for example, I want to install mercurial, using pip, but inside $HOME instead of /usr/local)
I'm with a mac machine and just thought about this possibility, instead of "polluting" my /usr/local, I would use my $HOME instead.
PEP370 is exactly about this. Is just creating a Ë/.local and do a pip install package enough to make these packages to be installed only at my $HOME folder?
[/INST] While you can use a virtualenv, you don't need to. The trick is passing the PEP370 --user argument to the setup.py script. With the latest version of pip, one way to do it is:
pip install --user mercurial
This should result in the hg script being installed in $HOME/.local/bin/hg and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local to $HOME/Library/Python. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg and $HOME/Library/Python/x.y/lib/python/site-packages.
</s> |
<s>[INST] Is there any difference between "foo is None" and "foo == None"? Is there any difference between:
if foo is None: pass
and
if foo == None: pass
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
[/INST] is always returns True if it compares the same object instance
Whereas == is ultimately determined by the __eq__() method
i.e.
>>> class foo(object):
def __eq__(self, other):
return True
>>> f = foo()
>>> f == None
True
>>> f is None
False
</s> |
<s>[INST] Understanding __get__ and __set__ and Python descriptors I am trying to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code:
class Celsius(object):
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
class Temperature(object):
celsius = Celsius()
Why do I need the descriptor class? Please explain using this example or the one you think is better.
What is instance and owner here? (in __get__). So my question is, what is the purpose of the third parameter here?
How would I call/ use this example?
[/INST] The descriptor is how Python's property type is implemented. A descriptor simply implements __get__, __set__, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example:
temp=Temperature()
temp.celsius #calls celsius.__get__
Accessing the property you assigned the descriptor to (celsius in the above example) calls the appropriate descriptor method.
instance in __get__ is the instance of the class (so above, __get__ would receive temp, while owner is the class with the descriptor (so it would be Temperature).
You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.
An article about descriptors can be found at http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/
EDIT: As jchl pointed out in the comments, if you simply try Temperature.celsius, instance will be None.
</s> |
<s>[INST] Reloading submodules in IPython Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice.
In IPython, the framework is loaded by a simple import command. However, it is often necessary to change code in one of the submodules of the framework. At this point a model is already loaded and I use IPython to interact with it.
Now, the framework contains many modules that depend on each other, i.e. when the framework is initially loaded the main module is importing and configuring the submodules. The changes to the code are only executed if the module is reloaded using reload(main_mod.sub_mod). This is cumbersome as I need to reload all changed modules individually using the full path. It would be very convenient if reload(main_module) would also reload all sub modules, but without reloading numpy/scipy..
[/INST] IPython comes with some automatic reloading magic:
%load_ext autoreload
%autoreload 2
It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.
If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
Credit to @Kos via a comment below.
[1]
If you don't have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.
</s> |
<s>[INST] Class method differences in Python: bound, unbound and static What is the difference between the following class methods?
Is it that one is static and the other is not?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
[/INST] In Python, there is a distinction between bound and unbound methods.
Basically, a call to a member function (like method_one), a bound function
a_test.method_one()
is translated to
Test.method_one(a_test)
i.e. a call to an unbound method. Because of that, a call to your version of method_two will fail with a TypeError
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
You can change the behavior of a method using a decorator
class Test(object):
def method_one(self):
print "Called method_one"
@staticmethod
def method_two():
print "Called method two"
The decorator tells the built-in default metaclass type (the class of a class, cf. this question) to not create bound methods for method_two.
Now, you can invoke static method both on an instance or on the class directly:
>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two
</s> |
<s>[INST] How do I test one variable against multiple values? I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")
elif x or y or z == 2 :
Mylist.append("e")
elif x or y or z == 3 :
Mylist.append("f")
which would return a list of
["c", "d", "f"]
Is something like this possible?
[/INST] You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x and y are otherwise evaluated on their own (False if 0, True otherwise).
You can shorten that to:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).
When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.
This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.
x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.
</s> |
<s>[INST] Asking the user for input until they give a valid response I am writing a program that must accept input from the user.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
This works as expected if the user enters sensible data.
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
But if they make a mistake, then it crashes:
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in <module>
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
Instead of crashing, I would like it to try getting the input again. Like this:
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
How can I accomplish this? What if I also wanted to reject values like -1, which is a valid int, but nonsensical in this context?
[/INST] The simplest way to accomplish this would be to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.
When Your Input Might Raise an Exception
Use try and catch to detect when the user enters data that can't be parsed.
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Implementing Your Own Validation Rules
If you want to reject values that Python can successfully parse, you can add your own validation logic.
while True:
data = input("Please enter a loud message (must be all caps): ")
if not data.isupper():
print("Sorry, your response was not loud enough.")
continue
else:
#we're happy with the value given.
#we're ready to exit the loop.
break
while True:
data = input("Pick an answer from A to D:")
if data.lower() not in ('a', 'b', 'c', 'd'):
print("Not an appropriate choice.")
else:
break
Combining Exception Handling and Custom Validation
Both of the above techniques can be combined into one loop.
while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
#age was successfully parsed, and we're happy with its value.
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Encapsulating it All in a Function
If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.
def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value
age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")
Putting it all together
You can extend this idea to make a very generic input function:
def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
if type_ is not None:
try:
ui = type_(ui)
except ValueError:
print("Input type must be {0}.".format(type_.__name__))
continue
if max_ is not None and ui > max_:
print("Input must be less than or equal to {0}.".format(max_))
elif min_ is not None and ui < min_:
print("Input must be greater than or equal to {0}.".format(min_))
elif range_ is not None and ui not in range_:
if isinstance(range_, range):
template = "Input must be between {0.start} and {0.stop}."
print(template.format(range_))
else:
template = "Input must be {0}."
if len(range_) == 1:
print(template.format(*range_))
else:
print(template.format(" or ".join((", ".join(map(str,
range_[:-1])),
str(range_[-1])))))
else:
return ui
With usage such as:
age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer", str.lower, range_=('a', 'b', 'c', 'd'))
Common Pitfalls, and Why you Should Avoid Them
The Redundant Use of Redundant input Statements
This method works but is generally considered poor style:
data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
print("Sorry, your response was not loud enough.")
data = input("Please enter a loud message (must be all caps): ")
It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.
Recursion Will Blow Your Stack
If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.
def get_non_negative_int(prompt):
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
return get_non_negative_int(prompt)
if value < 0:
print("Sorry, your response must not be negative.")
return get_non_negative_int(prompt)
else:
return value
This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!
</s> |
<s>[INST] Is there a Numpy function to return the first index of something in an array? I know there is a method for python list to return the first index of something
l = list(1,2,3)
l.index(2)
>>> 1
Is there something like that for numpy arrays?
[/INST] Yes, here is the answer given a Numpy array, array, and a value, item, to search for.
itemindex = numpy.where(array==item)
The result is a tuple with first all the row indices, then all the column indices.
For example if array is two dimensions and it contained your item at two locations then
array[itemindex[0][0]][itemindex[1][0]]
would be equal to your item and so would
array[itemindex[0][1]][itemindex[1][1]]
numpy.where
</s> |
<s>[INST] How to copy a dictionary and only edit the copy Can someone please explain this to me? This doesn't make any sense to me.
I copy a dictionary into another and edit the second and both are changed. Why is this happening?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2', 'key1': 'value1'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
[/INST] Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.
If you want to copy the dict (which is rare), you have to do so explicitly with
dict2 = dict(dict1)
or
dict2 = dict1.copy()
</s> |
<s>[INST] Empty set literal in Python? [] = empty list
() = empty tuple
{} = empty dict
Is there a similar notation for an empty set?
Or do I have to write set()?
[/INST] No, there's no literal syntax for the empty set. You have to write set().
</s> |
<s>[INST] Django - what is the difference between render(), render_to_response() and direct_to_template()? Whats the difference (in language a python/django noob can understand) in a view between render(), render_to_response() and direct_to_template()?
e.g. from Nathan Borror's basic apps examples
def comment_edit(request, object_id, template_name='comments/edit.html'):
comment = get_object_or_404(Comment, pk=object_id, user=request.user)
# ...
return render(request, template_name, {
'form': form,
'comment': comment,
})
But I've also seen
return render_to_response(template_name, my_data_dictionary,
context_instance=RequestContext(request))
And
return direct_to_template(request, template_name, my_data_dictionary)
Whats the difference, what to use in any particular situation?
[/INST] https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render
render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])
render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response
render_to_response(template[, dictionary][, context_instance][, mimetype])¶
render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)
https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template
direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.
But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/
I'm happy I haven't typed RequestContext in a long, long time.
</s> |
<s>[INST] Unicode (utf8) reading and writing to files in python I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).
# the string, which has an a-acute in it.
ss = u'Capit\xe1n'
ss8 = ss.encode('utf8')
repr(ss), repr(ss8)
("u'Capit\xe1n'", "'Capit\xc3\xa1n'")
print ss, ss8
print >> open('f1','w'), ss8
>>> file('f1').read()
'Capit\xc3\xa1n\n'
So I type in Capit\xc3\xa1n into my favorite editor, in file f2.
then:
>>> open('f1').read()
'Capit\xc3\xa1n\n'
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
>>> open('f1').read().decode('utf8')
u'Capit\xe1n\n'
>>> open('f2').read().decode('utf8')
u'Capit\\xc3\\xa1n\n'
What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.
Edit: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?
>>> print simplejson.dumps(ss)
'"Capit\u00e1n"'
>>> print >> file('f3','w'), simplejson.dumps(ss)
>>> simplejson.load(open('f3'))
u'Capit\xe1n'
[/INST] Rather than mess with the encode, decode methods I find it easier to use the open method from the codecs module.
>>>import codecs
>>>f = codecs.open("test", "r", "utf-8")
Then after calling f's read() function, an encoded unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
If you know the encoding of a file, using the codecs package is going to be much less confusing.
See http://docs.python.org/library/codecs.html#codecs.open
</s> |
<s>[INST] Create List of Single Item Repeated n Times in Python I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach.
I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing
[e for number in xrange(n)]
for each list?
[/INST] You can also write:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
Performance testing
At first glance it seems that repeat is the fastest way to create a list with n identical elements:
>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819
But wait - it's not a fair test...
>>> itertools.repeat(0, 10)
repeat(0, 10) # Not a list!!!
The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:
>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233
So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.
</s> |
<s>[INST] How can I represent an infinite number in Python? In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
[/INST] In Python, you can do:
test = float("inf")
In Python 3.5, you can do:
import math
test = math.inf
And then:
test > 1
test > 10000
test > x
Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").
Additionally (Python 2.x ONLY), in a comparison to Ellipsis, float(inf) is lesser, e.g:
float('inf') < Ellipsis
would return true.
</s> |
<s>[INST] What is the difference between Python's re.search and re.match? What is the difference between the search() and match() functions in the Python re module?
I've read the documentation (current documentation), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.
[/INST] re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.
As re.match documentation says:
If zero or more characters at the
beginning of string match the regular expression pattern, return a
corresponding MatchObject instance.
Return None if the string does not
match the pattern; note that this is
different from a zero-length match.
Note: If you want to locate a match
anywhere in string, use search()
instead.
re.search searches the entire string, as the documentation says:
Scan through string looking for a
location where the regular expression
pattern produces a match, and return a
corresponding MatchObject instance.
Return None if no position in the
string matches the pattern; note that
this is different from finding a
zero-length match at some point in the
string.
So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.
The documentation has a specific section for match vs. search that also covers multiline strings:
Python offers two different primitive
operations based on regular
expressions: match checks for a match
only at the beginning of the string,
while search checks for a match
anywhere in the string (this is what
Perl does by default).
Note that match may differ from search
even when using a regular expression
beginning with '^': '^' matches only
at the start of the string, or in
MULTILINE mode also immediately
following a newline. The âmatchâ
operation succeeds only if the pattern
matches at the start of the string
regardless of mode, or at the starting
position given by the optional pos
argument regardless of whether a
newline precedes it.
Now, enough talk. Time to some example code:
# example code:
string_with_newlines = """something
someotherthing"""
import re
print re.match('some', string_with_newlines) # matches
print re.match('someother',
string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
re.MULTILINE) # also won't match
print re.search('someother',
string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
re.MULTILINE) # also finds something
m = re.compile('thing$', re.MULTILINE)
print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches
</s> |
<s>[INST] Get key by value in dictionary I made a function which will look up ages in dictionary and show the matching name:
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out to make it search backwards.
[/INST] mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george
Or in Python 3.x:
mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george
Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.
More about keys() and .values() in Python 3: Python: simplest way to get list of values from dict?
</s> |
<s>[INST] Representing and solving a maze given an image What is the best way to represent and solve a maze given an image?
Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel by pixel and store it in a list (array) of boolean values: True for a white pixel, and False for a non-white pixel (the colours can be discarded). The issue with this method, is that the image may not be "pixel perfect". By that I simply mean that if there is a white pixel somewhere on a wall it may create an unintended path.
Another method (which came to me after a bit of thought) is to convert the image to an SVG file - which is a list of paths drawn on a canvas. This way, the paths could be read into the same sort of list (boolean values) where True indicates a path or wall, False indicating a travel-able space. An issue with this method arises if the conversion is not 100% accurate, and does not fully connect all of the walls, creating gaps.
Also an issue with converting to SVG is that the lines are not "perfectly" straight. This results in the paths being cubic bezier curves. With a list (array) of boolean values indexed by integers, the curves would not transfer easily, and all the points that line on the curve would have to be calculated, but won't exactly match to list indices.
I assume that while one of these methods may work (though probably not) that they are woefully inefficient given such a large image, and that there exists a better way. How is this best (most efficiently and/or with the least complexity) done? Is there even a best way?
Then comes the solving of the maze. If I use either of the first two methods, I will essentially end up with a matrix. According to this answer, a good way to represent a maze is using a tree, and a good way to solve it is using the A* algorithm. How would one create a tree from the image? Any ideas?
TL;DR
Best way to parse? Into what data structure? How would said structure help/hinder solving?
UPDATE
I've tried my hand at implementing what @Mikhail has written in Python, using numpy, as @Thomas recommended. I feel that the algorithm is correct, but it's not working as hoped. (Code below.) The PNG library is PyPNG.
import png, numpy, Queue, operator, itertools
def is_white(coord, image):
""" Returns whether (x, y) is approx. a white pixel."""
a = True
for i in xrange(3):
if not a: break
a = image[coord[1]][coord[0] * 3 + i] > 240
return a
def bfs(s, e, i, visited):
""" Perform a breadth-first search. """
frontier = Queue.Queue()
while s != e:
for d in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
np = tuple(map(operator.add, s, d))
if is_white(np, i) and np not in visited:
frontier.put(np)
visited.append(s)
s = frontier.get()
return visited
def main():
r = png.Reader(filename = "thescope-134.png")
rows, cols, pixels, meta = r.asDirect()
assert meta['planes'] == 3 # ensure the file is RGB
image2d = numpy.vstack(itertools.imap(numpy.uint8, pixels))
start, end = (402, 985), (398, 27)
print bfs(start, end, image2d, [])
[/INST] Here is a solution.
Convert image to grayscale (not yet binary), adjusting weights for the colors so that final grayscale image is approximately uniform. You can do it simply by controlling sliders in Photoshop in Image -> Adjustments -> Black & White.
Convert image to binary by setting appropriate threshold in Photoshop in Image -> Adjustments -> Threshold.
Make sure threshold is selected right. Use the Magic Wand Tool with 0 tolerance, point sample, contiguous, no anti-aliasing. Check that edges at which selection breaks are not false edges introduced by wrong threshold. In fact, all interior points of this maze are accessible from the start.
Add artificial borders on the maze to make sure virtual traveler will not walk around it :)
Implement breadth-first search (BFS) in your favorite language and run it from the start. I prefer MATLAB for this task. As @Thomas already mentioned, there is no need to mess with regular representation of graphs. You can work with binarized image directly.
Here is the MATLAB code for BFS:
function path = solve_maze(img_file)
%% Init data
img = imread(img_file);
img = rgb2gray(img);
maze = img > 0;
start = [985 398];
finish = [26 399];
%% Init BFS
n = numel(maze);
Q = zeros(n, 2);
M = zeros([size(maze) 2]);
front = 0;
back = 1;
function push(p, d)
q = p + d;
if maze(q(1), q(2)) && M(q(1), q(2), 1) == 0
front = front + 1;
Q(front, :) = q;
M(q(1), q(2), :) = reshape(p, [1 1 2]);
end
end
push(start, [0 0]);
d = [0 1; 0 -1; 1 0; -1 0];
%% Run BFS
while back <= front
p = Q(back, :);
back = back + 1;
for i = 1:4
push(p, d(i, :));
end
end
%% Extracting path
path = finish;
while true
q = path(end, :);
p = reshape(M(q(1), q(2), :), 1, 2);
path(end + 1, :) = p;
if isequal(p, start)
break;
end
end
end
It is really very simple and standard, there should not be difficulties on implementing this in Python or whatever.
And here is the answer:
</s> |
<s>[INST] What is the standard way to add N seconds to datetime.time in Python? Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02, for example?
These obvious ideas don't work:
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
In the end I have written functions like this:
def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
I can't help thinking that I'm missing an easier way to do this though.
Related
python time + timedelta equivalent
[/INST] You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.
For example:
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print a.time()
print b.time()
results in the two values, three seconds apart:
11:34:59
11:35:02
You could also opt for the more readable
b = a + datetime.timedelta(seconds=3)
if you're so inclined.
If you're after a function that can do this, you can look into using addSecs below:
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print a
print b
This outputs:
09:11:55.775695
09:16:55
</s> |
<s>[INST] Removing a list of characters in string I want to remove characters in a string in python:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
But I have many characters I have to remove. I thought about a list
list = [',', '!', '.', ';'...]
But how can I use the list to replace the characters in the string?
[/INST] If you're using python2 and your inputs are strings (not unicodes), the absolutely best method is str.translate:
>>> chars_to_remove = ['.', '!', '?']
>>> subj = 'A.B!C?'
>>> subj.translate(None, ''.join(chars_to_remove))
'ABC'
Otherwise, there are following options to consider:
A. Iterate the subject char by char, omit unwanted characters and join the resulting list:
>>> sc = set(chars_to_remove)
>>> ''.join([c for c in subj if c not in sc])
'ABC'
(Note that the generator version ''.join(c for c ...) will be less efficient).
B. Create a regular expression on the fly and re.sub with an empty string:
>>> import re
>>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
>>> re.sub(rx, '', subj)
'ABC'
(re.escape ensures that characters like ^ or ] won't break the regular expression).
C. Use the mapping variant of translate:
>>> chars_to_remove = [u'δ', u'Î', u'ж']
>>> subj = u'AжBδCÎ'
>>> dd = {ord(c):None for c in chars_to_remove}
>>> subj.translate(dd)
u'ABC'
Full testing code and timings:
#coding=utf8
import re
def remove_chars_iter(subj, chars):
sc = set(chars)
return ''.join([c for c in subj if c not in sc])
def remove_chars_re(subj, chars):
return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)
def remove_chars_re_unicode(subj, chars):
return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)
def remove_chars_translate_bytes(subj, chars):
return subj.translate(None, ''.join(chars))
def remove_chars_translate_unicode(subj, chars):
d = {ord(c):None for c in chars}
return subj.translate(d)
import timeit, sys
def profile(f):
assert f(subj, chars_to_remove) == test
t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
print ('{0:.3f} {1}'.format(t, f.__name__))
print (sys.version)
PYTHON2 = sys.version_info[0] == 2
print ('\n"plain" string:\n')
chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?' * 1000
test = 'ABC' * 1000
profile(remove_chars_iter)
profile(remove_chars_re)
if PYTHON2:
profile(remove_chars_translate_bytes)
else:
profile(remove_chars_translate_unicode)
print ('\nunicode string:\n')
if PYTHON2:
chars_to_remove = [u'δ', u'Î', u'ж']
subj = u'AжBδCÎ'
else:
chars_to_remove = ['δ', 'Î', 'ж']
subj = 'AжBδCÎ'
subj = subj * 1000
test = 'ABC' * 1000
profile(remove_chars_iter)
if PYTHON2:
profile(remove_chars_re_unicode)
else:
profile(remove_chars_re)
profile(remove_chars_translate_unicode)
Results:
2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
"plain" string:
0.637 remove_chars_iter
0.649 remove_chars_re
0.010 remove_chars_translate_bytes
unicode string:
0.866 remove_chars_iter
0.680 remove_chars_re_unicode
1.373 remove_chars_translate_unicode
---
3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
"plain" string:
0.512 remove_chars_iter
0.574 remove_chars_re
0.765 remove_chars_translate_unicode
unicode string:
0.817 remove_chars_iter
0.686 remove_chars_re
0.876 remove_chars_translate_unicode
(As a side note, the figure for remove_chars_translate_bytes might give us a clue why the industry was reluctant to adopt Unicode for such a long time).
</s> |
<s>[INST] Plot logarithmic axes with matplotlib in python I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.plot(a, color='blue', lw=2)
show()
[/INST] You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
ax.set_yscale('log')
You can use 'linear' to switch back to a linear scale. Here's what your code would look like:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.plot(a, color='blue', lw=2)
ax.set_yscale('log')
show()
</s> |
<s>[INST] PyPy -- How can it possibly beat CPython? From the Google Open Source Blog:
PyPy is a reimplementation of Python
in Python, using advanced techniques
to try to attain better performance
than CPython. Many years of hard work
have finally paid off. Our speed
results often beat CPython, ranging
from being slightly slower, to
speedups of up to 2x on real
application code, to speedups of up to
10x on small benchmarks.
How is this possible? Which Python implementation was used to implement PyPy? CPython? And what are the chances of a PyPyPy or PyPyPyPy beating their score?
(On a related note... why would anyone try something like this?)
[/INST] "PyPy is a reimplementation of Python in Python" is a rather misleading way to describe PyPy, IMHO, although it's technically true.
There are two major parts of PyPy.
The translation framework
The interpreter
The translation framework is a compiler. It compiles RPython code down to C (or other targets), automatically adding in aspects such as garbage collection and a JIT compiler. It cannot handle arbitrary Python code, only RPython.
RPython is a subset of normal Python; all RPython code is Python code, but not the other way around. There is no formal definition of RPython, because RPython is basically just "the subset of Python that can be translated by PyPy's translation framework". But in order to be translated, RPython code has to be statically typed (the types are inferred, you don't declare them, but it's still strictly one type per variable), and you can't do things like declaring/modifying functions/classes at runtime either.
The interpreter then is a normal Python interpreter written in RPython.
Because RPython code is normal Python code, you can run it on any Python interpreter. But none of PyPy's speed claims come from running it that way; this is just for a rapid test cycle, because translating the interpreter takes a long time.
With that understood, it should be immediately obvious that speculations about PyPyPy or PyPyPyPy don't actually make any sense. You have an interpreter written in RPython. You translate it to C code that executes Python quickly. There the process stops; there's no more RPython to speed up by processing it again.
So "How is it possible for PyPy to be faster than CPython" also becomes fairly obvious. PyPy has a better implementation, including a JIT compiler (it's generally not quite as fast without the JIT compiler, I believe, which means PyPy is only faster for programs susceptible to JIT-compilation). CPython was never designed to be a highly optimising implementation of the Python language (though they do try to make it a highly optimised implementation, if you follow the difference).
The really innovative bit of the PyPy project is that they don't write sophisticated GC schemes or JIT compilers by hand. They write the interpreter relatively straightforwardly in RPython, and for all RPython is lower level than Python it's still an object-oriented garbage collected language, much more high level than C. Then the translation framework automatically adds things like GC and JIT. So the translation framework is a huge effort, but it applies equally well to the PyPy python interpreter however they change their implementation, allowing for much more freedom in experimentation to improve performance (without worrying about introducing GC bugs or updating the JIT compiler to cope with the changes). It also means when they get around to implementing a Python3 interpreter, it will automatically get the same benefits. And any other interpreters written with the PyPy framework (of which there are a number at varying stages of polish). And all interpreters using the PyPy framework automatically support all platforms supported by the framework.
So the true benefit of the PyPy project is to separate out (as much as possible) all the parts of implementing an efficient platform-independent interpreter for a dynamic language. And then come up with one good implementation of them in one place, that can be re-used across many interpreters. That's not an immediate win like "my Python program runs faster now", but it's a great prospect for the future.
And it can run your Python program faster (maybe).
</s> |
<s>[INST] What does the 'b' character do in front of a string literal? Apparently, the following is valid syntax...
my_string = b'The string'
I would like to know...
What does this b character infront of the string mean?
What are the effects of using it?
What are appropriate situations to use it.
I found a related question right here on SO but that question is about PHP though and it states the b is used to indicate the string is binary as opposed to unicode which was needed for code to be compatible from version of PHP < 6 when migrating to PHP 6. I don't think this applies to Python.
I did find this documentation on the python site about using a u character in the same syntax to specify a string as unicode. Unfortunately it doesn't mention the b character anywhere in that document.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
[/INST] Python 3.x makes a clear distinction between the types:
str = '...' literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled)
bytes = b'...' literals = a sequence of octets (integers between 0 and 255)
If you're familiar with Java or C#, think of str as String and bytes as byte[]. If you're familiar with SQL, think of str as NVARCHAR and bytes as BINARY or BLOB. If you're familiar with the Windows registry, think of str as REG_SZ and bytes as REG_BINARY. If you're familiar with C(++), then forget everything you've learned about char and strings, because A CHARACTER IS NOT A BYTE. That idea is long obsolete.
You use str when you want to represent text.
print('ש××× ×¢×××')
You use bytes when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str to a bytes object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes into a str.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'â¬'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...' notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
In Python 2.x
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode = u'...' literals = sequence of Unicode characters = 3.x str
str = '...' literals = sequences of confounded bytes/characters
Usually text, encoded in some unspecified encoding.
But also used to represent binary data like struct.pack output.
In order to ease the 2.x-to-3.x transition, the b'...' literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes in 3.x) from text strings (which should be str in 3.x). The b prefix does nothing in 2.x, but tells the 2to3 script not to convert it to a Unicode string in 3.x.
So yes, b'...' literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there
more symbols than the b and u that do
other things?
The r prefix creates a raw string (e.g., r'\t' is a backslash + t instead of a tab), and triple quotes '''...''' or """...""" allow multi-line string literals.
</s> |
<s>[INST] add one row in a pandas.DataFrame I understand that pandas is designed to load fully populated DataFrame but I need to create an empty DataFrame then add rows, one by one.
What is the best way to do this ?
I successfully created an empty DataFrame with :
res = DataFrame(columns=('lib', 'qty1', 'qty2'))
Then I can add a new row and fill a field with :
res = res.set_value(len(res), 'qty1', 10.0)
It works but seems very odd :-/ (it fails for adding string value)
How can I add a new row to my DataFrame (with different columns type) ?
[/INST] You could use pandas.concat() or DataFrame.append(). For details and examples, see Merge, join, and concatenate.
</s> |
<s>[INST] overloading __init__ in python Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at __class__?
Is there some trick I might be missing?
I'm used to C++ where overloading by argument type is easy.
Thanks.
[/INST] A much neater way to get 'alternate constructors' is to use classmethods. For instance:
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.
</s> |
<s>[INST] python ImportError No module named I am very new at Python and I am getting this error:
Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
Python is installed in a local directory:
My directory tree is like this:
(local directory)/site-packages/toolkit/interface.py
My code is in here
(local directory)/site-packages/toolkit/examples/mountain.py
To run the example I do python mountain.py, and in the code I have:
from toolkit.interface import interface
And i get the error that I wrote, I have already checked sys.path and there I have the directory /site-packages, also I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.
I do not know why Python cannot find the file when it is in sys.path, any ideas? Can be a permissions problem? Do I need execution permission?
[/INST] Based on your comments to orip's post, I guess this is what happened:
You edited __init__.py on windows.
The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
You used WinSCP to copy the file to your unix box.
WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."
The missing __init__.py (now called __init__.py.bin) means python doesn't understand toolkit as a package.
You create __init__.py in the appropriate directory and everything works... ?
</s> |
<s>[INST] How to delete a character from a string using python? There is a string, for example EXAMPLE
How can I remove the middle character i.e. M from it. I don't need the code, what I want to know is
Do strings in python end in any special character?
Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
[/INST] In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:
newstr = oldstr.replace("M", "")
If you want to remove the central character:
midlen = len(oldstr)/2
newstr = oldstr[:midlen] + oldstr[midlen+1:]
You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0, can appear in a string.
</s> |
<s>[INST] What's the difference between raw_input() and input() in python3.x? What is the difference between raw_input() and input() in python3.x ?
[/INST] The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone (but can easily be simulated by using eval(input())).
</s> |
<s>[INST] How to fix python indentation I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tidy" but for python) without breaking the code?
[/INST] Use the reindent.py script that you find in the Tools/scripts/ directory of your Python installation:
Change Python (.py) files to use
4-space indents and no hard tab
characters. Also trim excess spaces
and tabs from ends of lines, and
remove empty lines at the end of
files. Also ensure the last line ends
with a newline.
Have a look at that script for detailed usage instructions.
</s> |
<s>[INST] How do you create a daemon in Python? Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion underneath.
However, another code sample, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.
These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?
[/INST] There are many fiddly things to take care of when becoming a well-behaved daemon process:
prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)
behave correctly inside a chroot gaol
set UID, GID, working directory, umask, and other process parameters appropriately for the use case
relinquish elevated suid, sgid privileges
close all open file descriptors, with exclusions depending on the use case
behave correctly if started inside an already-detached context, such as init, inetd, etc.
set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case
redirect the standard streams stdin, stdout, stderr since a daemon process no longer has a controlling terminal
handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave
allow proper cleanup when the process is terminated
actually become a daemon process without leading to zombies
Some of these are standard, as described in canonical Unix literature (Advanced Programming in the UNIX Environment, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and PID file handling, are conventional behaviour most daemon users would expect but that are less standardised.
All of these are covered by the PEP 3143 âStandard daemon process libraryâ specification. The python-daemon reference implementation works on Python 2.7 or later, and Python 3.2 or later.
</s> |
<s>[INST] Wrapping a C library in Python: C, Cython or ctypes? I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing.
Use Cython to expose the relevant parts from the C library to Python.
Do the whole thing in Python, using ctypes to communicate with the external library.
I'm not sure whether 2) or 3) is the better choice. The advantage of 3) is that ctypes is part of the standard library, and the resulting code would be pure Python – although I'm not sure how big that advantage actually is.
Are there more advantages / disadvantages with either choice? Which approach do you recommend?
Edit: Thanks for all your answers, they provide a good resource for anyone looking to do something similar. The decision, of course, is still to be made for the single case—there's no one "This is the right thing" sort of answer. For my own case, I'll probably go with ctypes, but I'm also looking forward to trying out Cython in some other project.
With there being no single true answer, accepting one is somewhat arbitrary; I chose FogleBird's answer as it provides some good insight into ctypes and it currently also is the highest-voted answer. However, I suggest to read all the answers to get a good overview.
Thanks again.
[/INST] Warning: a Cython core developer's opinion ahead.
I almost always recommend Cython over ctypes. The reason is that it has a much smoother upgrade path. If you use ctypes, many things will be simple at first, and it's certainly cool to write your FFI code in plain Python, without compilation, build dependencies and all that. However, at some point, you will almost certainly find that you have to call into your C library a lot, either in a loop or in a longer series of interdependent calls, and you would like to speed that up. That's the point where you'll notice that you can't do that with ctypes. Or, when you need callback functions and you find that your Python callback code becomes a bottleneck, you'd like to speed it up and/or move it down into C as well. Again, you cannot do that with ctypes. So you have to switch languages at that point and start rewriting parts of your code, potentially reverse engineering your Python/ctypes code into plain C, thus spoiling the whole benefit of writing your code in plain Python in the first place.
With Cython, OTOH, you're completely free to make the wrapping and calling code as thin or thick as you want. You can start with simple calls into your C code from regular Python code, and Cython will translate them into native C calls, without any additional calling overhead, and with an extremely low conversion overhead for Python parameters. When you notice that you need even more performance at some point where you are making too many expensive calls into your C library, you can start annotating your surrounding Python code with static types and let Cython optimise it straight down into C for you. Or, you can start rewriting parts of your C code in Cython in order to avoid calls and to specialise and tighten your loops algorithmically. And if you need a fast callback, just write a function with the appropriate signature and pass it into the C callback registry directly. Again, no overhead, and it gives you plain C calling performance. And in the much less likely case that you really cannot get your code fast enough in Cython, you can still consider rewriting the truly critical parts of it in C (or C++ or Fortran) and call it from your Cython code naturally and natively. But then, this really becomes the last resort instead of the only option.
So, ctypes is nice to do simple things and to quickly get something running. However, as soon as things start to grow, you'll most likely come to the point where you notice that you'd better used Cython right from the start.
</s> |
<s>[INST] Get exception description and stack trace which caused an exception, all as a string I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.
I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a string its full description and the stack trace that caused the error (simply all we use to see on the console). I need this string to print it to a text box in the GUI.
Something like this:
try:
method_that_can_raise_an_exception(params)
except Exception, e:
print_to_textbox(complete_exception_description(e))
The problem is: what is the function complete_exception_description?
[/INST] See the traceback module, specifically the format_exc() function. Here.
import traceback
try:
raise ValueError
except:
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
</s> |
<s>[INST] Python int to binary? Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.
[/INST] Python's string format method can take a format spec.
>>> "{0:b}".format(10)
'1010'
Format spec docs for Python 2
Format spec docs for Python 3
</s> |
<s>[INST] Is it possible to break a long line to multiple lines in Python Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible?
[/INST] From PEP 8 - Style Guide for Python Code:
The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. If necessary, you
can add an extra pair of parentheses around an expression, but sometimes
using a backslash looks better. Make sure to indent the continued line
appropriately. The preferred place to break around a binary operator is
after the operator, not before it.
Example of implicit line continuation:
a = some_function(
'1' + '2' + '3' + '4')
Example of explicit line continuation:
a = '1' + '2' + \
'3' + '4'
</s> |
<s>[INST] Why does python use 'else' after for and while loops? I understand how this construct works:
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
But I don't understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for statement to the else block. To me, continue or continuewith would make more sense (and I'm trying to train myself to read it as such).
I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?
[/INST] A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.
For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.
Using the Python for...else construct you have
...
for i in mylist:
if i == theflag:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.)
...
Compare this to a method that does not use this syntactic sugar:
...
flagfound = False
for i in mylist:
if i == theflag:
flagfound = True
break
process(i)
if not flagfound:
raise ValueError("List argument missing terminal flag.")
...
In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.
</s> |
<s>[INST] Why use argparse rather than optparse? I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to getopt and optparse we now have argparse.
Why has yet another command-line parsing module been created? Why should I use it instead of optparse? Are there new features that I should know about?
[/INST] As of 2.7, optparse is deprecated, and will hopefully go away in the future.
argparse is better for all the reasons listed on its original page (http://code.google.com/p/argparse/):
handling positional arguments
supporting sub-commands
allowing alternative option prefixes like + and /
handling zero-or-more and one-or-more style arguments
producing more informative usage messages
providing a much simpler interface for custom types and actions
More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.
</s> |
<s>[INST] python: how to import the class within the same directory or sub directory I have a directory that stores all the .py files.
bin/
main.py
user.py # where class User resides
dir.py # where class Dir resides
I want to use classes from user.py and dir.py in main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class User if user.py is in a sub directory?
bin/
dir.py
main.py
usr/
user.py
[/INST] Python 2
Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".
Then just do...
from user import User
from dir import Dir
The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.
bin/
main.py
classes/
user.py
dir.py
So if the directory was named "classes", then you'd do this:
from classes.user import User
from classes.dir import Dir
Python 3
Same as previous, but prefix the module name with a . if not using a subdirectory:
from .user import User
from .dir import Dir
</s> |
<s>[INST] How can I check the syntax of Python script without executing it? I used to use perl -c programfile to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python script?
[/INST] You can check the syntax by compiling it:
python -m py_compile script.py
</s> |
<s>[INST] Python in Xcode 7 How does one create a Python friendly environment in Xcode 7?
[/INST] I figured it out! The steps make it look like it will take more effort than it actually does.
These instructions are for creating a project from scratch. If you have existing Python scripts that you wish to include in this project, you will obviously need to slightly deviate from these instructions.
If you find that these instructions no longer work or are unclear due to changes in Xcode updates, please let me know. I will make the necessary corrections.
Open Xcode. The instructions for either are the same.
In the menu bar, click âFileâ â âNewâ â âNew Projectâ¦â.
Select âOtherâ in the left pane, then "External Build System" in the right page, and next click "Next".
Enter the product name, organization name, or organization identifier.
For the âBuild Toolâ field, type in /usr/local/bin/python3 for Python 3 or /usr/bin/python for Python 2 and then click âNextâ. Note that this assumes you have the symbolic link (that is setup by default) that resolves to the Python executable. If you are unsure as to where your Python executables are, enter either of these commands into Terminal: which python3 and which python.
Click âNextâ.
Choose where to save it and click âCreateâ.
In the menu bar, click âFileâ â âNewâ â âNew Fileâ¦â.
Select âOtherâ under âOS Xâ.
Select âEmptyâ and click âNextâ.
Navigate to the project folder (it will not work, otherwise), enter the name of the Python file (including the â.pyâ extension), and click âCreateâ.
In the menu bar, click âProductâ â âSchemeâ â âEdit Schemeâ¦â.
Click âRunâ in the left pane.
In the âInfoâ tab, click the âExecutableâ field and then click âOtherâ¦â.
Navigate to the executable from Step 6. You may need to use â§âG to type in the directory if it is hidden.
Select the executable and click "Choose".
Uncheck âDebug executableâ. If you skip this step, Xcode will try to debug the Python executable itself. I am unaware of a way to integrate an external debugging tool into Xcode.
Click the â+â icon under âArguments Passed On Launchâ. You might have to expand that section by clicking on the triangle pointing to the right.
Type in $(SRCROOT)/ (or $(SOURCE_ROOT)/) and then the name of the Python file you want to test. Remember, the Python program must be in the project folder. Otherwise, you will have to type out the full path (or relative path if it's in a subfolder of the project folder) here. If there are spaces anywhere in the full path, you must include quotation marks at the beginning and end of this.
Click âCloseâ.
Note that if you open the "Utilities" panel, with the "Show the File inspector" tab active, the file type is automatically set to "Default - Python script". Feel free to look through all the file type options it has, to gain an idea as to what all it is capable of doing. The method above can be applied to any interpreted language. As of right now, I have yet to figure out exactly how to get it to work with Java; then again, I haven't done too much research. Surely there is some documentation floating around on the web about all of this.
Running without administrative privileges:
If you do not have administrative privileges or are not in the Developer group, you can still use Xcode for Python programming (but you still won't be able to develop in languages that require compiling). Instead of using the play button, in the menu bar, click "Product" â "Perform Action" â "Run Without Building" or simply use the keyboard shortcut ^âR.
Other Notes:
To change the text encoding, line endings, and/or indentation settings, open the "Utilities" panel and click "Show the File inspector" tab active. There, you will find these settings.
For more information about Xcode's build settings, there is no better source than this. I'd be interested in hearing from somebody who got this to work with unsupported compiled languages. This process should work for any other interpreted language. Just be sure to change Step 6 and Step 16 accordingly.
</s> |
<s>[INST] Test if executable exists in Python? In Python, is there a portable and simple way to test if an executable program exists?
By simple I mean something like the which command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen & al and see if it fails (that's what I'm doing now, but imagine it's launchmissiles)
[/INST] Easiest way I can think of:
def which(program):
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
Edit: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.
Edit: Updated to use os.path.isfile() instead of os.path.exists() per comments.
</s> |
<s>[INST] How would you make a comma-separated string from a list? What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, [ 'a', 'b', 'c' ] to 'a,b,c'? (The cases [ s ] and [] should be mapped to s and '', respectively.)
I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.
Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised s.join([e1,e2,...]) as a shorthand for s+e1+e2+....)
[/INST] myList = ['a','b','c','d']
myString = ",".join(myList )
This won't work if the list contains numbers.
As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do:
myList = ','.join(map(str, myList))
</s> |
<s>[INST] TypeError: 'module' object is not callable File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__
self.serv = socket(AF_INET,SOCK_STREAM)
TypeError: 'module' object is not callable
Why am I getting this error?
I'm confused.
What do you need to know to answer my question?
[/INST] socket is a module, containing the class socket.
You need to do socket.socket(...) or from socket import socket:
>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>
Notice that the error here is pretty easy to understand: if module object is not callable, you are probably calling a module object! What's a module object? It's the type of thing you get when you import a module.
But even if you don't understand that (which is fine, it's often confusing that classes, modules, functions etc are all just objects like everything else), there's a pretty easy way to start debugging:
"Hmm, module object is not callable. That sounds like I'm trying to call something that you can't call. I wonder what I'm trying to call?"
"Oh, I'm calling socket. That should be callable! I wonder if the variable socket is what I think it is?`
print socket
</s> |
<s>[INST] Python thread pool similar to the multiprocessing Pool? Is there a Pool class for worker threads, similar to the multiprocessing module's Pool class?
I like for example the easy way to parallelize a map function
def long_running_func(p):
c_func_no_gil(p)
p = multiprocessing.Pool(4)
xs = p.map(long_running_func, range(100))
however I would like to do it without the overhead of creating new processes.
I know about the GIL. However, in my usecase, the function will be an IO-bound C function for which the python wrapper will release the GIL before the actual function call.
Do I have to write my own threading pool?
[/INST] I just found out that there actually is a thread-based Pool interface in the multiprocessing module, however it is hidden somewhat and not properly documented.
It can be imported via
from multiprocessing.pool import ThreadPool
It is implemented using a dummy Process class wrapping a python thread. This thread-based Process class can be found in multiprocessing.dummy which is mentioned briefly in the docs. This dummy module supposedly provides the whole multiprocessing interface based on threads.
</s> |
<s>[INST] Python: import a file from a subdirectory I have a file called tester.py, located on /project.
/project has a subdirectory called lib, with a file called BoxTime.py:
/project/tester.py
/project/lib/BoxTime.py
I want to import BoxTime from tester. I have tried this:
import lib.BoxTime
Which resulted:
Traceback (most recent call last):
File "./tester.py", line 3, in <module>
import lib.BoxTime
ImportError: No module named lib.BoxTime
Any ideas how to import BoxTime from the subdirectory?
EDIT
The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:
import lib.BoxTime as BT
...
BT.bt_function()
[/INST] Take a look at the Packages documentation (Section 6.4) here: http://docs.python.org/tutorial/modules.html
In short, you need to put a blank file named
__init__.py
in the "lib" directory.
</s> |
<s>[INST] Can a variable number of arguments be passed to a function? In a similar way to using varargs in C or C++:
fn(a, b)
fn(a, b, c, d, ...)
[/INST] Yes.
This is simple and works if you disregard keyword arguments:
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2,3)
I was called with 3 arguments: (1, 2, 3)
As you can see, Python will give you a single tuple with all the arguments.
For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.
</s> |
Subsets and Splits