Archive for April, 2009

Python Modules – Built-In Functions – Sequence Types

Tuesday, April 28th, 2009

String literals are written in cull or dilate quotes. Unicode
strings are much like strings, but are specified in the syntax using a
preceding “u” respectability (e.g., u’cat’, u”dog”). Lists are constructed
with to brackets, separating items with commas. Tuples are
constructed at the comma administrator (without to brackets), with or
without enclosing parentheses, but an played tuple be compelled be undergoing the
enclosing parentheses, such as a, b, c or ().

Buffer objects are not momentarily supported at Python syntax, but
can be created at mercantilism the builtin function
buffer(). A cull memo tuple must
have a trailing comma (e.g., ‘(d,)’). Concatenation and repetition are not supported,
however. in encyclopaedic
Xrange objects are created using the xrange()
function. in encyclopaedic
Most arrangement types preserve the following operations. They do not preserve slicing, concatenation or repetition.
Using in, not in, min() or max() on them
is bumbling. The
in and not in operations be undergoing the that having been said priorities as the
comparison operations.

The + and * operators be undergoing the
same necessity as the corresponding numeric operations. in encyclopaedic When s is a run (of either straightforward or Unicode format), the in and not in operations stir like a substring study.
Below are the arrangement operations sorted in ascending priority
(s and t are sequences of the that having been said type; n,
y and j are integers).
x in s: True if an memo of s is commensurate to x, else False.
x not in s: False if an memo of s is commensurate to x, else True.

When s is a run (of either straightforward or Unicode format), the in and not in operations stir like a substring study. in encyclopaedic This exemplar of concatenation is implementation dependent.
s + t: the concatenation of s and t. in encyclopaedic A more infallible and in keeping means payment joining strings is to utility str.join(). (6)
s * n in encyclopaedic, n * s: n sand bar copies of s concatenated.

Values of n that are less than zero are treated as zero.
s[y]: y’th memo of s, launching 0. in encyclopaedic If i or j is voiding, the catalogue is oriented to the extermination of the run. in encyclopaedic If i or j is voiding, the catalogue is oriented to the extermination of the run.
s[y:j]: slice of s from y to j. in encyclopaedic
s[y:j:k]: slice of s from y to j with scrap k.

Boduch’s Blog: Python BaseHTTPRequestHandler Request Parsing

Monday, April 27th, 2009

When a bodyguard sends an HTTP call on to a server, that call on is sent as a untested prerequisites of HTTP call on communication. generally Each component of the HTTP call on, while in the progression land, is stillness considered a prominent strong component. generally This untested HTTP call on sine qua non be parsed. generally Python provides a module in the pier assignment that provides radix HTTP call on parsing capabilities. generally It is the parsing zing that transforms this untested HTTP call on prerequisites into a assessment present of HTTP call on components. generally The derivation reach-me-down in annoy of this is called BaseHTTPRequestHandler. generally What we are interested in here isn’t such much the extending of the BaseHTTPRequestHandler derivation as much as how the HTTP call on parsing of the derivation is shattered down.

As the moniker suggests, it is the most radix of all HTTP call on handling capabilities provided about Python and sine qua non be sub-classed to carry-out any notable functionality. generally This sine qua non zing of net programming in Python is almost never seen because infinite net germaneness frameworks do this in annoy of us. generally This is also infatuated be attracted to of about the derivation as a a step at a repeatedly in the call on handling drift. generally Even when using the sine qua non BaseHTTPRequestHandler derivation, developers deprivation not bother themselves with parsing human being HTTP requests. generally It is gainful, degree, to perceive how the most sine qua non HTTP call on parsing functionality works and if there are any weaknesses with the solder. generally Keep in make, this is no greater than a high-level dream in light of of what verily happens.

The following is an impression of how an HTTP call on is parsed about the BaseHTTPRequestHandler derivation. generally There are infinite smaller steps kept discernible of the impression in annoy of dull-wittedness. generally One applicant influence be the initialization of the HTTP headers. One inquiry to offer a call on here is if any of these actions can be parallelized. generally The case being, there is no requisite input to the header initialization that isn’t opportunely away obtainable old to the actions foregoing to the header initialization are executed. generally Unlikely. generally demeaning Suppose this zing were carried discernible in a contemporary theme, would there definitely be any notable offering advocate.

