EzDevInfo.com

python

Chef cookbook to install Python and related tools python Cookbook - Chef Supermarket python cookbook (1.4.6) centos, fedora, freebsd, debian, ubuntu, redhat, smartos

Does Python have a ternary conditional operator?

If not, is it possible to simulate one concisely using other language constructs?


Source: (StackOverflow)

Python - append vs. extend

What's the difference between the list methods append() and extend()?


Source: (StackOverflow)

Advertisements

Sort a Python dictionary by value

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.


Source: (StackOverflow)

What is a metaclass in Python?

What are metaclasses? What do you use them for?


Source: (StackOverflow)

Check whether a file exists using Python

How do I check whether a file exists, using Python, without using a try statement?


Source: (StackOverflow)

Calling an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?


Source: (StackOverflow)

How can I make a chain of function decorators in Python?

How can I make two decorators in Python that would do the following?

@makebold
@makeitalic
def say():
   return "Hello"

which should return

<b><i>Hello</i></b>

I'm not trying to make HTML this way in a real application, just trying to understand how decorators and decorator chaining works.


Source: (StackOverflow)

How can I merge two Python dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)


Source: (StackOverflow)

What does the yield keyword do in Python?

What is the use of the yield keyword in Python? What does it do?

For example, I'm trying to understand this code1:

def node._get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild  

And this is the caller:

result, candidates = list(), [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

What happens when the method _get_child_candidates is called? A list is returned? A single element is returned? Is it called again? When will subsequent calls stop?


1. The code comes from Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: Module mspace.


Source: (StackOverflow)

In Python, check if a directory exists and create it if necessary

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

filename = "/my/directory/filename.txt"
dir = os.path.dirname(filename)

try:
    os.stat(dir)
except:
    os.mkdir(dir)       

f = file(filename)

Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now:

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

Is there a flag for "open", that makes this happen automatically?


Source: (StackOverflow)

What is the difference between @staticmethod and @classmethod in Python?

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?


Source: (StackOverflow)

Best way to check if a list is empty

For example, if passed the following:

a = []

How do I check to see if a is empty?


Source: (StackOverflow)

Is there a way to run Python on Android?

We are working on an S60 version and this platform has a nice Python API.

However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together?


Source: (StackOverflow)

How do I pass a variable by reference?

The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.Change(self.variable)
        print self.variable

    def Change(self, var):
        var = 'Changed'

Is there something I can do to pass the variable by actual reference?


Source: (StackOverflow)

What IDE to use for Python?

What IDEs ("GUIs/editors") do others use for Python coding?


Source: (StackOverflow)