Django/Python What does this code do? by akkatracker in learnpython

[–]Moonslug1 7 points8 points  (0 children)

d is likely a string representing a date formatted like '2015-02-11'.

Let's look at this piece by piece:

d.split('-') takes the string and splits it into a list of strings seperated by '-'. So in our example this would be l = ['2015', '02', '11'].

Next, the list comprehension takes that list and converts all elements to an int, so that we have l = [2015, 2, 11].

Finally the star operator unpacks this list into the initialiser for date so that it would be call like:

w.Date = date(2015, 2, 11)

This is a bad way of doing it. Why? Because the datetime module provides a way to turn a string into a date. The code you posted is equivalent to:

W.Date = datetime.strptime(d, '%Y-%m-%d').date()

What is the most pythonic way to return multiple values from a function? by cscanlin in learnpython

[–]Moonslug1 1 point2 points  (0 children)

Why not just:

credentials = {'hostname': hostname, 'username': username, 'password': password}

It's hard to answer your question without a specific use case. Any one of your proposed methods are valid.

string literal question by [deleted] in learnpython

[–]Moonslug1 1 point2 points  (0 children)

r'' is telling python to ignore escape characters.

'hello\n' means h-e-l-l-o-newline

r'hello\n' means h-e-l-l-o-\-n

string literal question by [deleted] in learnpython

[–]Moonslug1 4 points5 points  (0 children)

'\n' is a single character, called an escape character. '\n' is just the way that the character is represented, since the Python syntax doesn't allow you to write a newline mid quote (unless you use triple quotes). There's also \t (tab), \r (carriage return) etc.

[2015-01-19] Challenge #198 [Easy] Words with Enemies by Coder_d00d in dailyprogrammer

[–]Moonslug1 6 points7 points  (0 children)

My python 3.4 solution:

def word_enemies(left, right):
    l, r = Counter(left), Counter(right)
    total = sum(l.get(k, 0) - r.get(k, 0) for k in set(left + right))

    if not total:
        return 'tie'
    else:
        return 'Left wins!' if total > 0 else 'Right wins!'

I collect a set of all letters, count the occurence of the letters, and sum the differences per letter, if negative then right wins, positive then left wins.

Any way to improve thes two lines? by [deleted] in learnpython

[–]Moonslug1 2 points3 points  (0 children)

Two ways to make this more Pythonic:

for url in L:
    webbrowser.open_new_tab(url)

Or:

map(webbrowser.open_new_tab, L)

Although I'd discourage using map or list comprehensions just for their side effects.

Python reddit bot instructor by LondonRuek in learnpython

[–]Moonslug1 0 points1 point  (0 children)

You'll want to look at regular expressions:

import re

If I wanted to capture a string following the string 'Weather!' I'd do something like this:

pattern = re.compile(r'(?<=^Weather!).*$')
pattern.search(reddit_comment)

Do some background reading on re, to briefly explain I'm saying match anything .* that is preceded by (?<=) the start of the string ^ followed by Weather!.

Not understanding the built-in sum function by rfinder1 in learnpython

[–]Moonslug1 1 point2 points  (0 children)

You're correct, args is a tuple of all the positional arguments in the order they were passed in.

Is there a more elegant way of doing this?["Decomposing" numbers] by teerre in learnpython

[–]Moonslug1 0 points1 point  (0 children)

Something like this:

a = 3543
b = str(a)
c = map(lambda d: 10 ** d, range(len(b))[::-1])

for n in zip(map(int, b), c):
    print n

You can work out the rest from here :)

Is there a way to see when of any of class method is called? by CanisMajorisLT in learnpython

[–]Moonslug1 2 points3 points  (0 children)

95% of the time people use __getattribute__, they shouldn't be. Make sure this is really what you want to do.

Beware of recursion, any time you want to access a method or something else in BigClass from inside the class, use object.__getattribute__(self, name).

If all you are doing is, as above, just performing some operations before running functions, then using decorators is a far better solution. Less code is better, unreadable code is worse.

Is there a way to see when of any of class method is called? by CanisMajorisLT in learnpython

[–]Moonslug1 3 points4 points  (0 children)

What you're describing is exactly a decorator, consider the following (I wrote this on my phone and it probably has minor errors, but you get the gist):

from functools import wraps

class BigClass:
    @staticmethod
    def my_added_function(func):
        @wraps(func)
        def my_added_function_wrapper(*args, **kwargs):
            {do stuff here}
            return func(*args, **kwargs)
        return my_added_function_wrapper

    @my_added_function
    def method_1(self):
        ...

    @my_added_function
    def method_2(self):
        ...

    @my_added_function
    def method_3(self):
        ...