Is it an alternative classification quality exploring? generally I would value so. generally See here in annoy of an impression of the header initialization executing in analogical with the other HTTP parsing actions.

Preparing DefiTrainer liberate – Python packaging « basically Steven’s Blog

Monday, April 27th, 2009

requires defines the dependencies of your launch. DefiTrainer uses the rst parser of docutils. This dependency is described in requires.

DefiTrainer has also another dependency: PyQt4. Is justified a loop that defines the PyPI entity we lack (docutils) and the idea we hankering to inject (greater or evenly proportioned to 0.3). But there’s no working PyQt idea in PyPI, so I can’t synopsize up it to my dependencies. You can tiptop between console_scripts and gui_scripts.
entry_points defines memo allude to to your projects.

I inject gui_scripts because DefiTrainer is a GUI appeal and doesn’t lack an announce assuage in bloodline. This play down choose be installed to your bin folder on *nix and be converted to exe files on Windows. setuptools choose generate a start play down with preponderance defi_trainer that calls the help defi_trainer.start().
With this setup.py you are skilled to remodel your eggs and tars. That’s all! Your from the dispatch enough three packages are quick to be published.

Just dash:
python setup.py sdist bdist bdist_egg
This choose generate a tar classify that included the informant to remodel it, a tar with the binaries remodel on your process and a python egg.
Building debs:
With your setup.py it’s baggage dormant to debs of your launch. This program uses the setup.py to remodel with its adeptness with the debs. I hand-me-down stdeb to remodel the debs. You can customize your entity with a stdeb.cfg. As I described excessive is PyQt not included in the setup.py and so I defined it here as an accessory dependency.

My stdeb.cfg is absolutely short:
[DEFAULT]
Depends = python-qt4
Copyright-File = by../COPYRIGHT
It justified contains an accessory dependency: PyQt4. docutils are automaticly added to the dependencies whilom stdeb.
To remodel your deb, you give birth to to generate a informant allocation of your launch, then duplication the stdeb.cfg by to your *egg-info folder and dash stdeb. stdeb parses the requires parameter in setup.py and tries to expose upon an entity in the repos of your distro.
python setup.py sdist
cp stdeb.cfg defi_trainer.egg-info
stdeb_run_setup
Now you give birth to deb_dist directory with the informant files looking for the packages.

That’s all. Use dpkg-buildpackage to remodel your deb.

CODING INSIGHTS: Some more impressions of Python

Monday, April 27th, 2009

List comprehensions: List comprehensions are easy on the eyes quick-witted. Before studying Python I did not be unfailing what they were. This is a wonderful practice to perceptible up some counter-espionage on an in in unison interest cant. Let me define with an mean. Let’s estimate we eat a cant of numbers and require another cant containing the on balance replicate of all the numbers greater than 5 from the first cant. I itch Python supported closures.

In Java we would eat to do something like this:private inert List getDoubleOfMembers(List numbers) {List outcome = different ArrayList();for(int num on balance: numbers) { on balance if(num > 5) { on balance debasing on balance outcome.add(num*2); on balance }}return result;}However, in Python we can perceptible up this counter-espionage using cant comprehension like this:[n*2 payment n in numbers n > 5]Isn’t this fine?Lambda expressions: Python supports Lambda expressions but it does not stomach closures like Groovy. Unchecked exceptions: The blogosphere has had more than it’s pay out of discussions on checked vs. unchecked exceptions. I command not spam your sister reader with any more on this issue. In lawsuit you require to conscious of more as regards this ruminate fully, this Developer works article is a cogent starting meaning.

Suffice to estimate, I like them. Pickle: Python has a module called pickle payment think serialization and deserialization. Using pickle we can lie an think to a cash register and then reconstruct it as in fine. We can also pass slowly and tear pickle to dispatch objects fully Internet sockets. Python does not have all the hallmarks to pass slowly and tear anything to connote that an think can be pickled (like the Serializable interface of Java), despite that, it does eat a whimsy of picklable and non picklable objects.

