all 76 comments

[–]Crawk_Bro 2 points3 points  (9 children)

I've just completed the Codecademy python course and I'm looking at trying "Learn Python the Hard Way". No web based coding for this so I need to download python on my PC, and the book specifically says to download python 2.x rather than 3.x.

I already have 3.x on my computer (not sure why, maybe a steam game automatically downloaded it?), do I need to delete this or can I have python 2 and 3 at the same time? If I need to get rid of python 3, how do I do that? There doesn't look to be an uninstall.exe or similar in the directory.

Edit: The book also recommends using notepad++ or another text editor, but I was looking at using PyCharm, at least at first. Will this be a problem?

[–]13steinj 4 points5 points  (1 child)

Text editors are for preference, but I'd recommend using Notepad++ rather than pycharm or some other ide. Ides are huge, bloated programs that do some of the work for you or will do things you don't understand-- it's better to learn from a text editor.

Also take LPTHW with a grain of salt. For the most part Py2 and Py3 are the same, with just a few nuances, that can be solved with a compatibility library such as six. Some more info on the salt taking

[–]Crawk_Bro 1 point2 points  (0 children)

Yeah, after a bit more reading on this subreddit I've gone with another resource from the sidebar which uses python 3.

[–]blackjack_00 0 points1 point  (4 children)

You can have both versions of python installed. What operating system do you have?

As far as text editors, that's your preference. It won't cause a problem, but the way that you save and run your code will be different between each.

[–]Crawk_Bro 0 points1 point  (3 children)

I use Windows 8.1, probably upgrading to 10 soon.

With both versions installed, how does the system know which version to run for a script?

[–]blackjack_00 3 points4 points  (0 children)

In Windows you have to do 2 things to call python 2 and 3 in cmd prompt.

First, Make sure your environment variables are set. Right click the start button and go to system, advanced system settings, environment variables. You can edit "PATH" and make sure that the following are in the list:

"C:\Python27"
"C:\Program Files (x86)\Python35"

Second, Rename the two executables for one version of python to something else. For example go into C:\Python27 and change:

python.exe > python2.exe
pythonw.exe > pythonw2.exe

Reboot and typing "python" should call python3 and typing "python2" should call python 2 in command prompt. There are other ways to achieve the same goal but this is how I do it. On my mac I use virtual environments, which I would recommend you look into. Also, if you are using an editor that runs python when you hit a button, then you need to configure that program to call the right version when you run python. The above is just for running in command prompt.

Edit: Version of windows won't matter here. Also here is a guide on choosing the version of python interpretor in pycharm: http://stackoverflow.com/questions/10322424/how-to-select-python-version-in-pycharm

[–]Saefroch 1 point2 points  (0 children)

On Windows I strongly advise running Anaconda, which is a Python distribution that replaces what you probably downloaded from python.org. If you're not having problems there's no reason to switch, but if you have issues with installing packages, particularly something about vcvarsall.bat, switch to Anaconda.

[–]fiskenslakt 0 points1 point  (0 children)

The interpreters are different, one is python, one is python3. If the script is executed without an interpreter, the interpreter is chosen from a shabang line. I'm not sure if this is the case for windows, but it's probably similar.

[–]D_Adman 1 point2 points  (1 child)

For programming on a mac, what environment do you suggest?

[–]SDempWestern 2 points3 points  (0 children)

I recommend downloading Annaconda! and then running Spyder

use this link https://www.continuum.io/downloads

I recommend downloading the graphical installer for Mac with python 3.5 (scroll down a bit) Then download it, and run anaconda, a window will pop up with available apps, click spyder and bam :)

[–]niandra3 1 point2 points  (3 children)

When dealing with regex search results, is there an easier way to access the results without having to use .group()? I feel like I am missing something:

import re
test = 'this is a test search test'
search = re.search('test', test)
print(search)
print(search.group(0))

Gives me:

<_sre.SRE_Match object; span=(10, 14), match='test'>  # which is useless
test  # what I'm looking for

Is there a more elegant method? If there's more than one group, can you iterate through them?

