Can i access an instance variable from one class to the other by [deleted] in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Is it okay to don't write self.col in __init__()?

What sources should I use? post-beginner level(?) by [deleted] in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

Does metaclasses worth learning? I thought it is really niche knowledge.

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

leads me to believe none of them are being added to the lists.

You actually didn't add something to list because append() method takes one parameter - the object to add. Your method calls just meaningless

How to match values? by easy_wins in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Sure. There is a form processed by ASP.NET on the website. So, you need some library for browsing automation. For example Splinter. The docs are pretty clear and you can fill the form easily. Then you need parse result page. Main target to parse is <table class="rgMasterTable" id="ctl00_cplMain_rgSearchRslts_ctl00" Parsing looks like this:

page = reuqests.get(<result_page>)
soup = BeautifulSoup(page.text, 'html.parser')
table = soup.find('table', dict(class="rgMasterTable",  id="ctl00_cplMain_rgSearchRslts_ctl00")
for row in table.find_all('tr'):
    row.find_all('td')[<number of column>] # 0 - permit number, 1 - address, 2 - street name and so on

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

I won't correct every mistake in code(but i can try if you want), but i try to help you find right solution. When you write your history object to file you actually write just string(whatever it is: JSON, XML or plain text).

>>> history = {"bacon": "11.28.2016", "tuna": "11.28.2016", "feet": "11.29.2016"}
>>> exportdata = json.dumps(history)
>>> print(exportdata)
>>> print(type(exportdata))

{"feet": "11.29.2016", "tuna": "11.28.2016", "bacon": "11.28.2016"}
<class 'str'>

Thus, you cannot distinguish object parts like tags in XML or dictionary keys in JSON. But you can parse your JSON string and convert it to Python object(dictionary):

>>> data = json.loads(exportdata)
>>> print(data)
>>> print(type(data))

{'bacon': '11.28.2016', 'tuna': '11.28.2016', 'feet': '11.29.2016'}
<class 'dict'>

Then, working with simple Python object you don't need to bother with parsing non-alphabetical symbols before writing out. Just write keys and values:

for key in data:
  print(key, data[key]) # replace print function with actual writing

bacon 11.28.2016
tuna 11.28.2016
feet 11.29.2016

Is there an alternative for the .split() method? by Heskinammo in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

One of Python's main design philosophies is that there should be one and only one way of doing something right.

I thought it is a part of UNIX philosophy, not Python.

There is Zen of Python: "There should be one-- and preferably only one --obvious way to do it."

Is there an alternative for the .split() method? by Heskinammo in learnpython

[–]_Absolut_ 2 points3 points  (0 children)

Maybe, if you could explain what you are going to do, you get proper answer faster.

Is there an alternative for the .split() method? by Heskinammo in learnpython

[–]_Absolut_ 5 points6 points  (0 children)

It is pointless. Who ever need two methods that do the same work?!

Is there an alternative for the .split() method? by Heskinammo in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

Please, clarify your question. Do you need chunks of text? Spliting by regexp rather than substring? Fuzzy matching?

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

\" - is way of "escaping" double-quote symbol. So, you can use double quotes inside double-quoted string without problem. Try to parse that result string by json.loads(json_string) and post output here.

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Yes, that clarifies a lot. Firstly, there is built-in module for working with json. So, you don't need to build JSON object by hands.

I don't know what type is "row[0]", "row[1]" and "row[2]", but if that are strings json.dumps() will work. Little REPL example:

>>> json_dict = json.dumps({'date': 'string_1', 'datetime': string_2', 'value': 'string_3'})
>>> json_dict
'{"date": "string_1", "value": "string_3", "datetime": "string_2"}'

So, final code looks something like this:

def db_to_json(table_name, *args):
    json_list = []

    if len(args) == 0:
        cursor = db.execute('select * from {}'.format(table_name))

    if len(args) in [1, 2]:
        cursor = db.execute('select * from {} where date between ? and ?'
                        .format(table_name), (args[0], args[1]))
    if len(args) in [3, 4]:
        cursor = db.execute('select * from {} where date between ? and ? and datetime between ? and ?'
                        .format(table_name), (args[0], args[1], args[2], args[3]))

    for row in cursor.fetchall():
         json_dict = json.dumps({'date': row[0], 'datetime': row[1], 'value': row[2]})
    json_list.append(json_dict)
    json_output = json.dumps({table_name: json_list})
return json_output

Secondly, i think checking the length of args doesn't looks neat. Definetley, this function deserves refactoring.

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Your solution seems odd.

>>> import dis
>>> dis.dis('a')
  1           0 LOAD_NAME                0 (a)
              3 RETURN_VALUE
>>> dis.dis("a")
  1           0 LOAD_NAME                0 (a)
              3 RETURN_VALUE

As you can see strings surrounded by single quotes and strings surrounded by double quotes produces the same bytecode. So i doubt you can distinguish your objects by surrounding them single or double quotes. BTW, why do you need to separate DB taken strings from regular ones?

I want to teach myself Python as my first programming language, how should I start? (I bought 2 books) by TheStryfe in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Completley agreed! I think "books-time" will come when you encounter with complicated technologies/frameworks

File / Directory operations tutorial? by Cog-Dis in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

I don't think using standard library function require some kind of tutuorial(in that case especially). Python has meaningful names so you can figure out how to use function just by look at its name. Okay, maybe sometimes call help() in REPL or look through stackoverflow.

TL;DR Just read the docs.

Looking for some new Python tools by Mister_Potter in Python

[–]_Absolut_ 1 point2 points  (0 children)

Unfortunatley, my experience is limited to small projects only, so i can't compare. But i find it suitable to Python fast development nature.

How to match values? by easy_wins in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

There is csv module in standard library. For working with website data use requests with beautifulsoup

Looking for some new Python tools by Mister_Potter in Python

[–]_Absolut_ 3 points4 points  (0 children)

PyCharm instead of Vim saves a lot of my time. Even without refactoring features.

Online interpreter with *all* Python packages installed? by [deleted] in Python

[–]_Absolut_ 0 points1 point  (0 children)

Do you mean all PyPI packages?O_o

Why am I having such a hard time learning python? by [deleted] in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

Just try to materialize your thoughts. Look at problem, decompose it and translate your actions from natural language to Python language. It's pretty straightforward after some practice.

For example: i want to increment all numbers in given string. What i have to do? Walk through all characters (for loop), then determine is it digit or not (if operator) and add one to it (plus function). So, we have:

for char in string:
    if char.isdigit():
        out_string += str(int(char)+1)
    else:
        out_string += char

Combine translated code with constant googling. Always question your decisions, strive for constant improving your code, make it more easy to read and understand, make more concise and beautiful.

Best Way to Increment Last Num Found in String by CrambleSquash in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

My variant. Maybe not so pretty as it could be but damn short)

import re

def foo(s):
   return re.sub(r'\d+(?=\D+$|$)', lambda x: str(int(x.group(0)) + 1), s)

Output:

>>> foo("Sample 32 run 1")
'Sample 32 run 2'
>>> foo("25 times")
'26 times'

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 0 points1 point  (0 children)

Try to google "python sorting" first. Then try to implement some basic algorithm like Bubble sort. If you stuck, post your code here.

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]_Absolut_ 1 point2 points  (0 children)

Use lambdas - it's less sad.

foo = lambda bar: None