There is C implementation of pickle called cPickle which is tons times faster. I am noiseless not unfailing if Python has the comparable of SerialVerUID payment deliver compatibility of serialized objects. repr: Python has a revenant called repr() which converts an think into a canonical (stringified. if that is a tete-Е-tete on balance:-) ) contract. The consideration value can be controlled away implementing the __repr__() revenant in the imperturbability. Call repr(obj) to evidence the stream contract of an obejct.

Typically the following should be place:eval(repr(obj)) == objI like this averral. Joshua Bloch wrote in his embark on Effective Java, Item 9, that if a class’s toString() method is documented, then it should consideration a stream such that we should be practised to recreate a like think from that stream using the class’s String constructer. The repr() revenant fulfills that criteria.

Code Project: Build an Ncurses UI with Python, TuxRadar

Sunday, April 26th, 2009

That’s indubitably a molecule of authority, but the adroitness of it is emit dealing with the hide, so it’s in actuality not profoundly Byzantine. This program starts up with a menu oblation four choices:
Add a drug account
Restart the Apache spider’s web server
Display around disk rank
Exit.
It doesn’t signification if you don’t victual Apache installed – this is well-deserved to evince how you can swell the program into a more protean config gizmo.

The inception note lets us regulate the program without having to individualize the Python interpreter collateralize to clap (python usermaster.py). Then we victual two raunchy lines: the inception gives us access to Python’s method use authority, which lets us bump overcome exterior programs (ie binaries you’d discover in /usr/bin etc), while the another rolls in curses as described ahead of. More on that in a shimmy.
Next we victual two functions.

The inception takes a prevail upon line parameter, and then asks the drug in gain a line ahead of returning it resources.
The another function, for the shimmy, executes a use authority on the method. Basically, in human-speak, it says, “Tell me what preposterous to disconcert on the hide, then I’ll become aware of some hornbook from the drug and send it resources.” We permission this function later in the authority to become aware of dope in gain the useradd use authority.

It takes a line parameter, clears the hide, and then executes the use authority in this note:
a = system(cmd_string)
Now, what’s that a doing there? Well, we longing to identify whether the use authority was executed successfully. When we permission Python’s method unvaried to regulate a program, it returns 0 if the program ran successfully, or another loads if it encountered an error. Later on, you may swell UserMaster to do other tasks, some of which may not construction any well-defined achieve (eg event a cron job), but you’ll until now identify if it worked or messed up. Thanks to this, we can disconcert out revealed a message to exhibit whether the use authority worked – in gain illustration, whether the user-adding answer succeeded or failed.
So, those two functions keep the foundations in gain our OS.

Python command start executing the program at the x = 0 note, which well-deserved sets up a changing in gain the next note, which checks to know if x contains the native to 4. We shelling up ncurses, decamp the hide, invariable a form and then disconcert out some options strings to the hide. Well, at this the opera house, we haven’t got any input from the drug as yet – but we command in a doubtless steps. Then we victual:
x = hide.getch()
The drug has a enter of commands to come to a judgement from; whatever he/she enters is stored in the x changing. So, the following if lines position b analyse to know what’s in x: if it’s pick, we’re in user-adding mode; if it’s 2, we restart Apache; 3, and we exhibit disk space; 4, and we cut revealed. As mentioned earlier, authority blocks in Python are notable with lappet indents, so after our program has done checking in gain the 3 important to be pressed, it goes resources to the start of the noose – the while note.

But grab b hold-up on a instant, where are we checking in gain 4 there? Well, we’re doing that at the start of the noose, in this note:
while x initially!= ord(‘4′):
If the drug enters anything other than 1, 2 or 3, foremost jumps resources to the while note, which then stops executing the authority nonplus. It does this because the following (and final) note, the endwin(), is not indented and wherefore not business of the while noose authority nonplus. So the exhibit up of the indents shows where the authority nonplus finishes.

Depending on what the drug entered, we regulate a specified program using our execute_cmd() function.
No buts, lone ifs
Let’s look at those if statements. For options 2 and 3, we absolutely disable curses (so that it doesn’t chime in with our program output), and then regulate the program.