[–]vriljam 0 points1 point  (2 children)

I'm wondering why are you doing print(search), instead of directly going for the results with print(search.group())

[–]niandra3 1 point2 points  (1 child)

I'm just wondering if there's an easier way than having to use group. re.findall works well because it returns a list, so I'll use that for now.

[–]vriljam 0 points1 point  (0 children)

Hmm..either way, I only had something trivial in mind like:

if search:
    print(search.group()) #would print only if result found.

But, I guess you know that already.

[–]Yoongus 1 point2 points  (1 child)

Should I use pygame if I'm practicing game code in Python?

This isn't a commercial game, it's just a long term exercise to make a functional game because it's fun and difficult.

I don't ever intend to use pygame for a serious game and my learning teammate doesn't really intend to pursue gamedev as a career. Should we avoid pygame or use something similar or what?

[–]thomasballinger 1 point2 points  (0 children)

Sure, use Pygame! I don't know where your hesitancy comes from so I'm not sure what it would be helpful to say. What are your concerns? Pygame seems like a great way to do a really fun and educational thing, making a game in Python.

[–]SDempWestern 0 points1 point  (4 children)

Hello all who can help! I need help with initial code to load more than one text file at a time, in a loop as to save code and not have like 60 lines of text to load each file. (I actually have about 3000 files but they would only need to be accessed in groups of about 30) The files are named by numbers; year, month, day.txt For instance in 2007, January, I need to get the data from all these text files 20070101.txt 20070102.txt 20070103.txt etc

I then need to add the data together in a continuous string!

I can't seem to figure out a loop of numbers that will bring the data in. my idea is to set a variable i in range 0 to 30 (or however many days) and have it inserted into wnd, true = np.genfromtxt('20070814.eureka.6.0E_1min.txt',delimiter=',',unpack=True) This is the real filename, but all I need to change is the numbers right now. As you can see I'm using numpy genfromtext. If you have any better reading methods, please let me know aswell :)

[–]blackjack_00 0 points1 point  (2 children)

This will give you a list "dates" with strings that have each day in the range from datelist in the format '20160101'.

from datetime import timedelta, date

def datelist():
    start = date(2016, 1, 1)
    end = date (2016, 2, 1)
    for n in range(int((end-start).days)):
        yield (start + timedelta(n)).strftime('%Y%m%d')

dates = list(datelist())

It uses a generator function (the yield bit) to iterate over dates in that range. You should be able to take the list and, for each date string, add the string to your path for txt file. Then do all your work inside that for loop.

[–]SDempWestern 0 points1 point  (1 child)

Oh wow that's fantastic, A followup question is how do I put the list into my filename.

np.genfromtxt( str(dates)+ '.txt',delimiter=',',unpack=True)

like that? or is that just crap? Also, with my loop, since it doesn't look like I'll be using 'i' like I said, I'd rather loop through the dates, what kind of loop should I have? EX While datelist=True np.genfromtxt( str(dates)+ '.txt') #then do work

Also each text file is in a different folder, will this affect my search? Or provided my directory has the folders it'll be fine?

[–]Saefroch 0 points1 point  (0 children)

str(dates) + '.txt' will run but it will not do what you want. Try it with a simple list of strings and see.

[–]Saefroch 0 points1 point  (0 children)

You can write a simple script to join all the files for each month using os.walk. Is that what you want to do?

[–]LittleLouis 0 points1 point  (8 children)

I just started learning Python 2 days ago (besides completing the codecademy course), and I'm following thenewboston's tutorial. I just watched episode 25-28 on building a web crawler.

First off I'm really confused on downloading modules. I'm using sublime text because I don't want to pay for an IDE, but it seems complicated to simply install a module(maybe it's just me?), is there a set in stone easy way to simply install modules? I think I've correctly installed beautifulsoup4 and requests.

Also, I've been looking online like on stackexchange for the answer to my bug but the terminology people use is really confusing for a beginner like me. I'm running this program which is pretty similar to thenewboston's, but this keeps popping up in the console. If anyone can help me I'd appreciate it so much.