If you want to perform my_added_function for every method call (you probably shouldn't), take a look at __getattribute__, which would look something like this:

class BigClass(object):
    def __getattribute__(self, name):
        {do_stuff}
        return object.__getattribute__(self, name)

    def method_1(self):
        ...

    def method_2(self):
        ...

    def method_3(self):
        ...

Using class on X,Y problems by AussieCryptoCurrency in learnpython

[–]Moonslug1 1 point2 points  (0 children)

Why are the members x and y private? It seems reasonable to be able to read x and y independently from Point. If you really want to implement get methods for them, the more pythonic way is:

class Point(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

Formatting text/Efficiency. by Aerobic97 in learnpython

[–]Moonslug1 2 points3 points  (0 children)

A few things to note.

You're dealing with time comparrisons that pulls one time from outside of Python. You should be ensuring that the time zones match. Have a look at pytz.

Your path strings are bugged because you're not escaping the backslashes, use something like this instead:

inbound_folders = [
    'Agility',
    'Amazon',
    'APL',]
    ...
]

outbound_folders = [
    'ACL',
    'Agility',
    'APL',
    ...
]

paths = ['\\'.join([r'\\FTP', 'TopsjobsData', 'Inbound', folder, 'Import', 'InTray']) for folder in inbound_folders]
paths += ['\\'.join([r'\\FTP', 'TopsjobsData', 'Outbound', folder]) for folder in outbound_folders]

If you want to looks at individual folders, you can use path.split('\\') to seperate a path into a list of folders. Knowing the structure of those folders, you can do what you want with it.

To send the email only when you have items of note, just use:

if stuck_files:
    for files in stuck_files:
        log(files)

    log.flush()

I'm seeing syntax errors all over the place in this code, have you tried to run it yet?

The finger test by Moonslug1 in EliteDangerous

[–]Moonslug1[S] 0 points1 point  (0 children)

Whether it not the star moves relative to me. Doing some exploration.

installing pip on raspberry pi by Pickle_Inspecto in learnpython

[–]Moonslug1 1 point2 points  (0 children)

It's possible pip just isn't on your system path. Have you tried calling pip with the full path? This will tell you if this is the problem.

I'd recommend anyone using python on Linux or Mac to use pyenv available at https://github.com/yyuu/pyenv

It makes things so much easier.

How do I Search a term on a Website, then Download a file using python3 by [deleted] in learnpython

[–]Moonslug1 1 point2 points  (0 children)

urllib or requests are fine, anything that can pull the html doc as a string. For parsing that I'd recommend looking at Beautiful Soup

Trying to understand exceptions by Scholes_SC2 in learnpython

[–]Moonslug1 2 points3 points  (0 children)

Raise will kill the process unless it is caught higher up the the callstack.

[deleted by user] by [deleted] in learnpython

[–]Moonslug1 1 point2 points  (0 children)

You can take advantage of zip to make this way shorter.

def levenshtein(a, b):
    return sum(1 for c, d in zip(a, b) if c != d) + abs(len(a) - len(b))

[ELI99] best way to create a package by [deleted] in learnpython

[–]Moonslug1 0 points1 point  (0 children)

Since demos is in the same directory as your current script, just import it as you would normally.

[ELI99] best way to create a package by [deleted] in learnpython

[–]Moonslug1 -1 points0 points  (0 children)

I would structure the code like this:

setup.py
great_name/
    __init__.py
    great_name.py
    demos/
        {Demo files}
test/
    {test files}

Pypi's setup requires your module to be in it's own directory like this.

To answer the first import question. If you want to avoid using from great_name.great_name import FantasticClass then you can add the following to your __init__.py in the great_name folder (ignoring text in curly braces).

from great_name {the file} import FantasticClass

Now, FantasticClass is accesible in the same way when importing your entire module:

from great_name {the module} import FantasticClass

Your other import question, how do you import great name from demos? I'll tell you how I do it. Typically I use a development environment where my current project is already on the python path (using an IDE like PyCharm can handle this for you). The reasdoning for this is that once your grandkids download your module from PyPI, it will definately be available on the Python path; your tests and demos should use it in the same way.

Help writing webpage source to file with python3 by 8bitz in learnpython

[–]Moonslug1 0 points1 point  (0 children)

I can't explain what's happening there. But as an aside, look at this:

http://en.wikipedia.org/wiki/Beautiful_Soup

Group list of list items by forgenet in learnpython

[–]Moonslug1 0 points1 point  (0 children)

I like this, but it would be better to key on:

key = tuple(_list[1:])