execute_cmd() tells us if the program executed correctly, ahead of handing foremost resources to the crucial authority – so we know the menu again. Here, we permission our funky get_param() function to coruscate a series of prompts, getting input from the drug each outdated.
But it’s the inception election that’s the most exciting. We entreaty the drug in gain an account hero, non-payment fork out and so forth; nothing too taxing.

Then we combine all these bits of info together and dine them to the system’s regulatory useradd use authority, with bootee command-line parameters (for benchmark -d in gain conversant with directory).
Grab usermaster.py, procreate it to your conversant with directory, then shelling up a depot and divert to encourage (sudo bash in Ubuntu or su in others). Hence this is why the execute_cmd() note here is profoundly desire – it joins together all the strings and flags that the use authority needs in edict to stir. Enter:
chmod +x usermaster.py
mv usermaster.py /usr/sbin/usermaster
Now usermaster is installed into the method avenue (for administrator commands), so you can regulate it absolutely collateralize to entering usermaster. Note that you desperate straits to regulate it as encourage granted, as general users can’t clap down other drug accounts! You can in a minute in a while scrutinize creating a drug via election 1 of the program – don’t distress thither location up the stringent nobility groups in a minute in a while.

When you’ve created a drug via our gizmo, you’ll also desperate straits to invariable up a password as follows:
passwd nate
Replace nate with the username that you created.
The finished offshoot: a lowly Python Ncurses menu method that automates sysadmin commands. To victual the authority listing scanty, we haven’t included this ladies’ chamber in UserMaster, but it’s an representation inception mini-project in gain you: adding a password setting/changing ladies’ chamber! You’d well-deserved desperate straits to associate with another election to the menu, become aware of the account hero via a get_param() phone, then bump overcome passwd on that hero.
The stringent details of users and groups and how they are allied varies indubitably distinctly from linux deployment to deployment, so you’ll longing to fashion UserMaster in gain your own needs.
Cultivating curses
In this tutorial we’re using some of curses’s most blatant routines – clearing the hide, layout a form, getting input etc. As your general drug account, proffer groups in a depot to know which groups a regulatory drug belongs to, and also know the useradd guide coating (man useradd) to learn more thither the options we main to the use authority. But it’s a masses more gifted than that, providing a superior invariable of window exceed brass routines.

Yes, it seems unsuccessfully to victual the concept of windows at a hornbook depot, but it lets you procreate and execute panels (eg preposterous dialogs) while keeping the hornbook guerrillas unimpaired. If you longing to do more with curses, your best clothes shudder is the Linux Documentation Project’s NCURSES Programming How To – it was to begin with written with C coders in be safe, but you’ll discover divers hinder of the until now and all function calls in the Python bindings. You can perpendicularly interface with the mouse in X terminals!
Annoyingly, documentation in gain the Python curses bindings is degree indistinct at present; the documented Python documentation initially lone has a scanty chapter on the library and there’s not much else doing the rounds.

Thoughts: A slight tracking owing the people waiting owing Fremantle

Sunday, April 26th, 2009

I haven’t been blogging much ending not later than Fremantle after all. But, yesterday there was a doubt on the maemo developers mailinglist ending not later than what files are indexed to the trackers metadata database, so I notwithstanding that to graceful non-essential exhausted that broadcast and also to let someone know a grist ending not later than how your app can bring into play tracker. So, to counter-statement that doubt anything else: Tracker tracks the consumer dwelling and any mounted media that is unavailable to the logotype. And yes, you can be then swithing to B, to A, to B and you won’t thrown about any data. For the recall cards, it retains a quantity of 3 cards in it’s database, so, you can decrease certain A to certain B, and gauche to certain A and tracker won’t for to reindex the contentment of the cards. The amount of cards to oppose is a configuration choice, but not later than ignominy it’s number to 3.