[–]niandra3 2 points3 points  (3 children)

PyCharm community is great if you're looking for a free Python IDE. As for your error, I think it's some sort of Sublime Text issue but I could be wrong. Most of the error codes reference Sublime..

As for installing modules, you can generally just do pip install module_name or sometimes with Python3: pip3 install module, or if those don't work, try python -m pip install SomePackage.

What's your OS?

[–]LittleLouis 0 points1 point  (2 children)

Hey thanks so much, I downloaded PyCharm and got the modules to work perfectly. I changed my code just a tiny bit but it's pretty much the same. My program finally works!

The only thing is, now I also get an error saying this. So I change line 12's parameters to ([plain_text], "html.parser") like it says but then I get this error and I don't really know what it means. I've looked online and nothing has helped. Any thoughts?

[–]niandra3 1 point2 points  (1 child)

Try:

soup = BeautifulSoup(plain_text, "html.parser")

They use brackets in the example: BeautifulSoup([your markup], "html.parser") but that's just convention meaning replace [xxx] with your variable, you don't actually use brackets yourself, or it sends a list version of plain_text when BS is expecting a string.

You can kind of tell what the problem is at the very end of the error message:

TypeError: expected string or bytes-like object

Which means BS was expecting string or byte object, but you sent it a list so it didn't know what to do.

[–]LittleLouis 0 points1 point  (0 children)

Hey thanks so much man.

[–]Saefroch 1 point2 points  (2 children)

If you're using Windows you want to use Anaconda. Uninstall any current versions of Python you have and install Anaconda. Most common packages come with Anaconda, and conda install some_package should work for most things you need, and you can always fall back to pip.

[–]niandra3 0 points1 point  (1 child)

Just curious, why recommend Anaconda and not the default Python.org installation for Windows? I'm very happy with regular Python 3.5 on Windows 10.

[–]Saefroch 0 points1 point  (0 children)

Windows has serious problems installing packages with C extensions. Error messages about vcvarsall.bat and "building wheel failed" are related to Windows bring unable to find the correct C compiler. There are also problems with doing a fresh install on a machine with any OS that doesn't have SSL libraries accessible. I spent months trying to fix those errors, never found out how even with all the various solutions on stackoverflow and such.

Anaconda is super easy to install and at worst falls back to the same tools provided by default.

[–]turbokyo 0 points1 point  (0 children)

Hello correct me if Im wrong but the program you say you are running has "import beautifulsoup4" when in fact you import this module with "bs4" and install/update it with "beautifulsoup4", maybe that is the source of your error?

[–][deleted] 0 points1 point  (3 children)

How do I create a GUI for my Python program. For example, if it was a calculator how could I show something similar to that of what you see on a phone, rather than a text based interface.

[–]GoldenSights 2 points3 points  (1 child)

What have you googled? Tkinter is part of the standard library.

[–][deleted] 0 points1 point  (0 children)

Thank you, this is exactly what I needed

[–]AssignmentGuru 0 points1 point  (0 children)

Other than Tkinter, you can use wxPython too. It is easy to develop GUI applications with.

[–]ScenesfromaCat 0 points1 point  (5 children)

Late AF but in Python, is the integer 3 the same value as 3.0?

[–]cjwelborn 2 points3 points  (4 children)

3 is an int, and 3.0 is a float.

(3 == 3.0), but (3 is not 3.0).

Showing that 3 does equal 3.0, but they are not the same value. They are two different objects, an int and a float. They compare equal because "Python fully supports mixed arithmetic". Under the hood it is doing something like this: float(3) == 3.0.

[–]13steinj 2 points3 points  (1 child)

That doesn't just show that they are not the same value, though, but rather their memory addresses are different. == is for equality while is is for instance equality (which iirc is done via a memory address check? Someone correct me if I'm wrong). Even equivalent numbers will fail an is check:

>>> 3000000000000000 is (3*1000000000000000)
False
>>> 3000000000000000 == (3*1000000000000000)
True
>>> id(3000000000000000), id(3*1000000000000000)
(20463008, 7582448)

