Creating Static Methods in Python
This is a short introductory guide to creating static methods. Static methods, though not used entirely that often, can be a very useful tool. I personally get the most use out of them when organizing my code.
Python’s static methods have a similar implementation as Java & C++. Static methods were not introduced into Python until version 2.2
Example of version 2.2 and higher implementation:
>>> class Foo:
... def bar(arg):
... Foo.arg = arg
... bar = staticmethod(bar)
...
>>> Foo.bar('Hello World')
>>> Foo.arg
'Hello World'
>>> Foo().bar('Hello')
>>> Foo.arg
'Hello'
Static methods can be called either on the class (such as Foo.bar()) or on an instance (such as Foo().bar()). The instance is ignored except for its class.
In version 2.4, function decorator syntax was added, which allows another way to define a static method. If you are using 2.4 or above, this is the recommended way of creating a static method.
Example of version 2.4 and higher implementation:
>>> class Foo:
... @staticmethod
... def bar(arg):
... Foo.arg = arg
...
>>> Foo.bar('Hello World')
>>> Foo.arg
'Hello World'
>>> Foo().bar('Hello')
>>> Foo.arg
'Hello'
If you are looking to do more advanced static methods, look into using classmethod instead of staticmethod. One of the differences between the two is that class method receives the class as implicit first argument, just like an instance method receives the instance. For further reading on class method, refer to the built in functions page. If anyone is interested in seeing example of class method in use, let me know.
Does a Function Like isset() Exist in Python?
The answer is no.
One way to see if a variable exists in the namespace is by catching exceptions when trying to access the variable. Here is an example:
try:
if foo:
# variable is set, do something
pass
except NameError:
# variable not set, do something
pass
Avoid code like this were ever possible. This is not a recommended best practice. If you need variables that you don’t know the name of, trying using a dictionary (hash table) instead. They are made for that exact purpose.
Example of Best Practices
>>> unknown_vars = {}
>>> unknown_vars['foo'] = 2323
>>> 'foo' in unknown_vars
True
>>> 'bar' in unknown_vars
False
OR checking against globals (Thanks to bsdemon for this tip)
>>> foo = 2323
>>> 'foo' in globals()
True
>>> 'bar' in globals()
False
OR checking against locals (Thanks to bsdemon for this tip)
>>> def test():
... a = 12
... if 'a' in locals():
... return 'OK'
... else:
... return 'SORRY'
...
>>> test()
'OK'
UPDATED: My first gut reaction was to quick make a function to handle checking against globals, but as bsdemon pointed out in his second comment, you won’t be able to use the function to check local variables. Thank you again for catching that mistake.
Android Maybe Slow To Market, But This Is Only The Beginning.
While checking out Tech Crunch this morning, came across an interesting article, which I just so happen to disagree with. The article was titled T-Mobile Is Dreaming Of Android Riches. And It Might Have To Keep Dreaming. Naturally, like most articles on Tech Crunch, the piece was well written and though out, but I believe they missed something.
No one can deny that the excitement around the Android platform has dwindled down to nothing (No thanks to Google and the Open Handset Alliance), but that doesn’t mean in the long run, Android will be a viable competitor to Apple. History has shown us over and over again, that executives have ignored new technologies, because of a lack of understanding and/or only concentrating on what’s hot.
My prediction for Android is this. A wave of new phones will finally start coming out with Android installed. These phones will be slightly cheaper or have features that the iPhone lacks (such as a physical keyword), which will cause a decent percentage of people to buy these new phones instead of the iPhone. Plus, you know mobile companies like T-Mobile are going to push consumers to buy their phones instead of Apple, duh.
Jump ahead a year or so and people’s awareness of Android will start coming around. Companies who ignore the current noise and have apps on the market for Android and will enjoy the first big profits. Naturally everyone else will jump on the bandwagon once they see money is being made.
In my opinion, the only real problem for Android is the hardware that the platform sits on. If the hardware is not up to par with Apples iPhone, Apple will win out. People will dish out money for an alternative to the iPhone, but it has to have similar or better hardware specs, end of story. Imagine if this new T-Mobile phone comes out without the capability or hard drive space for music or video’s, shit who cares about what platform it’s running then. (hmmm…kind of reminds me of the wars between Apples and PC’s which is till going on today.)
Tech Crunch is right in saying they should keep dreaming, but only if mobile companies fail to provide the adequate hardware specs. The Android platform itself may take longer to become mainstream, but over time, consumer demand for applications will be there.
Apple iPhone SDK Out in the Wild!
This has been long awaited my many hardcore iPhone fans as well as companies looking to get a jump start on this new market. Along with the software update, Apple also announced that venture capital firm Kleiner Perkins has created a $100 million “iFund” to fund software development on both the iPhone and iPod Touch.
Developers will be provided pretty loose restrictions on what will be aloud to be used, so expect too see some really kick ass apps coming out soon. Apple has said it will keep 30 percent of the revenue from applications sold through Apple Store, but will not charge developers credit card, hosting or marking fees. The developers themselves get to set prices for applications. Apple’s developer program costs $99 to join.
A quote from http://blogs.zdnet.com/Apple/?p=1388…a little fluff from Apple never hurts right?
“Today, we’re witnessing history: that’s the launching of the SDK, the creation of the third great platform, the iPhone and the iPod Touch. Think about it. What the iPhone is all about is in your pocket, you have something that’s broadband, and connected all the time. It’s persona, it knows who you are and where you are. That’s a big deal, a really big deal. It’s bigger than the personal computer.”
“So, [iFund] is about this great opportunity. But more than the money, it’s really about the people, the entrepreneurs, it’s about the great team at Apple, and most of all it’s about the great talent that we can recruit together and go build these amazing companies.”
The SDK can be found here http://developer.apple.com/iphone/program/. Though I wouldn’t get to excited, because as some of my co-workers found out this morning, it will take a bit of time to download. The SDK is over a 2GB in size (ouch right! Take that Facebook and Google).
Building URL (HTTP GET) Query Dynamically
Probably one of the most tedious parts of web development is hand coding a URL with several parameters attached to it. Most beginning developers are use to hand coding URL’s when developing dynamic web apps, much like this.
<a href="page.php?id=<? echo $_GET['id']; ?>&title=<? echo $_GET['title']; ?>&q=<? echo $_GET['q']; ?>">XXX</a>
This isn’t a horrible practice and of course it works, but the code snippet below will make your life ten times easier, believe me. It’s much more expandable and easier to strip and encode data if needed. Plus, the first way can be lead to bugs in your code if not properly handled.
In addition, you need PHP 5+ to use the http_build_query() function. (You could easily build a similar function yourself if needed).
<?
$queries = array();
if(isset($_GET)) {
$keys = array_keys($_GET);
foreach($keys as $key) {
$queries[$key]=$_GET[$key];
}
}
//http://us2.php.net/http_build_query
$params = http_build_query($queries);
?>
<a href="page.php?<? echo $params; ?>">XXX</a>
If you need to add parameters to your URL, just append to the $queries array.
HTTP POST without cURL library - PHP
Found this interesting function that can handle a HTTP POST without using redirects or any special hacks. This is extremely useful for sending data over a secure HTTPS POST or to another web site. cURL is probably the better choice here, but if you don’t have the library avaliable, (like many developers because of strict hosting solutions), this function might be your best bet.
Anyway on to the code. I found this awesome code snippet at: http://netevil.org/node.php?nid=937
I encourage you to check out some other parts of this guys site, pretty good stuff.
array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
?>
Microsoft Windows Vista to harm iPod Sales?
Documentation updates on Apple’s web site indicates that Apple is urging iPod owners to stay clear of using their iPod on Windows Vista because it could possibly harm the iPod (corruption of hard drive and files on device).
So the question is, will this actually harm Apple’s iPod sales? Doubtful, since Apple will evently provide an update to the iTunes software and really most customers will not even notice the issue. It does question whether Microsoft has been withholding competitors ability to update software packages for Vista or is Apple just trying to make Microsoft look bad. Either way, I predict that this will be merly be overlooked by the major of customers.
As for iTunes not being updated, it is also interesting to note that Microsoft’s own Zune software package (which is a rival music player) did not work with Windows Vista until only recently. Sounds like Microsoft is having some real internal communications problems.
Google Updates Page Rank (It’s been a while)
So I checked out Runman’s blog today and he made a post about Google Page Rank being Updated. The first thing I did was quick check all my sites to see if my page rank was increased.
Now let me say that I haven’t really been trying to build any rankings on any particular site, but I feel that a few probably should automatically out rank this site because of the following:
1) This site is not even 6 months old
2) I have hardly any back links or even content
3) I have almost 0 traffic going to this site
While checking my rankings I noticed that this site actually got a 1/10 page rank (nothing to be proud of). The odd thing is that another site I own has some high quality back links, is over a year old, and has more content, but it didn’t even go up (actually still at 0/10). Weird right. So does Google weigh blogs better then normal sites since I have been linked to sites like Technorati?
I think I will do some more experimenting :).
A Note on Python & Programming Guidlelines
Today I had to go through the mundane task of fixing other programmers code. Not that I’m a better programmer, but nothing is worse then going through unorganized, undocumented, and messy code.
My biggest hint to any new programmer is to be as organized as possible. Organization does take time. Each programmer really does evolve with experience, but most newbies just don’t take the extra time to be organized. Believe me, when I look at code I made two or three years ago, I really kick myself for being stupid and lazy. I end up rewriting programs or spending extra time figuring out algorithms (The old algorithms are usually inefficient to boot!).
The other reason I’m writing this article (kinda relative to the above comments) is because I have been meaning to share the following document that I found for python coding guidelines. Most of the points made in this document can be applied to any scripting language. It’s not that long, but I would recommend at least skimming it.
http://jaynes.colorado.edu/PythonGuidelines.html
If this document does not help, I would recommend looking at other highly experienced programmers code to see how they keep organized. Take a look at a few open source projects, I guarantee it will help.
FC5 Boot GDM - init levels
Red Hat & Fedora versions all have different run levels. These run levels determine different operational and security states of the Linux/Unix system.
The use of the ‘init’ command under the root user will allow you to change the level. For example.
If the current level is at 3 and you want to be at 5 do the following:
su root
init 5
The following table explains all the run levels for Red Hat/Fedora Distributions.
| Run Level | Description |
| 0 | Halt |
| 1 | Single user mode |
| 2 | Multiuser, without NFS |
| 3 | Full multiuser mode |
| 4 | unused |
| 5 | x11 |
| 6 | reboot |
GDM, the GUI startup interface for most linux distributions, needs to use the 5th run level to operate at startup. Some times the run level is at 3 for some linux distros and it needs to be changed to 5. To change the run level at startup, do the following:
Open the following file under the root account:
/etc/inittab
and there should be a line like
id:3:initdefault:
Change the 3 to a 5, and you should be fine.
(Note: if you do a text install of Fedora, it will automatically set the run level to 3. Once you follow the above instructions, GDM will start up automatically as it should.)