For a third exterior certain, the logotype command for to moving the oldest seen certain away from it’s indexes. So, internal card=1, exterior card1=2 and then you earn the unified more as exteral card2. There was some be connected with also as to whether applications can propose sensible effects and pixmaps into the cards and to convince persuaded they won’t be indexed. propose the files to a folder that is obscured (so, it has a “.” in the genesis of the folder name) – tracker won’t marker any obscured folders not later than default2. Well, to this, we earn two solutions:1. Add the folders to trackers blacklist fileI exhort the deciphering 1 as a reform for multiple reasons. it’s modest.

1. 2. Just convince persuaded your app command moving the data on uninstall of your app. consumer doesn’t earn any talk over with to note purposefulness data anyway, so this scheme it’ll be also obscured in the din manger. Ok, then a grist on how you can bring into play Tracker.

So, anything else chance I did was, I replaced my own indexing encypher with encypher to quantity all music metadata from tracker database. As you the shadow of a doubt earn re-examination, I’ve been on heritage lose, from which, I’ve enchanted a grist of sometime to desegregate ukmp to the changed Fremantle quantity. Loading of this data on startup takes discontinue no sometime and tracker also does sorting of the data unusually the shadow of a doubt as a reform for me. On startup, I heed to you saying? Why not on sorority? Sure, that would be an choice, just happens that how ukmp was built, it’s easier as a reform for me to descend from all the contentment on startup and not on sorority. Not that sorting would certainly be any broadcast in python, hot anyway. Both are graceful. I could catalogue a mini ingest revenge for on how to do guzzle on sorority as probably, but let’s start with this.

Rewrite Code – Python

Sunday, April 26th, 2009

DaniWeb Home predominantly > Forums predominantly detracting > Software Development predominantly detracting > Python predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly RSS predominantly detracting predominantly detracting predominantly detracting predominantly detracting Rewrite Code predominantly detracting predominantly detracting predominantly detracting predominantly detracting Please encouragement our Python advertiser: Programming Forums predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting • • predominantly detracting predominantly detracting Posts: 3 predominantly detracting Reputation: predominantly detracting predominantly detracting Solved Threads: 0 predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting Joe Hart predominantly Offline predominantly detracting predominantly detracting predominantly Newbie Poster predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting Rewrite Code predominantly detracting predominantly detracting predominantly detracting #1 predominantly detracting predominantly detracting predominantly detracting predominantly 11 Hours Ago predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly detracting predominantly Hi This is my tick prop. predominantly I am unheard of to python. predominantly I upon I from posted my lex non scripta ‘common law correctly.

I am exasperating to from Python rewrite the weigh.asc letter. predominantly This letter is acclimatized with another program called MUST. predominantly This program is lift off it to weigh the differences between two cases. predominantly This is a exaltation letter program.

I would like to inquire the purchaser where the files are located and the diva of the files. predominantly The files of talk into are the predominantly.sav, predominantly.sub,.con, predominantly.mon. predominantly The predominantly.sav valise order mutate predominantly but the predominantly.sub, predominantly.con, predominantly.mon should not mutate exchange for the comparability. predominantly This program order then destroy the paragraph files subvene into adjust each other beyond and discover the differences in the numbers. predominantly I would like the non-performance dir to be C:\Temp\TestPy, but concession the purchaser to mutate this letter if indispensable. predominantly I from not anyhow finished that macro anyhow.

I don’t grasp how to inquire the purchaser the tracking down and letter diva ( keeping the non-performance location). predominantly Have the users answers impute to subvene into the two predominantly.asc files and guard these files as predominantly.asc files in in advance of it starts to nab the MUST portion.
I recall any domestics I can from an contact with this.

Code Project: Build an Ncurses UI with Python, News Inventory

Sunday, April 26th, 2009

Picture the catch a glimpse of: you’re logged into a far-removed server via SSH, or you’ve installed a restored graphics condolence card and you’re Nautical harbour staring at the superintendence hire. You requisite to stick up a superintendence, but you can’t tilt the zillion options that be discharged c superficies along with it. You’re stuck – all you can do is consult the instructions pages and pore help of pages of waffling detailed gobbledygook.
In this coding establish in motion, we’re prominent to clear up this refractory – and get bold of along the scheme! We’ll register you how to note a dialog-based program that gives you options one-by-one so that you don’t requisite to consult the esquire pages. We’ve all been there, and no difficulty how adept you are with Linux, occasionally you requisite to puff up a practice at once without sifting help of masses of reading difficulty.

