Python

Python ImportError: cannot import name X

This was strange, I had a bunch of classes in a file and was trying to import one of them from a file in a child folder.

The package looked like this:

/main_classes.py <– “import child” was in here way on top
/child/__init__.py <– For every file in this folder, import it
/child/some_file.py <– Import a class in main_classes.py *Error*

The reason was that I was doing “import child” way on top before implementing the class I was importing in some_file.py.

I moved the “import child” line from the top of the main_class.py to the constructor of the class I was implementing and it fixed the issue.

I hope this made sense :) (and I know it will to the person with this problem ;) )

Archived under Python Comments

Decorating Python’s sys.stdout

Try this:

class stdoutflip:
 
    def __init__(self, sys):
        self.stdout = sys.stdout
        sys.stdout = self
 
    def write(self, txt):
        txt = list(txt)
        txt.reverse()
        self.stdout.write(''.join(txt))
 
 
class stdoutupper:
 
    def __init__(self, sys):
        self.stdout = sys.stdout
        sys.stdout = self
 
    def write(self, txt):
        self.stdout.write(txt.upper())

To test it do this:

out = stdoutupper(stdoutflip(sys))

Now try printing stuff:

print "Hello Python!"

:)

Archived under Fun, Programming, Python Comments

Python as CGI and Error 500, Internal Server Error

If you have this problem on *nix systems, these are the things to look for:

1 - Make sure your line breaks are \n not \r\n you can set this in almost all editors, you will have to either select *nix like line breaks or \n somewhere in your editor preferences.

2 - After the first step you will have to make sure that your FTP client uploads the files in ASCII format and this will insure that \n will stay \n.

3 - If it still doesn’t work, make sure your Python script’s permissions are 755. You can try:
chmod 755 your_python_script.py

Or use your FTP client to fix this. (Refer to it’s documentation but usually you can right click on the file, on your server and click properties)

4 - If you still have the problem, you will have to have the right shebang line in the beginning of your script, the most common one is:
#!/usr/bin/env python
If this doesn’t work try:
#!/usr/bin/python
Or:
#!/usr/local/bin/python
Note that, this must be the first line

5 - If none of these worked and you have root access to your server, try:
tail -f /usr/local/apache/logs/error_log (Note that, the path to Apache error log might be different on your server)
And look for the error message associated with your request.

6 - If you still can’t figure it out, write to your hosting company and ask them.

I hope this helps :)

Archived under Annoying Stuff, Python Comments

Let’s make Python web friendly

Here is a great language, so powerful and fun to write code with yet it’s not really being used for developing web applications.

There is no easy way to run your Python scripts like PHP, you will either have to run them as CGI and there is a lot of pain associated with that if you know what I mean, sometimes you only get “Internal Server Error” and you have to pull your hair out until you find out what the problem is.

The other thing you can do is to use something like mod_python, which is almost impossible for an average user to install and it imposes some restrictions on you. For example, you have to have certain methods with certain names and mod_python will call those for you.

I’m in the process of starting to make a module for Apache (and the Lighty and then IIS hopefully) that has three great qualities that will help getting Python out there for web developers to try:

1 - It will install very, very, very easily on all platforms, it will be ready to go, no pain. The server admin just runs install and it’s there, ready to use.

2 - It doesn’t do anything fancy, nothing fancy, it only hands over the Python script to the Python interpreter and writes the output to Apache, that’s it.

3 - You can put your Python scripts anywhere you want just like PHP.

The goals of this project:

1 - To make Python readily available for anyone to try, without a lot of pain, as easy as PHP.

2 - To have this new Python module installed on all the hosting packages.

3 - To have this new Python module be part of all Linux distributions.

4 - To have a lot of web developers finally using it and enjoying it.

5 - To start the development of a lot of open source web apps written in Python.

If you want to help me with this, leave a comment, you don’t have to be a C wizard.
Otherwise, please help me spread the word in any way you want.

Thanks!

Archived under Python Comments (14)

Python: understanding/reading list comprehensions

List comprehensions in Python can be tricky and hard to look at but once you know the secret, it will become very clear, for example, say we have a list:

a = [1, 2, 3, 4, 5]

And we want to make a second list out of this “b” with values of “a” plus 2, so we want to get this:

b = [3, 4, 5, 6, 7]

Now, the way to do this without using any fancy feature would be:

b = []
for item in a:
    b.append(item + 2)