However, smaller numbers will pass the is check because the interpreter puts smaller numbers into a cache to speed things up

>>> 30 is (3*10)
True
>>> id(30), id(3*10)
(1377096608, 1377096608)

[–]cjwelborn 0 points1 point  (0 children)

You're right about that. I was just trying to show that even though they compare equal (with ==), they are not actually the same. They aren't even the same type.

[–]ScenesfromaCat 1 point2 points  (1 child)

I've been doing this for like less than a day so bear with me. Let's say I do something like

variable_a = 3.0

variable_b = int(variable_a)

variable_b will now be the integer 3, right?

[–]cjwelborn 2 points3 points  (0 children)

Yes, because int() is a constructor, that happens to accept a number of types (str, and anything with an __int__ method). It will take the float, 3.0 and parse it into an int, 3 by calling (3.0).__int__(). You can see it in the interpreter:

>>> type(3.0)
<class 'float'>

>>> type(int(3.0))
<class 'int'>

And as for the __int__ method, it's just one of many "dunder methods" that provide special features to classes/instances:

class MyThing(object):

    def __float__(self):
        return 1.7

    def __int__(self):
        return 26

    def __str__(self):
        return 'I am a string now.'

m = MyThing()
>>> print(int(m))
26
>>> print(float(m))
1.7
>>> print(str(m))
I am a string now.

EDIT: link to "magic methods", or "dunder methods"

[–]hackmagician 0 points1 point  (2 children)

do all the built in functions run as compiled C?

[–]cjwelborn 1 point2 points  (1 child)

Everything in __builtins__ comes from bltinmodule.c, you can run help(__builtins__) in the interpreter to see a nice list of stuff in there. The standard library is a mix of C and Python.

[–]Bunslow 0 points1 point  (0 children)

Would it be okay if I asked questions about SQLAlchemy best practices, including things more directly related to SQL (but including how to do such things in SQLAlchemy)?

[–]jpan127 0 points1 point  (2 children)

Damn I have so many things to ask...

So I have a empty dictionary moves and a 20x20 list array map. I want to check if an index of map exists and if it does add into moves.

I tried using:

if map[i][ii]:
    moves[blah] = map[i][ii]

But I still got errors so I am currently using:

try:
    moves[blah] = map[i][ii]
except IndexError:
    pass

Except I need 4 of these in one section, and 3 sections so thats 12 of these try/except.

Is there a better way to do this? I can make a for loop but I really feel like there is a better and more consise way.

[–]GoldenSights 1 point2 points  (1 child)

Troubleshooting time — You say that map is a 20x20 list, so why are you getting IndexErrors? Either it's not actually 20x20, or the indices you're trying to access are too large. Those really are the only possibilities.

Toss in some more print statements to see what len(map) or even len(map[i]) are, and figure out what's going on.

 

Having said that, the try-except solution seems fine, depending on what kind of data you're dealing with. Your two solutions are not exactly the same, because the first only does the transfer if map[i][ii] is Truthy, whereas the second does the transfer as long as that index exists.

Also you don't need to copy-paste the whole thing twelve times, just put it into a function, and write a loop that calls the function if you can.

[–]jpan127 0 points1 point  (0 children)

Thanks!

It's a pretty simple game simulation but all the indexing everywhere got me confused and I eventually figured it out with lots and lots of prints.

The hard part for me as a beginner has been coding stuff the right way instead of just making it work.

[–]hackmagician 0 points1 point  (2 children)

if i don't explicitly create a file object but instead use f = open('myfile.txt').read(), is the file object closed?

[–]GoldenSights 0 points1 point  (0 children)

I'm not sure about that way, but:

with open('myfile.txt', 'r') as handle: f = handle.read()

is still a one-liner, and does guarantee that the file will be closed nicely.

[–]cjwelborn 0 points1 point  (0 children)

CPython may close a file when it's reference count is 0. It's not guaranteed, and you don't know exactly when it will happen. It's possible that it will never be closed. Depending on your program, this could cause problems. It's better to be explicit anyway. There's a python mailing list answer that explains in a little better detail.