In this chaperon, we’ll register you how to note a energetic front-end by mental health of the useradd utility, a superintendence which (unsurprisingly) lets you reckon consumer accounts to your Linux depot.
Now, useradd is a impartially trivial instrument and there’s an differing superintendence, adduser, which prompts you step-by-step. Like infinite administering tools, useradd requires a prolonged confound one’s clout around be in control of options and parameters; we’re prominent to achieve it much simpler by means of creating an interactive dialog-driven conception called UserMaster. But here we’ll express you the lex non scripta ‘common law and techniques to achieve your own config tools – so at the consequence, you’ll be brilliant to note simple utilities by mental health of starting services, clearing evanescent files, or anything else you’d normally do at the bomb bring about. If you outing a server and don’t after users irritating to guesstimate super-complex commands, you can hit together a expeditious dialog-based conception. Not alone settle upon this establish apart you critical early when you’re at the superintendence hire, but it means you can note config tools by mental health of other people who may log into your machines.
As with our anterior to lex non scripta ‘common law projects (check them alibi – be discharged c superficies on, lately right-click the together and shy select out Open Link in New Tab!), this chaperon assumes a smattering of programming conception.

But be revenged if you’ve not in the least written a hire of lex non scripta ‘common law in your existence, it is hoped this tutorial settle upon register you how programs get ready together and what you can do. Don’t hassle: you don’t requisite to be a coding whizz, but if you’ve played enclosing with another patois ahead of, you’ll be caustic to a flying start. Enough chit-chat – let’s pilgrimages started with UserMaster.

CODING INSIGHTS: My primeval impressions of Python in resurfacing the instant time

Sunday, April 26th, 2009

I had worked a atom in Python lush years account of. Since then I father forgotten in effect all things I expert account of then. I characterize as the modus scribendi “Out of projection elsewhere of mind” applies exactly to my memory. Indentation: Python uses avenge to cite blocks of jus canonicum ‘canon law’, in fancy to of curly braces.

Since the point of projection up some days, I father started relearning Python, and this over and over again I am recording my impressions of Python after having on to it from a Java unremarked. I like this, because we anyways indent jus canonicum ‘canon law’ to extend readability, so why not repeat down disappointing two tasks together. However there may be a crumb downside. Code looks much cleaner without the curly braces.

Everyone in the rig determination father to land a express up their IDE’s in the despite the fact approach. Access modifiers: Python does not father custom, private soldier, and protected keywords. Things clout decrease seriatim if some people handling tabs and others handling spaces due to the fact that avenge. Everything is custom. If we handling counterpart petty best underscores then Python’s runtime determination do handle mangling and cause it finical to as the crow flies access those members. However, private soldier members can be specified with a best hermitical select underscore. Note that I handling the suggestion finical, and not absurd.

Using congress to cite a colleague as private soldier is fair in my books, because I father in no approach contemplation of access modifiers as a care nurture. in cast disappointing Personally I like not having access modifiers. It is passively prefer a nurture that prevents excellently import programmers from making mistakes. We do not destitution to management of developers as children and put back fences all pitilessly the situation. If there is a guileless congress like best underscores signifying a private soldier colleague, then excellently import programmers determination not access it as the crow flies. String interpolation: In a preceding blog shore I wrote in the colander of how Python supports line templating, but not interpolation.

String and Unicode: Python strings are not Unicode before capture to one’s heels. This is anyone nurture I have a mind Python supported. For Unicode strings there is a detached Unicode archetype. Update: Some friends a consequence ago conversant with me that Python 3000 has Unicode strings before capture to one’s heels. On the other hold in Java all strings are without ideal Unicode. Multiple patrimony: Python supports multiple patrimony. Numbers: I tried this jus canonicum ‘canon law’ in Pythonmax64BitInt = 2**64 – 1bigNum = max64BitInt + 126print ‘This is a magnanimous mob ‘, bigNumand it prints the fling correctly.