To turn this into a list comprehension we will start like this:

b = [for item in a]

Now, we will have to add our “item + 2″ to the left side of the for loop so:

b = [item + 2 for item in a]

If you didn’t understand what happened, don’t worry, just keep reading.
Now, let’s look at another example, this time, we will try to understand a list comprehension that’s already written, a very simple one:

a = [1, 2, 3, 4, 5]
b = [x*x*x for x in a]

To read this, start form right to left:

for x in a: x*x*x

Internally, this will be translated to something like:

b = []
for x in a:
    b.append(x*x*x)

So the secret is to read from right to left.

If there should be a condition, it will come after the for loop so to increment all the items that are greater than 4 by 2:

b = [item + 2 for item in a if item > 4]

I hope this helps :)

Archived under Python Comments

Print without a new line or space in Python

Here is another little trick in Python; the print statement always inserts a line break after it prints your text, for example:

print "Hello"
print "Python"
print "!"

Will print:
Hello
Python
!

Now, you can fix the issue with the line break by inserting a comma after the print statement:

print "Hello",
print "Python",
print "!"

This will print:
Hello Python !

But the problem is that it will still insert a space after it prints the text, so to fix this you will have to use sys.stdout.write like this:

import sys
sys.stdout.write("Hello ")
sys.stdout.write("Python")
sys.stdout.write("!")

This will print:
Hello Python!

Have fun with Python :)

Archived under Python Comments (4)

__FILE__ equivalent in Python; get the path to current file in Python

Update:
There is __file__ in Python.

You could do this as suggested by some but I don’t know why:

import inspect
this_file = inspect.currentframe().f_code.co_filename

I hope this helps :)

Archived under Python Comments (4)

Dynamically adding methods to objects in Python

The trick is that you have to add the function to the class not the instance to see how, run your interpreter and write these:

class test:
	def __init__(self):
		self.yes = "Hello Python!"
 
def a(self):
	print self.yes
 
t = test()
t.b = a
t.b()

When this runs, you get:

Traceback (most recent call last):
File “ “, line 1, in
t.b()
TypeError: b() takes exactly 1 argument (0 given)

To fix this, you will have to assign the function a to the class itself (test) not the instance (t) like:

test.b = a
t = test()
t.b()

Python is fun :)

Archived under Python Comments

One Problem With Python

I think one problem Python has is the lack of a great online manual, with great I mean like PHP’s:
http://www.php.net/manual/en/function.ftp-alloc.php

Every single function is documented with examples and I think this is one of the main reasons why PHP is so popular.

Archived under PHP, Programming, Python Comments

I Heart Python

I always knew about this language but I was so busy with PHP and daily work that I didn’t really get to learn it and whenever I looked at the syntax, it scared me, I didn’t want to learn another syntax so I decided to learn it later.

About a month ago, I came across Python and got a chance to play with it and I have to say WOW!

It is one of the coolest languages I’ve ever seen, the syntax is cool, the laziness is cool.
It has a great library and you can do anything you want basically.

To see some cool things, go ahead and download the Python interpreter here:
http://www.python.org/download/

Get the latest version and after you are done, run it and type these:
(Note: You will have to hit enter/return twice at the end of last line.)

import urllib2
def get_url(url, num):
	contents = urllib2.urlopen(url)
	print str(num) + " done!"

Tabs are important!

Then go ahead and type these:

for i in range(0, 100):
	get_url("http://www.yahoo.com/", i)

Note how clean this is, the code speaks for itself.

As you can see the output looks like this:
0 done!
1 done!
2 done!
3 done!
4 done!
5 done!
6 done!
7 done!
8 done!
9 done!

Now I will show you some of Python’s powers, go ahead and type these:

import thread
for i in range(0, 100):
	thread.start_new_thread(get_url, ("http://www.yahoo.com/", i))

Wow! This is so great, imagine how much you can do with this language.
Also note that, I’m not an advance python programmer and I’m still learning but this language will take over the world one day.

The only thing about PHP is that it can be embedded inside web pages but it would be very easy to write a template engine in Python to do this.

It could be like PHP’s Smarty but with Python syntax and could compile the templates into Python scripts and run them instead of compiling every time. It would then check for the mime time of the file and would recompile if there were any changes.

I’m having so much fun playing around with Python and have never been this excited about a programming language :)

Archived under Programming, Python Comments (3)