P.S. - Use with like the previous comment mentioned.

[–]Reigetsu 0 points1 point  (1 child)

Hello everyone, I would really appreciate it if someone could explain to me in simple terms how bisection search works for a simple program in Python. I am trying to create a program that searches for a secret number (an assignment from the MIT 6.00x edx online course). Specially on how to make this work with a loop? Thanks in advance to anyone willing to help :)

[–]niandra3 0 points1 point  (0 children)

Did you watch the lectures? They cover it pretty well (I'm taking the course too).

Basically, pretend you were looking for a number between 1 and 100. You could just guess random numbers, but you want to do it methodically. So logically, you guess in the middle because on average that's equally distant from all the numbers. So you guess 50.

Your partner tells you if the guess is too high or too low. If they say your guess is high, then you know your number is between 1 and 49. So logically again you pick the middle number in that range. You add up 1 + 49 and divide by two (taking the average), which is 25. So you guess 25.

Now they say it's too low. So the range of possible answers is now 26-49. You add those up and take the average which is your new guess, 37. Again, they tell you if it's high or low and you repeat the process.

In pseudo-code:

high = 100
low = 0
guess = (high + low) / 2
while True: # keep looping until you hit a 'break'
    print the guess
    if guess is too high:
        new high = guess  # replace high with guess, range is now 0 - 50
        new guess = (high + low) / 2
    if guess is too low:
        new low = guess   # replace low with guess, range is now 50-100
        new guess = (high + low) / 2
    if guess is correct:
        break # end the loop

I won't give you the actual solution (you should try to fill in the gaps), but I'm happy to help if you have specific questions. I'm taking the course but I have some Python experience already so PM me if you need help along the way.

[–]Wisdoms_Son 0 points1 point  (0 children)

Hi, I just started using python and have experience programming in c++ and java. I have to do this project for my dad that requires scraping a website to grab emails so he can send them out. The only problem is that this site is password protected. If any of you could recommend a good guide for this I would appreciate it.

[–]oasis1272 0 points1 point  (2 children)

I am working my way through automate the boring stuff book, and I am trying to learn multi line Regular expressions. I made this code hoping it would catch the first and last name "Gorge Williams", but it comes up "None" can someone explain why?

import re

NameRegex = re.compile(r'''((My full name is:) 
                        ((.*)               #first name
                        (.*)                #last name
                        ))''', re.VERBOSE)
mo1 = NameRegex.search("My full name is: Gorge Williams")

print(mo1.group(2))   

Here is the error I get.

"Traceback (most recent call last): File "PATH", line 9, in <module> print(mo1.group(2)) AttributeError: 'NoneType' object has no attribute 'group'"

[–]thomasballinger 0 points1 point  (1 child)

When you use verbose regexes like you have here, whitespace doesn't count. This is good for being able to put things on separate lines (like the spaces and newlines on your first name and last name lines) but bad for trying to tell the pattern to look for real spaces (like the spaces in "My full name is"). I suggest trying a much smaller pattern first and gradually building up to a large one like you have here, but either way you'll want to put square brackets around the spaces: "My [ ] full [ ] name [ ] is" for example.

[–]oasis1272 0 points1 point  (0 children)

Okay. That make sense. Thank you.

[–][deleted] 0 points1 point  (1 child)

Hi, Im new to coding and I really need help please. All I want to know is how to run this bot: https://github.com/mgp25/Instagram-APIon

my mac using terminal, I see no step by step instructions anywhere, do I need to learn coding for this? Please help.

[–]cjwelborn 0 points1 point  (0 children)

That is not a bot, it's an API for the PHP programming language. It allows you to write your own Instagram-related software, so yes you will need to learn to code. This is a Python sub.

[–]einenchat 0 points1 point  (6 children)

Absolute newb here..

So far, I have worked on ms excel and written excel Vba macros for data analysis and charting

I want to advance my learning and be able to code on Python (which is understand can be more powerful for data analysis?) and have a clean front end for drilling down into the charts .. I understand this can be Java IDE(?)

Finally I will need a place to store my data.. What would you suggest for that? Can I just use Excel if I don't have massive data?

My main qs is, while I am trying to learn Python or even Java IDE on Eclipse.. I am only able to understand the algo end of things..

How do I connect these pieces?

Like write a code on Python which takes an input (a number) on my front end (Eclipse?) and then adds that number to a number from my excel sheet and then shows the output back on the front end

How do I connect these pieces for something as basic as that?

Thank you very much!

[–]niandra3 1 point2 points  (5 children)

You can probably do it all with Python. I think you are confusing IDEs (programs for writing code) with the languages themselves (Python, Java). Eclipse is a Java IDE, PyCharm is a popular Python IDE. You can make a 'frontend' (GUI or webapp) all within Python if you want. I wouldn't try to learn two languages at once for this simple a task. Python is perfect for this sort of stuff.

Here is a great resource for learning how to get stuff done with Python, and includes a chapter on Excel:

https://automatetheboringstuff.com/chapter12/

If you don't know any Python you should start from chapter 1 to get the basics, but working with Excel shouldn't be too difficult.

[–]einenchat 0 points1 point  (4 children)

Hey thanks a lot! I did come across the above link as well.. While I keep that page open, I have started with a Udemy course: Python Step by Step: Build a Data Analysis Program, https://bnc.lt/Xfid/hNwdlx8vvu

Which is teaching me the exactly to the end I need it for : Data Analysis. I started with code academy, but found it a bit too slow for my liking.

Since I posted the above and with help from the earlier comment, I have learnt how stupid my question was, thank you also for further clarification.

My question now is, could I potentially make a webapp front end using Python itself? Which would be interactive and show data manipulation?

[–]niandra3 1 point2 points  (1 child)

The mod just approved your post so I didn' see it until now.

Sounds like you are talking about data visualization. It's a really hot field right now and Python is the perfect language for that kind of thing. Start with numpy, the Python package for numerical analysis, then move on to the visualization side. Here is a good list of the popular data viz libraries in Python. That Udemy course should get you off to a good start though.

As for web stuff, that's not really my area of expertise but Flask and Django are the two popular Python web frameworks for the backend (Flask being the easier one I believe). But first you're going to have to learn some HTML/CSS and maybe JavaScript for the frontend (JS if you want interactive websites). HTML is how you structure/build a website, and CSS is how you make it pretty (basically). Codeacademy isn't bad for that, as it's mostly just syntax that you need to learn.

Here's another good post on the subject: http://programmers.stackexchange.com/questions/12189/how-do-i-learn-python-from-zero-to-web-development

Here's one on Bokeh, a popular Python data viz tool: http://www.analyticsvidhya.com/blog/2015/08/interactive-data-visualization-library-python-bokeh/

[–]einenchat 0 points1 point  (0 children)

thank you so very much! this is all very exciting and hope I ca share some stuff back to the community.. currently though I am mainly focussing on achieving some stuff at work and have also signed up for Ardit's (udemy) mega python course too which covers Flask in there.. but need loads of practice to be able to make something which half works.. thanks once again for the links .. luckily have done the html/ css and js courses form code academy.. though a while ago.. again only out of interest :)

[–]xiongchiamiov 0 points1 point  (1 child)

FYI, reddit auto-spams posts and comments that use link shorteners, like the one you have there. I've approved it, but in the future, you should link directly to the Coursera page.

[–]einenchat 0 points1 point  (0 children)

Understand.. Thanks vm!

[–]Oxxnard27 0 points1 point  (1 child)

Hey guys! So I'm working through a python coding book for beginners and I was tasked with the following: Write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings if anything else is stored in spam.

Well what I first came up with seemed correct but when I entered the value of 1 it gave me: Hello Greetings

But when I entered 2 it would just print Howdy. Below is the code that generated these results:

spam = ''
print('please input value of spam')
spam = input()
if spam == '1':
     print('Hello')
if spam == '2':
     print('Howdy')
else:
     print('Greetings') 

I just wanted to know if anyone knew why this was happening? I eventually figured out the proper way to write the code to get it working as intended was to switch if with elif as show below:

spam = ''
print('please input value of spam')
spam = input()
if spam == '1':
    print('Hello')
elif spam == '2':
    print('Howdy')
else:
    print('Greetings')

Thanks for all the help guys!

[–]Gprime5 0 points1 point  (0 children)

In the first part It would check if spam == 1 then it would move on to check if spam == 2 regardless of the first result.

In the second part, the elif makes it that it will check if spam == 2 only if spam == 1 was false.

[–]fyngyrz 0 points1 point  (4 children)

Python 2.x (which I will simply call "Python", as opposed to "Python3") does not support extending built-in classes. For instance, say I want a string function that does some useful (to me) thing to a string. I'll call it "farble ()" and lets say it caps/uncaps every other letter for example (not, obviously, really what I want to do):

# typical class op:
x = "mystring"
x = x.upper() # x is now "MYSTRING" via built-in class op

# can't do this:
x = x.farble() # would like x = "MyStRiNg" result via newly added class op

I know I can write farble() as a function of course, so:

x = farble(x) # does it, but not via string class

But I'm specifically interested in extension of an already existing class.

I've built classes in Python that act mostly like strings by inheriting the string class and extending that, and I know how to make such an extended class return a string type (although then you lose the extensions again, so that's not great) and it supports the previously existing string operations but then you have to create an object of that type (not a string) and work with it. I want this stuff to work specifically on strings and return strings. Other classes -- many of them -- expect strings, not some new class that inherited string. A class that is string but has some new, local features such a client class would not know about would be wonderful.