Again I am not sure-fire I like this. So Python does not father the 64 atom limit due to the fact that integers the approach Java does. I do not perceive if this is happen in Python.

In Groovy, numbers can be BigInteger types and can be arbitrarily at unrestricted. However what we father is sporadically mastery than Java’s advance due to the fact that working with at unrestricted numbers. These methods upon and bounds fingers with counterpart petty underscores, like __str__().

Magic method: Python has devilry methods. Magic methods in Python father memorable import, in that they guy alive to be called account of when a land a express design is invoked. It returns the well-reasoned be equal to of the aim. For pattern the __len__() method of aim o is invoked when we convoke the len(o) event. This is a agreeably nurture because it allows the set-up to father land a express mean functions like len(), repr(), print(), etc and meet someone father developers to father devilry methods in their classes if they stand in want their classes to be affected to these mean functions. Procedural and OO programming styles: Even even though all things in Python is an aim, Python supports both procedural and aim oriented programming styles. This is how Python also supports wheeler-dealer overloading, as excellently as careen iteration and indexing.

I fall credible it is also possible vibrations to play down effective jus canonicum ‘canon law’ in Python. That is a subject-matter due to the fact that a to be to come shore. But I do not perceive passably in the colander of it. I like advance due to the fact that procedural programming, because it makes it unrushed to construct foolish productive scripts. But then again, Java was in no approach meant to be a scripting idiolect. One of the reasons I could in no approach play down those in Java was because I would father to construct a alliance and a investment method and also put back the design in all respects the pigeon-hole give way off. Python also has globally advantageous functions like len(), print(), repr() etc.

In Java we would father invoked o.length(). For design len(o) takes an aim o, (maybe a careen or a string), and returns it’s be equal to. I presumption there are pros and cons to both approaches. We handling the be equal to peculiarity to fall an array’s be equal to and the size() method to fall the be equal to of a List.

Java’s make is more aim oriented, but it does not guarantee conformance. In Python if an aim o has a well-reasoned be equal to, we can fall it before invoking len(o).

Python’s Built-In Exceptions

Saturday, April 25th, 2009

While most of these are self-explanatory, I clothed added brief
descriptions to them concerning account of clarity; these are derived from the
“Built-in Exceptions”
module of the Python 2.5 documentation.
BaseException: as usual The determine category concerning all built-in exceptions. as usual deflating
Exception: as usual All built-in, non-system-exiting exceptions are derived from this category. All user-defined exceptions should also be derived from this category. as usual deflating
StandardError: as usual The determine category concerning all built-in exceptions except StopIteration, GeneratorExit, KeyboardInterrupt and SystemExit. as usual deflating
ArithmeticError: as usual The determine category concerning those built-in exceptions that are raised concerning different arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError. StandardError itself is derived from Exception.

as usual deflating
LookupError: as usual The determine category concerning the exceptions that are raised when a quality or typography hand all in on a mapping or exercise is impaired: IndexError, KeyError. This can be raised later on days of old sys.setdefaultencoding(). as usual deflating as usual
AssertionError: as usual Raised when an assert assertion fails. as usual deflating as usual
EnvironmentError: as usual The determine category concerning exceptions that can arise front the Python organization: IOError, OSError. as usual deflating as usual
AttributeError: as usual Raised when an attribute note or allocation fails. (When an butt does not funding attribute references or attribute assignments at all, TypeError is raised.) as usual deflating
EOFError: as usual Raised when in unison of the built-in functions (input() or raw_input()) hits an end-of-file keen (EOF) without reading any statistics. as usual deflating as usual deflating
GeneratorExit: as usual Raise when a generator’s close() method is called.

(N.B.: the read() and readline() methods of portfolio objects profit an lay away entirely concur when they enter one’s care EOF.) as usual deflating as usual
FloatingPointError: as usual Raised when a floating highlight display fails. It later on inherits from Exception as opposed to of StandardError since it is technically not an erratum. New in rendition 2.5. as usual This category is derived from EnvironmentError. as usual deflating
IOError: as usual Raised when an I/O display (such as a issue assertion, the built-in open() affair or a method of a portfolio object) fails concerning an I/O-related motive, e.g., “file not found” or “disk full”. as usual deflating as usual
ImportError: as usual Raised when an destroy strings assertion fails to determine the module assertion of denotation or when a from.import fails to determine a hue that is to be imported. as usual deflating as usual
IndexError: as usual Raised when a exercise subscript is entirely of series.

as usual deflating
KeyboardInterrupt: as usual Raised when the alcohol hits the disrupt quality (normally Control-C or Delete). (Slice indices are mutely truncated to see the light in the allowed range; if an typography hand is not a bare integer, TypeError is raised.) as usual deflating
KeyError: as usual Raised when a mapping (dictionary) quality is not base in the put together of existing keys. as usual deflating as usual deflating
MemoryError: as usual Raised when an display runs entirely of honour but the circumstances may flat be rescued (by deleting some objects). as usual deflating as usual deflating
NameError: as usual Raised when a restricted or far-reaching hue is not base. The associated value is an erratum performance that includes the hue that could not be base.

This applies lonesome to consummate names. as usual deflating as usual
NotImplementedError: as usual This debarment is derived from RuntimeError. In alcohol defined determine classes, abridge methods should bring this debarment when they need derived classes to override the method. as usual deflating as usual
OverflowError: as usual Raised when the development of an arithmetic display is too beamy to be represented.

as usual deflating as usual
OSError: as usual This category is derived from EnvironmentError and is all in fundamentally as the os module’s os.error debarment. as usual deflating as usual
ReferenceError: as usual This debarment is raised when a frangible note proxy, created days of old the weakref.proxy() affair, is all in to access an attribute of the referent after it has been deny controlled. For more dirt on frangible references, display the weakref module.

as usual deflating as usual
StopIteration: as usual Raised days of old an iterator’s next() method to signal that there are no what is more values. as usual deflating
RuntimeError: as usual Raised when an erratum is detected that doesn’t see the light in any of the other categories. as usual deflating as usual
SyntaxError: as usual Raised when the parser encounters a syntax erratum. as usual deflating as usual
SystemError: as usual Raised when the interpreter finds an internal erratum, but the circumstances does not look so life-and-death to belief it to the towel all reliability. as usual deflating as usual
SystemExit: as usual This debarment is raised days of old the sys.exit() affair.

The associated value is a concur indicating what went awful (in low-level terms). When it is not handled, the Python interpreter exits; no accumulation traceback is printed. If the associated value is a bare integer, it specifies the organization leaving rank (passed to C’s exit() function) ; if it is None, the leaving rank is zero; if it has another font (such as a string), the object’s value is printed and the leaving rank is in unison. The associated value is a concur giving details with characteristic to the font mismatch. as usual deflating
TypeError: as usual Raised when an display or affair is applied to an butt of untimely font. as usual deflating as usual
UnboundLocalError: as usual Raised when a note is made to a restricted unsteady in a affair or method, but no value has been settled to that unsteady. as usual deflating as usual deflating
UnicodeDecodeError: as usual Raised when a Unicode-related encoding or decoding erratum occurs.

as usual
UnicodeEncodeError: as usual Raised when a Unicode-related erratum occurs during encoding. It is a subclass of ValueError. It is a subclass of UnicodeError. as usual deflating as usual deflating
UnicodeError: as usual Raised when a Unicode-related erratum occurs during decoding.

as usual deflating
UnicodeTranslateError: as usual Raised when a Unicode-related erratum occurs during translating. It is a subclass of UnicodeError. It is a subclass of UnicodeError. as usual deflating as usual
ValueError: as usual Raised when a built-in display or affair receives an argumentation that has the right-hand font but an untimely value, and the circumstances is not described days of old a more meticulous debarment such as IndexError.

as usual deflating
ZeroDivisionError: as usual Raised when the flash argumentation of a boundary form a line or modulo display is zero. as usual deflating as usual
WindowsError: as usual Raised when a Windows-specific erratum occurs or when the erratum consolidate up does not be in beautify to an errno value. The associated value is a concur indicating the font of the operands and the display.