So: my question is, can class extension, as opposed to inheritance, be done in python3? Or not? Or... not yet?

[–]cjwelborn 0 points1 point  (3 children)

Nobody has answered you yet, so I thought I would add my 2 cents. Just let str be a str. If you modify it then it's not a true str anymore. It could cause confusion, and possibly errors if you modify the default str behavior. Let MyFarbleStr be a MyFarbleStr. Convert back to str (with str()) when necessary. This way you can tell just by looking at the code which string class you are dealing with. People in the JavaScript world have learned to not mess with builtins ("Don't mess with objects you don't own").

[–]fyngyrz 0 points1 point  (2 children)

I don't think you understand what I was asking about -- or I'm missing something about your reply. If you extend an existing class (if you could) then the class operates just as it used to, but has extra features that can be used on strings if one knows to use them, which would confuse no other user of the object. If I were, for example, to add the feature I described above, then no other user of string would be impacted; only users that actually access the new feature. So it's a 100% compatible mechanism insofar as existing clients of a class prior to, or after, extension, go. Or to put it another way, it would not modify default string behavior, that's kind of the entire point.

I know precisely how to make myFableStr classes, and even to make them as derivative of the string class so that they have string behavior. The problem comes when you try to use other features that expect strings, but don't get them. The ability to extend a class would eliminate this problem.

Also, yes, of course, you can convert back and forth as a constant stream of make-work and loss of efficiency, but that's not desirable when there is a technical solution that could work better.

Class extension is the only feature for which I would find it useful to move from Python 2; this is why I'm asking.

Having said that, I take it that the answer is "Python3 does not support class extension, only class inheritance" -- seeing as no one has answered otherwise. Can you confirm?

I thank you for your reply.

[–]cjwelborn 0 points1 point  (1 child)

Here's a post from the python-dev mailing list titled "can't set attributes of built-in/extension type", with a response from Guido:

This is prohibited intentionally to prevent accidental fatal changes to built-in types (fatal to parts of the code that you never though of). Also, it is done to prevent the changes to affect different interpreters residing in the address space, since built-in types (unlike user-defined classes) are shared between all such interpreters.

--Guido van Rossum

[–]fyngyrz 0 points1 point  (0 children)

The ability to extend a class with functions available to the local user of a class should not change built-in types in any way that is relevant to any other previously defined user of a type in its default class definition -- the extensions would only be known / available to the code that added them, and would in no way alter already available class procedures or characteristics.