Search This Blog

Thursday, May 16, 2024

Classical radicalism

From Wikipedia, the free encyclopedia
https://en.wikipedia.org/wiki/Classical_radicalism


Irish Classical Radical Thomas Francis Meagher
 
Radicalism (from French radical) was a political movement representing the leftward flank of liberalism during the late 18th and early 19th centuries and a precursor to social liberalism, social democracy, civil libertarianism, and modern progressivism. This ideology is commonly referred to as "radicalism" but is sometimes referred to as radical liberalism, or classical radicalism, to distinguish it from radical politics. Its earliest beginnings are to be found during the English Civil War with the Levellers and later the Radical Whigs.

During the 19th century in the United Kingdom, continental Europe and Latin America, the term radical came to denote a progressive liberal ideology inspired by the French Revolution. Radicalism grew prominent during the 1830s in the United Kingdom with the Chartists and in Belgium with the Revolution of 1830, then across Europe in the 1840s–1850s during the Revolutions of 1848. In contrast to the social conservatism of existing liberal politics, radicalism sought political support for a radical reform of the electoral system to widen suffrage. It was also associated with a variety of ideologies and policies, such as liberalism, left-wing politics, republicanism, modernism, secular humanism, antimilitarism, civic nationalism, abolition of titles, rationalism, secularism, redistribution of property and freedom of the press.

In 19th-century France, radicalism was originally the extreme left of the day, in contrast to the social-conservative liberalism of Moderate Republicans and Orléanist monarchists and the anti-parliamentarianism of the Legitimists and Bonapartists. Until the end of the century, radicals were not organised as a united political party, but they had rather become a significant force in parliament. In 1901, they consolidated their efforts by forming the country's first major extra-parliamentary political party, the Republican, Radical and Radical-Socialist Party, which became the leading party of government during the second half of the French Third Republic (until 1940). The success of French Radicals encouraged radicals elsewhere to organize themselves into formal parties in a range of other countries in the late 19th and early 20th century, with radicals holding significant political office in Bulgaria (Radical Democratic Party), Denmark (Venstre), Germany (Progressive People's Party and German Democratic Party), Greece (New Party and Liberal Party), Italy (Republican Party, Radical Party, Social Democracy and Democratic Liberal Party), the Netherlands (Radical League and Free-thinking Democratic League), Portugal (Republican Party), Romania (National Liberal Party), Russia (Trudoviks), Serbia (People's Radical Party), Spain (Reformist Party, Radical Republican Party, Republican Action, Radical Socialist Republican Party and Republican Left), Sweden (Free-minded National Association, Liberal Party and Liberal People's Party), Switzerland (Free Democratic Party), and Turkey (Republican People's Party). During the interwar period, European radical parties organized the Radical Entente, their own political international.

Before socialism emerged as a mainstream political ideology, radicalism represented the left-wing of liberalism and, thus, of the political spectrum. As social democracy came to dominate the centre-left and supplanted socialism, radicals either re-positioned as conservative liberals or joined forces with social democrats. Thus, European radical parties split (as in Denmark, where Venstre undertook a conservative-liberal rebranding, while Radikale Venstre maintained the radical tradition), took up a new orientation (as in France, where the Radical Party aligned with the centre-right, later causing the split of the Radical Party of the Left) or dissolved (as in Greece, where the heirs of Venizelism joined several parties). After World War II, European radicals were largely extinguished as a major political force except in Denmark, France, Italy (Radical Party) and the Netherlands (Democrats 66). Latin America still retains a distinct indigenous radical tradition, for instance in Argentina (Radical Civic Union) and Chile (Radical Party).

Overview

Radicalism and liberalism

The two Enlightenment philosophies of liberalism and radicalism both shared the goal of liberating humanity from traditionalism. However, liberals regarded it as sufficient to establish individual rights that would protect the individual while radicals sought institutional, social/economic, and especially cultural/educational reform to allow every citizen to put those rights into practice. For this reason, radicalism went beyond the demand for liberty by seeking also equality, i.e. universality as in Liberté, Égalité, Fraternité.

In some countries, radicalism represented a minor wing within the Liberal political family, as in the case of England's Radical Whigs. Sometimes, the radical wing of the liberals were hardline or doctrinaire and in other cases more moderate and pragmatic. In other countries, radicalism had had enough electoral support on its own, or a favourable electoral system or coalition partners, to maintain distinct radical parties such as in Switzerland and Germany (Freisinn), Bulgaria, Denmark, Italy, Spain and the Netherlands, but also Argentina (Radical Civic Union), Chile and Paraguay.

Victorian era Britain possessed both trends: In England the Radicals were simply the left wing of the Liberal coalition, though they often rebelled when the coalition's socially conservative Whigs resisted democratic reforms, whereas in Ireland Radicals lost faith in the ability of parliamentary gradualism to deliver egalitarian and democratic reform and, breaking away from the main body of liberals, pursued a radical-democratic parliamentary republic through separatism and insurrection. This does not mean that all radical parties were formed by left-wing liberals. In French political literature, it is normal to make a clear separation between Radicalism as a distinct political force to the left of Liberalism but to the right of Socialism. Over time, as new left-wing parties formed to address the new social issues, the right wing of the Radicals would splinter off in disagreement with the main Radical family and became absorbed as the left wing of the Liberal family—rather than the other way around, as in Britain and Belgium.

The distinction between Radicals and Liberals was made clear by the two mid-20th-century attempts to create an international for centrist democratic parties. In 1923–24, the French Radicals created an Entente Internationale des Partis Radicaux et des Partis Démocratiques similaires: it was joined by the centre-left Radical parties of Europe, and in the democracies where no equivalent existed—Britain and Belgium—the liberal party was to allowed attend instead. After the Second World War the Radical International was not reformed; instead, a centre-right Liberal International was established, closer to the conservative-liberalism of the British and Belgian Liberal parties. This marked the end of Radicalism as an independent political force in Europe, though some countries such as France and Switzerland retained politically-important Radical parties well into the 1950s–1960s. Many European parties that are nowadays categorised in the group of social-liberal parties have a historical affinity with radicalism and may therefore be called "liberal-radical".

By country

United Kingdom

Jeremy Bentham

According to Encyclopædia Britannica, the first use of the term radical in a political sense is generally ascribed to the English parliamentarian Charles James Fox, a leader of the left wing of the Whig party who dissented from the party's conservative-liberalism and looked favourably upon the radical reforms being undertaken by French republicans, such as universal male suffrage. In 1797, Fox declared for a "radical reform" of the electoral system. This led to a general use of the term to identify all supporting the movement for parliamentary reform.

Initially confined to the upper and middle classes, in the early 19th century "popular radicals" brought artisans and the "labouring classes" into widespread agitation in the face of harsh government repression. More respectable "philosophical radicals" followed the utilitarian philosophy of Jeremy Bentham and strongly supported parliamentary reform, but were generally hostile to the arguments and tactics of the "popular radicals". By the middle of the century, parliamentary Radicals joined with others in the Parliament of the United Kingdom to form the Liberal Party, eventually achieving reform of the electoral system.

Origins

The Radical movement had its beginnings at a time of tension between the American colonies and Great Britain, with the first Radicals, angry at the state of the House of Commons, drawing on the Leveller tradition and similarly demanding improved parliamentary representation. These earlier concepts of democratic and even egalitarian reform had emerged in the turmoil of the English Civil War and the brief establishment of the republican Commonwealth of England amongst the vague political grouping known as the Levellers, but with the English Restoration of the monarchy such ideas had been discredited. Although the Glorious Revolution of 1688 had increased parliamentary power with a constitutional monarchy and the union of the parliaments brought England and Scotland together, towards the end of the 18th century the monarch still had considerable influence over the Parliament of Great Britain which itself was dominated by the English aristocracy and by patronage. Candidates for the House of Commons stood as Whigs or Tories, but once elected formed shifting coalitions of interests rather than splitting along party lines. At general elections, the vote was restricted to property owners in constituencies which were out of date and did not reflect the growing importance of manufacturing towns or shifts of population, so that in many rotten borough seats could be bought or were controlled by rich landowners while major cities remained unrepresented. Discontent with these inequities inspired those individuals who later became known as the "Radical Whigs".

William Beckford fostered early interest in reform in the London area. The "Middlesex radicals" were led by the politician John Wilkes, an opponent of war with the colonies who started his weekly publication The North Briton in 1764 and within two years had been charged with seditious libel and expelled from the House of Commons. The Society for the Defence of the Bill of Rights which he started in 1769 to support his re-election, developed the belief that every man had the right to vote and "natural reason" enabling him to properly judge political issues. Liberty consisted in frequent elections and for the first time middle-class radicals obtained the backing of the London "mob". Middlesex and Westminster were among the few parliamentary constituencies with a large and socially diverse electorate including many artisans as well as the middle class and aristocracy and along with the county association of Yorkshire led by the Reverend Christopher Wyvill were at the forefront of reform activity. The writings of what became known as the "Radical Whigs" had an influence on the American Revolution.

Major John Cartwright also supported the colonists, even as the American Revolutionary War began and in 1776 earned the title of the "Father of Reform" when he published his pamphlet Take Your Choice! advocating annual parliaments, the secret ballot and manhood suffrage. In 1780, a draft programme of reform was drawn up by Charles James Fox and Thomas Brand Hollis and put forward by a sub-committee of the electors of Westminster. This included calls for the six points later adopted in the People's Charter (see Chartists below).

The American Revolutionary War ended in humiliating defeat of a policy which King George III had fervently advocated and in March 1782 the King was forced to appoint an administration led by his opponents which sought to curb Royal patronage. In November 1783, he took his opportunity and used his influence in the House of Lords to defeat a Bill to reform the British East India Company, dismissed the government and appointed William Pitt the Younger as his Prime Minister. Pitt had previously called for Parliament to begin to reform itself, but he did not press for long for reforms the King did not like. Proposals Pitt made in April 1785 to redistribute seats from the "rotten boroughs" to London and the counties were defeated in the House of Commons by 248 votes to 174.

Popular agitation

Mary Wollstonecraft

In the wake of the French Revolution of 1789, Thomas Paine wrote The Rights of Man (1791) as a response to Edmund Burke's counterrevolutionary essay Reflections on the Revolution in France (1790), itself an attack on Richard Price's sermon that kicked off the so-called "pamphlet war" known as the Revolution Controversy. Mary Wollstonecraft, another supporter of Price, soon followed with A Vindication of the Rights of Woman. They encouraged mass support for democratic reform along with rejection of the monarchy, aristocracy and all forms of privilege. Different strands of the movement developed, with middle class "reformers" aiming to widen the franchise to represent commercial and industrial interests and towns without parliamentary representation, while "Popular radicals" drawn from the middle class and from artisans agitated to assert wider rights including relieving distress. The theoretical basis for electoral reform was provided by "Philosophical radicals" who followed the utilitarian philosophy of Jeremy Bentham and strongly supported parliamentary reform, but were generally hostile to the arguments and tactics of the "popular radicals".

In Ireland, the United Irishmen movement took another direction, adding to the doctrine of a secular and parliamentary republic inspired by the American and French republican revolutions, another doctrine of the French Revolution: civic nationalism. Dismayed by the inability of British parliamentarianism to introduce the root-and-branch democratic reforms desired, Irish Radicals channelled their movement into a republican form of nationalism that would provide equality as well as liberty. This was pursued through armed revolution and often with French assistance at various points over the late eighteenth and nineteenth centuries.

Popular Radicals were quick to go further than Paine, with Newcastle schoolmaster Thomas Spence demanding land nationalisation to redistribute wealth in a penny periodical he called Pig's Meat in a reference to Burke's phrase "swinish multitude". Radical organisations sprang up, such as the London Corresponding Society of artisans formed in January 1792 under the leadership of the shoemaker Thomas Hardy to call for the vote. One such was the Scottish Friends of the People society which in October 1793 held a British convention in Edinburgh with delegates from some of the English corresponding societies. They issued a manifesto demanding universal male suffrage with annual elections and expressing their support for the principles of the French Revolution. The numbers involved in these movements were small and most wanted reform rather than revolution, but for the first time working men were organising for political change.

The government reacted harshly, imprisoning leading Scottish radicals, temporarily suspending habeas corpus in England and passing the Seditious Meetings Act 1795 which meant that a license was needed for any meeting in a public place consisting of fifty or more people. Throughout the Napoleonic Wars, the government took extensive stern measures against feared domestic unrest. The corresponding societies ended, but some radicals continued in secret, with Irish sympathisers in particular forming secret societies to overturn the government and encourage mutinies. In 1812, Major John Cartwright formed the first Hampden Club, named after the English Civil War Parliamentary leader John Hampden, aiming to bring together middle class moderates and lower class radicals.

After the Napoleonic Wars, the Corn laws (in force between 1815 and 1846) and bad harvests fostered discontent. The publications of William Cobbett were influential and at political meetings speakers like Henry Hunt complained that only three men in a hundred had the vote. Writers like the radicals William Hone and Thomas Jonathan Wooler spread dissent with publications such as The Black Dwarf in defiance of a series of government acts to curb circulation of political literature. Radical riots in 1816 and 1817 were followed by the Peterloo massacre of 1819 publicised by Richard Carlile, who then continued to fight for press freedom from prison. The Six Acts of 1819 limited the right to demonstrate or hold public meetings. In Scotland, agitation over three years culminated in an attempted general strike and abortive workers' uprising crushed by government troops in the "Radical War" of 1820. Magistrates powers were increased to crush demonstrations by manufacturers and action by radical Luddites.

To counter the established Church of England doctrine that the aristocratic social order was divinely ordained, radicals supported Lamarckian Evolutionism, a theme proclaimed by street corner agitators as well as some established scientists such as Robert Edmund Grant.

Political reform

Economic conditions improved after 1821 and the United Kingdom government made economic and criminal law improvements, abandoning policies of repression. In 1823, Jeremy Bentham co-founded the Westminster Review with James Mill as a journal for "philosophical radicals", setting out the utilitarian philosophy that right actions were to be measured in proportion to the greatest good they achieved for the greatest number. Westminster elected two radicals to Parliament during the 1820s.

The Whigs gained power and despite defeats in the House of Commons and the House of Lords the Reform Act 1832 was put through with the support of public outcry, mass meetings of "political unions" and riots in some cities. This now enfranchised the middle classes, but failed to meet radical demands. The Whigs introduced reforming measures owing much to the ideas of the philosophic radicals, abolishing slavery and in 1834 introducing Malthusian Poor Law reforms which were bitterly opposed by "popular radicals" and writers like Thomas Carlyle. Following the 1832 Reform Act, the mainly aristocratic Whigs in the House of Commons were joined by a small number of parliamentary Radicals as well as an increased number of middle class Whigs. By 1839, they were informally being called "the Liberal party".

Chartists

Flyer for the Chartist demonstration on Kennington Common, 1848

From 1836, working class Radicals unified around the Chartist cause of electoral reform expressed in the People's Charter drawn up by six members of Parliament and six from the London Working Men's Association (associated with Owenite Utopian socialism), which called for six points: universal suffrage, equal-sized electoral districts, secret ballot, an end to property qualification for Parliament, pay for Members of Parliament and Annual Parliaments. Chartists also expressed economic grievances, but their mass demonstrations and petitions to parliament were unsuccessful.

Despite initial disagreements, after their failure their cause was taken up by the middle class Anti-Corn Law League founded by Richard Cobden and John Bright in 1839 to oppose duties on imported grain which raised the price of food and so helped landowners at the expense of ordinary people.

Liberal reforms

The parliamentary Radicals joined with the Whigs and anti-protectionist Tory Peelites to form the Liberal Party by 1859. Demand for parliamentary reform increased by 1864 with agitation from John Bright and the Reform League.

When the Liberal government led by Lord Russell and William Ewart Gladstone introduced a modest bill for parliamentary reform, it was defeated by both Tories and reform Liberals, forcing the government to resign. The Tories under Lord Derby and Benjamin Disraeli took office and the new government decided to "dish the Whigs" and "take a leap in the dark" to take the credit for the reform. As a minority government, they had to accept radical amendments and Disraeli's Reform Act 1867 almost doubled the electorate, giving the vote even to working men.

The Radicals, having been strenuous in their efforts on behalf of the working classes, earned a deeply loyal following—British trade unionists from 1874 until 1892, upon being elected to Parliament, never considered themselves to be anything other than Radicals and were labeled Lib-Lab candidates. Radical trade unionists formed the basis for what later became the Labour Party.

Belgium

The territories of modern Belgium had been merged into the Kingdom of the Netherlands in 1815. Aside from various religious and socioeconomic tensions between the Dutch north and proto-Belgian south, over the 1820s a young generation of Belgians, heavily influenced by French Enlightenment ideas, had formulated criticisms of the Dutch monarchy as autocratic. The monarch enjoyed broad personal powers, his ministers were irresponsible before parliament; the separation of powers was minimal; freedom of press and association were limited; the principle of universal suffrage was undermined by the fact that the largely Catholic south, despite possessing two-thirds of the population, received as many seats to the Estates-General (parliament) as the smaller Protestant north; and the Dutch authorities were suspected of forcing Protestantism onto Catholics. These concerns combined to produce a pro-Catholic Radicalism distinct from both the anticlerical Radicalism of France, and the Protestant Liberalism of the Dutch north.

Following the political crisis of 1829, where the Crown Prince was named prime minister, a limited reform was introduced establishing constitutional rights, similar to the charter of rights of France's autocratic Restoration Monarchy; the Belgian Radicals, like their French counterparts, regarded such a charter of rights as insufficient, potentially revocable by a whim of the monarch. Belgian Radicals closely followed the situation in France when, on 26 July to 1 August 1830, a conservative-liberal revolution broke out, overthrowing the autocratic monarchy for a liberal constitutional monarchy. Within a month a revolt had erupted in Brussels before spreading to the rest of the Belgian provinces. After Belgian independence, the Constitution of 1831 established a constitutional monarchy and parliamentary regime, and provided a list of fundamental civil rights inspired by the French Declaration of the Right of Man.

As in Britain, Radicals in Belgium continued to operate within the Liberal Party, campaigning throughout the 19th Century for the property-restricted suffrage to be extended. This was extended a first time in 1883, and universal male suffrage was achieved in 1893 (though female suffrage would have to wait until 1919). After this Radicalism was a minor political force in Belgium, its role taken over by the emergence of a powerful social-democratic party.

France

Maximilien François Marie Isidore de Robespierre. He belonged to The Mountain of the Jacobin Club, a radical force during the French Revolution.

During the nineteenth century, the Radicals in France were the political group of the far-left, relative to the centre-left "opportunists" (Gambetta: conservative-liberal and republican), the centre-right Orléanists (conservative-liberal and monarchist), the far-right Legitimists (anti-liberal monarchist), and the supporters of a republican military dictatorship, the Bonapartists.

Following the Napoleonic Wars and until 1848, it was technically illegal to advocate republicanism openly. Some republicans reconciled themselves to pursuing liberalism through the socially-conservative monarchy—the 'opportunists'. Those who remained intransigent in believing that the French Revolution needed to be completed through a republican regime based on parliamentary democracy and universal suffrage therefore tended to call themselves "Radicals" – a term meaning 'Purists'.

Under the Second Republic (1848–1852), the Radicals, on a platform of seeking a "social and democratic republic", sat together in parliament in a group named The Mountain. When Louis-Napoléon Bonaparte launched his military coup, Radicals across France rose up in insurrection to defend the democratic republic. This experience would mark French Radicalism for the next century, prompting permanent vigilance against all those who – from Marshall Mac-Mahon to General De Gaulle – were suspected of seeking to overthrow the constitutional, parliamentary regime.

After the return to parliamentary democracy in 1871, the Radicals emerged as a significant political force: led by Georges Clemenceau, they claimed that the socially-conservative liberal republicanism of Léon Gambetta and Jules Ferry had drifted away from the ideals of the French Revolution, and that the Radicals were the true heirs to 1791. In 1881, they put forward their programme of broad social reforms: from then on, the tactic of the main Radical Party was to have 'no enemies to the left' of the Republic, allying with any group that sought social reform while accepting the legality of the parliamentary republic.

Georges Eugène Benjamin Clemenceau

The Radicals were not yet a political party as they sat together in parliament out of kinship, but they possessed minimal organisation outside of parliament. The first half of the Third Republic saw several events that caused them to fear a far-right takeover of parliament that might end democracy, as Louis-Napoléon had: Marshall Mac-Mahon's self-coup in 1876, the General Boulanger crisis in the 1880s, the Dreyfus Affair in the 1890s. The Radicals were swept to power first in a coalition government (1899) then in governments of their own from 1902. They finally managed to implement their long-standing programme of reforms, such as the separation of Church and State, or the introduction of secret ballotting. In order to ensure that their legacy would remain unreversed, they unified the local Radical committees into an elector party: the Radical-Socialist Party, the first major modern political party in French history.

Intellectuals played a powerful role. A major spokesman of radicalism was Émile Chartier (1868–1951), who wrote under the pseudonym "Alain." He was a leading theorist of radicalism, and his influence extended through the Third and Fourth Republics. He stressed individualism, seeking to defend the citizen against the state. He warned against all forms of power – military, clerical, and economic. To oppose them he exalted the small farmer, the small shopkeeper, the small town, and the little man. He idealized country life and saw Paris as a dangerous font of power.

The Radical–Socialist Party was the main governmental party of the Third Republic between 1901 and 1919, and dominated government again between 1924 and 1926, 1932–1933 and 1937–1940; the centre-right governments dominated by the conservative-liberal centre-right often gave a portfolio to a Radical, who would join cabinet in a personal capacity as the most left-leaning minister.

The party itself was discredited after 1940, due to fact that many (though not all) of its parliamentarians had voted to establish the Vichy regime. Under the dictatorship several prominent Radicals, such as the young left-leaning former education minister Jean Zay, and the influential editorialist Maurice Sarraut (brother to the more famous Radical party leader Albert), were assassinated by the regime's paramilitary police, while others, notably Jean Moulin, participated in the resistance movement to restore the Republic.

The Democratic and Socialist Union of the Resistance was established after World War II to combine the politics of French Radicalism with credibility derived from members' activism in the French resistance.

In the 1950s, Pierre Mendès-France attempted to rebuild the Radical Party as an alternative to both the Christian-democratic MRP, while also leading the opposition to Gaullism which he feared to be another attempt at a right-wing coup. During this period the Radicals frequently governed as part of a coalition of centrist parties, spanning from the Socialists to the Christian-democrats.

Ultimately the installation of the Fifth Republic in 1958, and the subsequent emergence of a two-party system based on the Socialist and Gaullist movements, destroyed the niche for an autonomous Radical party. The Radical Party split into various tendencies. Its leading personality, Mendès-France himself, left in 1961 in protest at the party's acceptance of De Gaulle's military coup and joined the small social-democratic Unified Socialist Party. A decade later, a second faction advocated maintaining an alliance with the Socialist-dominated coalition of the left; it broke away in 1972 to form the Radical Party of the Left, which maintains close ties to the Socialist Party. The remainder of the original Radical Party became a de facto liberal-conservative party of the centre-right: renamed as the 'Valoisien' Radical Party, it advocated alliances with the rest of the liberal centre-right, participating first in the pro-Giscard d'Estaing Union for French Democracy (1972), then with the conservative Union for a Popular Movement (2002).

Ireland

Irish republicanism was influenced by French radicalism. Typical of these classical Radicals are 19th century such as the United Irishmen in the 1790s, Young Irelanders in the 1840s, Fenian Brotherhood in the 1880s, as well as Sinn Féin, and Fianna Fáil in the 1920s.

Japan

Japan's radical-liberalism during the Empire of Japan was dissident because it resisted the government's political oppression of republicanism. Rikken Minseitō, who supported the Empire of Japan's system at the time, were classified as "conservative". Therefore, the radical liberal movement during the Japanese Empire was not separated from socialism and anarchism unlike the West at that time. Kōtoku Shūsui was a representative Japanese radical liberal.

After World War II, Japan's left-wing liberalism emerged as a "peace movement" and was largely led by the Japan Socialist Party.

Since Japanese conservatism was influenced by Shintoism, Japan's radical liberalism and democratic socialism against it were influenced by Christianity.

Korea

United States

One of the trends of the American radical movement was the Jacksonian democracy, which advocated political egalitarianism among white men.

Radicalism was represented by the Radical Republicans, especially the Stalwarts, more commonly known as Radical Republican. A collection of abolitionist and democratic reformers, some of whom were fervent supporters of trade unionism and in opposition to wage labor such as Benjamin Wade.

Later political expressions of classical Radicalism centered around the Populist Party, composed of rural western and southern farmers who were proponents of policies such as railroad nationalization, free silver, expansion of voting rights and labor reform.

Continental Europe and Latin America

In continental Europe and Latin America, as for instance in France, Italy, Spain, Chile and Argentina (Radical Civic Union), Radicalism developed as an ideology in the 19th century to indicate those who supported at least in theory a republican form of government, universal male suffrage and, particularly, anti-clerical policies.

In German-speaking countries, this current is known as Freisinn (literally "free mind", or "freethought"), as in German Freeminded Party from 1884 to 1893, then Eugen Richter's Freeminded People's Party; and the Free Democratic Party of Switzerland.

The Freethinker parties, located mainly in the Netherlands, Scandinavia and German-speaking countries, included:

  • In Switzerland:
    • The Radical movement (or "Free-thinking" movement in the German-speaking cantons), not yet a political party, emerged during the period of Regeneration, starting 1830 (coincident with the French July Revolution). It became the dominant political force under the 1848 Constitution, holding all seven posts in the Federal Council until 1891.
    • The Radical-Democratic Party (PRD; in French-speaking Switzerland), also known as the Free-minded Democratic Party (FDP; in German-speaking Switzerland) existed from 1894 to 2009. It started as a centre-left party but gradually moved to the centre-right in the course of time. It was still by far the strongest party until the 1940s, holding at least four of seven posts in the Federal Council. Under the 1959 "magic formula" it held two of seven posts in the Federal Council.
    • The Radical-Liberal Party (PLR), or FDP. The Liberals (in the German-speaking regions), was formed in 2009 by the merger of PRD/FDP with the smaller, more right-leaning Liberal Party of Switzerland.
  • In the Netherlands:
  • In Germany, a succession of Radical parties existed:
  • In Austria, liberalism was originally closely related to German nationalism but later split:
    • liberal-nationalist Progressive Club (1873–1881).
    • United Left (1881–1888).
    • United German Left (1888–1897)
    • German Progressive Party (1896–1910).
    • Centrist Democrats, Democratic Middle-class Party, Democratic Economic Party and Economic People's Party (c. 1919)
    • Civic Workers' Party (1920–1927)
    • Democratic List (1927)
  • Branches of German and Austrian formed new parties in aftermath of World War I
  • In Denmark:
    • The current Liberal Party began as a radical party in 1870, hence its name in Danish (Venstre, meaning 'Left'). When it became more conservative, the Radical wing split in 1905 to form a new party, known as Radikale Venstre ('Radical Left').
  • In Norway:
    • The current Liberal Party began as a radical party in 1884, hence its name in Norwegian (Venstre, meaning 'Left').

In Mediterranean Europe, Radical parties were often labelled 'Democratic' or 'Republican' parties:

  • In France, during the nineteenth and the first half of the twentieth century, radicalism was intertwined with republicanism to the point that radical parties were often simply labelled 'republicans'. The election of Alexandre Ledru-Rollin in 1841 is generally considered the start of the radical-republican movement as a political force in France. Over the next century a pattern emerged of Radicals forming a party on the left of the parliamentary spectrum (but to the right of socialists), only for the party to drift to the centre, which would cause the party's left to splinter off and re-establish a new main Radical party while the weakened parent party was eventually absorbed by the liberal centre. This meant that there were generally two rival Radical parties at any one time, one leaning relatively towards socialism, and the other relatively towards liberalism.
    • La Montagne (The Mountain) (1848–1851) was the first parliamentary group to provide a home for France's miscellaneous radical republicans. Its official name, the Socialist Democrat group, signalled its two tendencies: the more socialist-leaning tendency of Louis Blanc, and the more middle-class democratic-reformist tendency of Alexandre Ledru-Rollin. At that time it represented a very small political current situated on the far-left of the parliamentary spectrum.
    • The Republican Union (1871–1884), led by Léon Gambetta, was the Mountain's spiritual successor during the transition to democracy; its members included former parliamentarians of the Montagne such as Louis Blanc, and prominent Radical intellectuals like Victor Hugo. A minor force at first, by 1876 it had grown in parliamentary strength but begun to drift towards centrist cooperation with liberal Catholics; this prompted the party's more fervent radicals to splinter off in several waves and form new Radical parties (Georges Clemenceau in 1876; René Goblet's Radical Left in 1881; Isambart's Progressive Union in 1894).
    • The Progressive Union (1894–1902) was originally a splinter of the Republican Union by left-leaning radicals during the Dreyfus Affair. In 1902 the formation of the major new Radical-Socialist Party to its immediate left forced it to pick a political family, and it chose to ally then merge with other centrist parties to form the politically-liberal Republican Democratic Alliance.
    • Radical Left (1881–1940), a parliamentary group initially formed by hardline anticlerical radicals dissatisfied with the Republican Union's centrism. It was a major political force in centre-left and centrist governments between 1898 and 1918, and regularly provided ministers in centrist and right-wing governments between 1918 and 1940; the importance of this current was underlined by its leader, the veteran Radical Georges Clemenceau, being called to lead the war government during the First World War. The foundation of the PRRRS to its left in 1901 pushed it one space towards the centre and it increasingly drifted into alliance with the liberal republican centre-right. By 1918 it was de facto a party of the centre-right, and from 1936 was essentially absorbed by the liberal right, its old political niche taken over by the PRRRS.
    • The Radical-Socialist Party (officially the Radical, Republican and Radical-Socialist Party or PRRRS), the most famous of France's many radical parties. It was the dominant political force in France from 1901 to 1919, and a major force from 1920 to 1940. Due to its central political role it could alternate in and out of alliance with both socialists and with conservative-liberals; this prompted several splinters by the party's most left- and right-wing members:
    • Centrist and centre-right Radical splinters: The Social and Unionist Radical Party (1928–37) was a small splinter of anti-socialist radicals from the PRRRS, led by Henry Franklin-Bouillon, who preferred to ally with the centrist Radical Left and other liberal right wing parties. The French Radical Party (1937–1938) was a similar small anti-communist splinter, led by André Grisoni. These two small groups merged in 1938 as the short-lived Independent Radical Party, which was itself restored after the Second World War and was a founding organisation of the Alliance of Left Republicans.
    • Independent Radical Party (1937–1940), a merger of the Unionist Radical Party and the French Radical Party.
    • Social-democratic Radical splinters: The Republican-Socialist Party (1911–1935) and the French Socialist Party (1923–1935) were two small parties formed of left-wing Radicals philosophically close to social-democracy or rightwing social-democrats philosophically close to Radicalism, but unable or unwilling to join either the official socialist party or the PRRRS. Although electorally small, they were a significant political force as they regularly provided ministers and heads of government in left-wing and centrist coalitions. They merged with other social-democratic parties and independents in 1935 as the Socialist Republican Union.
    • The Camille Pelletain Radical Party, a small splinter of anti-fascists from the PRRRS that briefly existed between 1934–1936. The party opposed the willingness by the PRRRS's party leaders during 1934-35 to prefer cooperation with the right and far-right rather than with other left-wing parties. Its name was a reference to a leading historical figure of left-wing Radicalism, Camile Pelletain, as a way to lay claim to an authentic Radical tradition felt to have been abandoned by the official party. Once the PRRRS returned to allying with the rest of the left in 1936, the Pelletanist Radicals returned to the old party.
    • After the Second World War, the pre-war Radical-Socialist Party, Radical Left party and their smaller counterparts were left discredited and weakened as communism, social-democracy, Christian-democracy and Gaullism exploded in popularity. The remaining Radicals mostly banded together with the remnants of other pre-war liberal parties to form a centre-right umbrella party named the Rally of the Republican Left: this was no longer distinctly Radical in ideology, but espoused laissez-faire parliamentary liberal-democracy. In 2017 the Radical-Socialist Party merged with the Radical Party of the Left to form the Radical Movement.
  • In Spain, Radicalism took the form of various 'democratic', 'progressive', 'republican' and 'radical' parties.
  • In Italy:
    Giuseppe Mazzini. His thoughts influenced many politicians of a later period, among them Woodrow Wilson, David Lloyd George, Mahatma Gandhi, Golda Meir and Jawaharlal Nehru.

Serbia and Montenegro

Radicalism had played a pivotal role in the birth and development of parliamentarism and the construction of the modern Serbian state leading to the Yugoslavian unification. The People's Radical Party formed in 1881 was the strongest political party and was in power in the Kingdom of Serbia more than all others together. The 1888 Constitution of the Kingdom of Serbia that defined it as an independent nation and formalised parliamentary democracy was among the most advanced in the entire world due to Radical contribution and it is known as The Radical Constitution. In 1902, a crack had occurred in which the Independent Radical Party left and "the Olde" remained in the party, leading the original People's Radical Party to stray far from progressivism and into right-wing nationalism and conservatism. In the Kingdom of Yugoslavia, the Independent Radicals united with the rest of the Serbian opposition and the liberal and civic groups in the rest of the new country, forming the Yugoslav Democratic Party, while several Republican dissidents formed a Republican Party. The NRS had promoted Serb nationalism and put itself as the defender of Serb national interests. Democrats and Radicals were the dominant political parties, especially since the exclusion of the Communists. Later far-right parties such as the Yugoslav Radical Union and the Serbian Radical Party adopted the title "radical" as allusion to NRS.

In Montenegro, a People's Party was formed in 1907 as the country's first political party and remained the largest in the period of country's parliamentary history until the Yugoslavian unification. Later, a True People's Party was formed, which never got widespread popular support and whose bigger part had joined the original NS, but the difference was not ideological and instead was opposition and support of the Crown and sometimes in foreign relations to Serbia (the clubbists were the crown's dissidents and supporters of the people as well as Serbia as a regional power and brotherly ally—the rightists were generally anti-democratic and autocratic monarchist and also distrustful to the Serbian government's acts on the national plan).

Python syntax and semantics

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers). The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. It supports multiple programming paradigms, including structured, object-oriented programming, and functional programming, and boasts a dynamic type system and automatic memory management.

Python's syntax is simple and consistent, adhering to the principle that "There should be one— and preferably only one —obvious way to do it." The language incorporates built-in data types and structures, control flow mechanisms, first-class functions, and modules for better code reusability and organization. Python also uses English keywords where other languages use punctuation, contributing to its uncluttered visual layout.

The language provides robust error handling through exceptions, and includes a debugger in the standard library for efficient problem-solving. Python's syntax, designed for readability and ease of use, makes it a popular choice among beginners and professionals alike.

Design philosophy

Python was designed to be a highly readable language. It has a relatively uncluttered visual layout and uses English keywords frequently where other languages use punctuation. Python aims to be simple and consistent in the design of its syntax, encapsulated in the mantra "There should be one— and preferably only one —obvious way to do it", from the Zen of Python.

This mantra is deliberately opposed to the Perl and Ruby mantra, "there's more than one way to do it".

Keywords

Python has 35 keywords or reserved words; they cannot be used as identifiers.

  • and
  • as
  • assert
  • async
  • await
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • False
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • None
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • True
  • try
  • while
  • with
  • yield

In addition, Python also has 3 soft keywords. Unlike regular hard keywords, soft keywords are reserved words only in the limited contexts where interpreting them as keywords would make syntactic sense. These words can be used as identifiers elsewhere; You can define a function or variable named match or case.

Notes

  • async and await were introduced in Python 3.5.

  • True and False became keywords in Python 3.0. Previously they were global variables.

  • nonlocal was introduced in Python 3.0.

    1. match, case and _ were introduced as keywords in Python 3.10.

    Indentation

    Python uses whitespace to delimit control flow blocks (following the off-side rule). Python borrows this feature from its predecessor ABC: instead of punctuation or keywords, it uses indentation to indicate the run of a block.

    In so-called "free-format" languages—that use the block structure derived from ALGOL—blocks of code are set off with braces ({ }) or keywords. In most coding conventions for these languages, programmers conventionally indent the code within a block, to visually set it apart from the surrounding code.

    A recursive function named foo, which is passed a single parameter, x, and if the parameter is 0 will call a different function named bar and otherwise will call baz, passing x, and also call itself recursively, passing x-1 as the parameter, could be implemented like this in Python:

    def foo(x):
        if x == 0:
            bar()
        else:
            baz(x)
            foo(x - 1)
    

    and could be written like this in C with K&R indent style:

    void foo(int x)
    {
        if (x == 0) {
            bar();
        } else {
            baz(x);
            foo(x - 1);
        }
    }
    

    Incorrectly indented code could be misread by a human reader differently than it would be interpreted by a compiler or interpreter. For example, if the function call foo(x - 1) on the last line in the example above was erroneously indented to be outside the if/else block:

    def foo(x):
        if x == 0:
            bar()
        else:
            baz(x)
        foo(x - 1)
    

    it would cause the last line to always be executed, even when x is 0, resulting in an endless recursion.

    While both space and tab characters are accepted as forms of indentation and any multiple of spaces can be used, spaces are recommended and 4 spaces (as in the above examples) are recommended and are by far the most commonly used. Mixing spaces and tabs on consecutive lines is not allowed starting with Python 3 because that can create bugs which are difficult to see, since many text editors do not visually distinguish spaces and tabs.

    Data structures

    Since Python is a dynamically-typed language, Python values, not variables, carry type information. All variables in Python hold references to objects, and these references are passed to functions. Some people (including Guido van Rossum himself) have called this parameter-passing scheme "call by object reference". An object reference means a name, and the passed reference is an "alias", i.e. a copy of the reference to the same object, just as in C/C++. The object's value may be changed in the called function with the "alias", for example:

    >>> alist = ['a', 'b', 'c']
    >>> def my_func(al):
    ...     al.append('x')
    ...     print(al)
    ...
    >>> my_func(alist)
    ['a', 'b', 'c', 'x']
    >>> alist
    ['a', 'b', 'c', 'x']
    

    Function my_func changes the value of alist with the formal argument al, which is an alias of alist. However, any attempt to operate (assign a new object reference to) on the alias itself will have no effect on the original object.

    >>> alist = ['a', 'b', 'c']
    >>> def my_func(al):
    ...     # al.append('x')
    ...     al = al + ['x'] # a new list created and assigned to al means al is no more alias for alist
    ...     print(al)
    ...
    >>> my_func(alist)
    ['a', 'b', 'c', 'x']
    >>> print(alist)
    ['a', 'b', 'c']
    

    In Python, non-innermost-local and not-declared-global accessible names are all aliases.

    Among dynamically-typed languages, Python is moderately type-checked. Implicit conversion is defined for numeric types (as well as booleans), so one may validly multiply a complex number by an integer (for instance) without explicit casting. However, there is no implicit conversion between, for example, numbers and strings; a string is an invalid argument to a mathematical function expecting a number.

    Base types

    Python has a broad range of basic data types. Alongside conventional integer and floating-point arithmetic, it transparently supports arbitrary-precision arithmetic, complex numbers, and decimal numbers.

    Python supports a wide variety of string operations. Strings in Python are immutable, so a string operation such as a substitution of characters, that in other programming languages might alter the string in place, returns a new string in Python. Performance considerations sometimes push for using special techniques in programs that modify strings intensively, such as joining character arrays into strings only as needed.

    Collection types

    One of the very useful aspects of Python is the concept of collection (or container) types. In general a collection is an object that contains other objects in a way that is easily referenced or indexed. Collections come in two basic forms: sequences and mappings.

    The ordered sequential types are lists (dynamic arrays), tuples, and strings. All sequences are indexed positionally (0 through length - 1) and all but strings can contain any type of object, including multiple types in the same sequence. Both strings and tuples are immutable, making them perfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elements can be inserted, deleted, modified, appended, or sorted in-place.

    Mappings, on the other hand, are (often unordered) types implemented in the form of dictionaries which "map" a set of immutable keys to corresponding elements (much like a mathematical function). For example, one could define a dictionary having a string "toast" mapped to the integer 42 or vice versa. The keys in a dictionary must be of an immutable Python type, such as an integer or a string, because under the hood they are implemented via a hash function. This makes for much faster lookup times, but requires keys not change.

    Dictionaries are central to the internals of Python as they reside at the core of all objects and classes: the mappings between variable names (strings) and the values which the names reference are stored as dictionaries (see Object system). Since these dictionaries are directly accessible (via an object's __dict__ attribute), metaprogramming is a straightforward and natural process in Python.

    A set collection type is an unindexed, unordered collection that contains no duplicates, and implements set theoretic operations such as union, intersection, difference, symmetric difference, and subset testing. There are two types of sets: set and frozenset, the only difference being that set is mutable and frozenset is immutable. Elements in a set must be hashable. Thus, for example, a frozenset can be an element of a regular set whereas the opposite is not true.

    Python also provides extensive collection manipulating abilities such as built in containment checking and a generic iteration protocol.

    Object system

    In Python, everything is an object, even classes. Classes, as objects, have a class, which is known as their metaclass. Python also supports multiple inheritance and mixins.

    The language supports extensive introspection of types and classes. Types can be read and compared—types are instances of type. The attributes of an object can be extracted as a dictionary.

    Operators can be overloaded in Python by defining special member functions—for instance, defining a method named __add__ on a class permits one to use the + operator on objects of that class.

    Literals

    Strings

    Python has various kinds of string literals.

    Normal string literals

    Either single or double quotes can be used to quote strings. Unlike in Unix shell languages, Perl or Perl-influenced languages such as Ruby or Groovy, single quotes and double quotes function identically, i.e. there is no string interpolation of $foo expressions. However, interpolation can be done in various ways: with "f-strings" (since Python 3.6), using the format method or the old % string-format operator.

    For instance, all of these Python statements:

    print(f"I just printed {num} pages to the printer {printer}")
    
    print("I just printed {} pages to the printer {}".format(num, printer))
    print("I just printed {0} pages to the printer {1}".format(num, printer))
    print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer))
    
    print("I just printed %s pages to the printer %s" % (num, printer))
    print("I just printed %(num)s pages to the printer %(printer)s" % {"num": num, "printer": printer})
    

    are equivalent to the Perl statement:

    print "I just printed $num pages to the printer $printer\n"
    

    They build a string using the variables num and printer.

    Multi-line string literals

    There are also multi-line strings, which begin and end with a series of three single or double quotes and function like here documents in Perl and Ruby.

    A simple example with variable interpolation (using the format method) is:

    print('''Dear {recipient},
    
    I wish you to leave Sunnydale and never return.
    
    Not Quite Love,
    {sender}
    '''.format(sender="Buffy the Vampire Slayer", recipient="Spike"))
    

    Raw strings

    Finally, all of the previously mentioned string types come in "raw" varieties (denoted by placing a literal r before the opening quote), which do no backslash-interpolation and hence are very useful for regular expressions; compare "@-quoting" in C#. Raw strings were originally included specifically for regular expressions. Due to limitations of the tokenizer, raw strings may not have a trailing backslash. Creating a raw string holding a Windows path ending with a backslash requires some variety of workaround (commonly, using forward slashes instead of backslashes, since Windows accepts both).

    Examples include:

    >>> # A Windows path, even raw strings cannot end in a backslash
    >>> r"C:\Foo\Bar\Baz\"
      File "<stdin>", line 1
        r"C:\Foo\Bar\Baz\"
                         ^
    SyntaxError: EOL while scanning string literal
    
    >>> dos_path = r"C:\Foo\Bar\Baz\ " # avoids the error by adding
    >>> dos_path.rstrip()              # and removing trailing space
    'C:\\Foo\\Bar\\Baz\\'
    
    >>> quoted_dos_path = r'"{}"'.format(dos_path)
    >>> quoted_dos_path
    '"C:\\Foo\\Bar\\Baz\\ "'
    
    >>> # A regular expression matching a quoted string with possible backslash quoting
    >>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip()
    'C:\\Foo\\Bar\\Baz\\'
    
    >>> code = 'foo(2, bar)'
    >>> # Reverse the arguments in a two-arg function call
    >>> re.sub(r'\(([^,]*?),([^ ,]*?)\)', r'(\2, \1)', code)
    'foo(2, bar)'
    >>> # Note that this won't work if either argument has parens or commas in it.
    

    Concatenation of adjacent string literals

    String literals (using possibly different quote conventions) appearing contiguously and only separated by whitespace (including new lines), are allowed and are aggregated into a single longer string. Thus

    title = "One Good Turn: " \
            'A Natural History of the Screwdriver and the Screw'
    

    is equivalent to

    title = "One Good Turn: A Natural History of the Screwdriver and the Screw"
    

    Unicode

    Since Python 3.0, the default character set is UTF-8 both for source code and the interpreter. In UTF-8, unicode strings are handled like traditional byte strings. This example will work:

    s = "Γειά" # Hello in Greek
    print(s)
    

    Numbers

    Numeric literals in Python are of the normal sort, e.g. 0, -1, 3.4, 3.5e-8.

    Python has arbitrary-length integers and automatically increases their storage size as necessary. Prior to Python 3, there were two kinds of integral numbers: traditional fixed size integers and "long" integers of arbitrary size. The conversion to "long" integers was performed automatically when required, and thus the programmer usually didn't have to be aware of the two integral types. In newer language versions the distinction is completely gone and all integers behave like arbitrary-length integers.

    Python supports normal floating point numbers, which are created when a dot is used in a literal (e.g. 1.1), when an integer and a floating point number are used in an expression, or as a result of some mathematical operations ("true division" via the / operator, or exponentiation with a negative exponent).

    Python also supports complex numbers natively. Complex numbers are indicated with the J or j suffix, e.g. 3 + 4j.

    Lists, tuples, sets, dictionaries

    Python has syntactic support for the creation of container types.

    Lists (class list) are mutable sequences of items of arbitrary types, and can be created either with the special syntax

    a_list = [1, 2, 3, "a dog"]
    

    or using normal object creation

    a_second_list = []
    a_second_list.append(4)
    a_second_list.append(5)
    

    Tuples (class tuple) are immutable sequences of items of arbitrary types. There is also a special syntax to create tuples

    a_tuple = 1, 2, 3, "four"
    a_tuple = (1, 2, 3, "four")
    

    Although tuples are created by separating items with commas, the whole construct is usually wrapped in parentheses to increase readability. An empty tuple is denoted by (), while a tuple with a single value can be created with (1,).

    Sets (class set) are mutable containers of hashable items of arbitrary types, with no duplicates. The items are not ordered, but sets support iteration over the items. The syntax for set creation uses curly brackets

    some_set = {0, (), False}
    

    Python sets are very much like mathematical sets, and support operations like set intersection and union. Python also features a frozenset class for immutable sets, see Collection types.

    Dictionaries (class dict) are mutable mappings tying keys and corresponding values. Python has special syntax to create dictionaries ({key: value})

    a_dictionary = {"key 1": "value 1", 2: 3, 4: []}
    

    The dictionary syntax is similar to the set syntax, the difference is the presence of colons. The empty literal {} results in an empty dictionary rather than an empty set, which is instead created using the non-literal constructor: set().

    Operators

    Arithmetic

    Python includes the +, -, *, / ("true division"), // (floor division), % (modulus), and ** (exponentiation) operators, with their usual mathematical precedence.

    In Python 3, x / y performs "true division", meaning that it always returns a float, even if both x and y are integers that divide evenly.

    >>> 4 / 2
    2.0
    

    and // performs integer division or floor division, returning the floor of the quotient as an integer.

    In Python 2 (and most other programming languages), unless explicitly requested, x / y performed integer division, returning a float only if either input was a float. However, because Python is a dynamically-typed language, it was not always possible to tell which operation was being performed, which often led to subtle bugs, thus prompting the introduction of the // operator and the change in semantics of the / operator in Python 3.

    Comparison operators

    The comparison operators, i.e. ==, !=, <, >, <=, >=, is, is not, in and not in are used on all manner of values. Numbers, strings, sequences, and mappings can all be compared. In Python 3, disparate types (such as a str and an int) do not have a consistent relative ordering, and attempts to compare these types raises a TypeError exception. While it was possible to compare disparate types in Python 2 (for example, whether a string was greater-than or less-than an integer), the ordering was undefined; this was considered a historical design quirk and was ultimately removed in Python 3.

    Chained comparison expressions such as a < b < c have roughly the meaning that they have in mathematics, rather than the unusual meaning found in C and similar languages. The terms are evaluated and compared in order. The operation has short-circuit semantics, meaning that evaluation is guaranteed to stop as soon as a verdict is clear: if a < b is false, c is never evaluated as the expression cannot possibly be true anymore.

    For expressions without side effects, a < b < c is equivalent to a < b and b < c. However, there is a substantial difference when the expressions have side effects. a < f(x) < b will evaluate f(x) exactly once, whereas a < f(x) and f(x) < b will evaluate it twice if the value of a is less than f(x) and once otherwise.

    Logical operators

    In all versions of Python, boolean operators treat zero values or empty values such as "", 0, None, 0.0, [], and {} as false, while in general treating non-empty, non-zero values as true. The boolean values True and False were added to the language in Python 2.2.1 as constants (subclassed from 1 and 0) and were changed to be full blown keywords in Python 3. The binary comparison operators such as == and > return either True or False.

    The boolean operators and and or use minimal evaluation. For example, y == 0 or x/y > 100 will never raise a divide-by-zero exception. These operators return the value of the last operand evaluated, rather than True or False. Thus the expression (4 and 5) evaluates to 5, and (4 or 5) evaluates to 4.

    Functional programming

    As mentioned above, another strength of Python is the availability of a functional programming style. As may be expected, this makes working with lists and other collections much more straightforward.

    Comprehensions

    One such construction is the list comprehension, which can be expressed with the following format:

    L = [mapping_expression for element in source_list if filter_expression]
    

    Using list comprehension to calculate the first five powers of two:

    powers_of_two = [2**n for n in range(1, 6)]
    

    The Quicksort algorithm can be expressed elegantly (albeit inefficiently) using list comprehensions:

    def qsort(L):
        if L == []:
            return []
        pivot = L[0]
        return (qsort([x for x in L[1:] if x < pivot]) +
                [pivot] +
                qsort([x for x in L[1:] if x >= pivot]))
    

    Python 2.7+ also supports set comprehensions and dictionary comprehensions.

    First-class functions

    In Python, functions are first-class objects that can be created and passed around dynamically.

    Python's limited support for anonymous functions is the lambda construct. An example is the anonymous function which squares its input, called with the argument of 5:

    f = lambda x: x**2
    f(5)
    

    Lambdas are limited to containing an expression rather than statements, although control flow can still be implemented less elegantly within lambda by using short-circuiting, and more idiomatically with conditional expressions.

    Closures

    Python has had support for lexical closures since version 2.2. Here's an example function that returns a function that approximates the derivative of the given function:

    def derivative(f, dx):
        """Return a function that approximates the derivative of f
        using an interval of dx, which should be appropriately small.
        """
        def function(x):
            return (f(x + dx) - f(x)) / dx
        return function
    

    Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported. Variable scope in Python is implicitly determined by the scope in which one assigns a value to the variable, unless scope is explicitly declared with global or nonlocal.

    Note that the closure's binding of a name to some value is not mutable from within the function. Given:

    >>> def foo(a, b):
    ...     print(f'a: {a}')
    ...     print(f'b: {b}')
    ...     def bar(c):
    ...         b = c
    ...         print(f'b*: {b}')
    ...     bar(a)
    ...     print(f'b: {b}')
    ... 
    >>> foo(1, 2)
    a: 1
    b: 2
    b*: 1
    b: 2
    

    and you can see that b, as visible from the closure's scope, retains the value it had; the changed binding of b inside the inner function did not propagate out. The way around this is to use a nonlocal b statement in bar. In Python 2 (which lacks nonlocal), the usual workaround is to use a mutable value and change that value, not the binding. E.g., a list with one element.

    Generators

    Introduced in Python 2.2 as an optional feature and finalized in version 2.3, generators are Python's mechanism for lazy evaluation of a function that would otherwise return a space-prohibitive or computationally intensive list.

    This is an example to lazily generate the prime numbers:

    from itertools import count
    
    def generate_primes(stop_at=None):
        primes = []
        for n in count(start=2):
            if stop_at is not None and n > stop_at:
                return # raises the StopIteration exception
            composite = False
            for p in primes:
                if not n % p:
                    composite = True
                    break
                elif p ** 2 > n:
                    break
            if not composite:
                primes.append(n)
                yield n
    

    When calling this function, the returned value can be iterated over much like a list:

    for i in generate_primes(100):  # iterate over the primes between 0 and 100
        print(i)
    
    for i in generate_primes():  # iterate over ALL primes indefinitely
        print(i)
    

    The definition of a generator appears identical to that of a function, except the keyword yield is used in place of return. However, a generator is an object with persistent state, which can repeatedly enter and leave the same scope. A generator call can then be used in place of a list, or other structure whose elements will be iterated over. Whenever the for loop in the example requires the next item, the generator is called, and yields the next item.

    Generators don't have to be infinite like the prime-number example above. When a generator terminates, an internal exception is raised which indicates to any calling context that there are no more values. A for loop or other iteration will then terminate.

    Generator expressions

    Introduced in Python 2.4, generator expressions are the lazy evaluation equivalent of list comprehensions. Using the prime number generator provided in the above section, we might define a lazy, but not quite infinite collection.

    from itertools import islice
    
    primes_under_million = (i for i in generate_primes() if i < 1000000)
    two_thousandth_prime = islice(primes_under_million, 1999, 2000).next()
    

    Most of the memory and time needed to generate this many primes will not be used until the needed element is actually accessed. Unfortunately, you cannot perform simple indexing and slicing of generators, but must use the itertools module or "roll your own" loops. In contrast, a list comprehension is functionally equivalent, but is greedy in performing all the work:

    primes_under_million = [i for i in generate_primes(2000000) if i < 1000000]
    two_thousandth_prime = primes_under_million[1999]
    

    The list comprehension will immediately create a large list (with 78498 items, in the example, but transiently creating a list of primes under two million), even if most elements are never accessed. The generator comprehension is more parsimonious.

    Dictionary and set comprehensions

    While lists and generators had comprehensions/expressions, in Python versions older than 2.7 the other Python built-in collection types (dicts and sets) had to be kludged in using lists or generators:

    >>> dict((n, n*n) for n in range(5))
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

    Python 2.7 and 3.0 unified all collection types by introducing dictionary and set comprehensions, similar to list comprehensions:

    >>> [n*n for n in range(5)]  # regular list comprehension
    [0, 1, 4, 9, 16]
    >>>
    >>> {n*n for n in range(5)}  # set comprehension
    {0, 1, 4, 9, 16}
    >>>
    >>> {n: n*n for n in range(5)}  # dict comprehension
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

    Objects

    Python supports most object oriented programming (OOP) techniques. It allows polymorphism, not only within a class hierarchy but also by duck typing. Any object can be used for any type, and it will work so long as it has the proper methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support for metaclasses, an advanced tool for enhancing classes' functionality. Naturally, inheritance, including multiple inheritance, is supported. Python has very limited support for private variables using name mangling which is rarely used in practice as information hiding is seen by some as unpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals. The slogan "we're all responsible users here" is used to describe this attitude.

    As is true for modules, classes in Python do not put an absolute barrier between definition and user, but rather rely on the politeness of the user not to "break into the definition."

    — 9. Classes, The Python 2.6 Tutorial (2013)

    OOP doctrines such as the use of accessor methods to read data members are not enforced in Python. Just as Python offers functional-programming constructs but does not attempt to demand referential transparency, it offers an object system but does not demand OOP behavior. Moreover, it is always possible to redefine the class using properties (see Properties) so that when a certain variable is set or retrieved in calling code, it really invokes a function call, so that spam.eggs = toast might really invoke spam.set_eggs(toast). This nullifies the practical advantage of accessor functions, and it remains OOP because the property eggs becomes a legitimate part of the object's interface: it need not reflect an implementation detail.

    In version 2.2 of Python, "new-style" classes were introduced. With new-style classes, objects and types were unified, allowing the subclassing of types. Even entirely new types can be defined, complete with custom behavior for infix operators. This allows for many radical things to be done syntactically within Python. A new method resolution order for multiple inheritance was also adopted with Python 2.3. It is also possible to run custom code while accessing or setting attributes, though the details of those techniques have evolved between Python versions.

    With statement

    The with statement handles resources, and allows users to work with the Context Manager protocol. One function (__enter__()) is called when entering scope and another (__exit__()) when leaving. This prevents forgetting to free the resource and also handles more complicated situations such as freeing the resource when an exception occurs while it is in use. Context Managers are often used with files, database connections, test cases, etc.

    Properties

    Properties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access. An example of a class defining some properties is:

    class MyClass:
        def __init__(self):
            self._a = None
    
        @property
        def a(self):
            return self._a
    
        @a.setter  # makes the property writable
        def a(self, value):
            self._a = value
    

    Descriptors

    A class that defines one or more of the three special methods __get__(self, instance, owner), __set__(self, instance, value), __delete__(self, instance) can be used as a descriptor. Creating an instance of a descriptor as a class member of a second class makes the instance a property of the second class.

    Class and static methods

    Python allows the creation of class methods and static methods via the use of the @classmethod and @staticmethod decorators. The first argument to a class method is the class object instead of the self-reference to the instance. A static method has no special first argument. Neither the instance, nor the class object is passed to a static method.

    Exceptions

    Python supports (and extensively uses) exception handling as a means of testing for error conditions and other "exceptional" events in a program.

    Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

    Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.

    Exceptions are often used as an alternative to the if-block, especially in threaded situations. A commonly invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission," which is attributed to Grace Hopper. The alternative, known as LBYL, or "Look Before You Leap", explicitly tests for pre-conditions.

    In this first code sample, following the LBYL approach, there is an explicit check for the attribute before access:

    if hasattr(spam, 'eggs'):
        ham = spam.eggs
    else:
        handle_missing_attr()
    

    This second sample follows the EAFP paradigm:

    try:
        ham = spam.eggs
    except AttributeError:
        handle_missing_attr()
    

    These two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the "exceptional" case), the EAFP sample will run slower. The Python profiler can be used in specific cases to determine performance characteristics. If exceptional cases are rare, then the EAFP version will have superior average performance than the alternative. In addition, it avoids the whole class of time-of-check-to-time-of-use (TOCTTOU) vulnerabilities, other race conditions, and is compatible with duck typing. A drawback of EAFP is that it can be used only with statements; an exception cannot be caught in a generator expression, list comprehension, or lambda function.

    Comments and docstrings

    Python has two ways to annotate Python code. One is by using comments to indicate what some part of the code does. Single-line comments begin with the hash character (#) and continue until the end of the line. Comments spanning more than one line are achieved by inserting a multi-line string (with """ or ''' as the delimiter on each end) that is not used in assignment or otherwise evaluated, but sits in between other statements.

    Commenting a piece of code:

    import sys
    
    def getline():
        return sys.stdin.readline()  # Get one line and return it
    

    Commenting a piece of code with multiple lines:

    def getline():
        """This function gets one line and returns it.
    
        As a demonstration, this is a multiline docstring.
    
        This full string can be accessed as getline.__doc__.
        """
        return sys.stdin.readline()
    

    Docstrings (documentation strings), that is, strings that are located alone without assignment as the first indented line within a module, class, method or function, automatically set their contents as an attribute named __doc__, which is intended to store a human-readable description of the object's purpose, behavior, and usage. The built-in help function generates its output based on __doc__ attributes. Such strings can be delimited with " or ' for single line strings, or may span multiple lines if delimited with either """ or ''' which is Python's notation for specifying multi-line strings. However, the style guide for the language specifies that triple double quotes (""") are preferred for both single and multi-line docstrings.

    Single-line docstring:

    def getline():
        """Get one line from stdin and return it."""
        return sys.stdin.readline()
    

    Multi-line docstring:

    def getline():
        """Get one line
           from stdin
           and return it.
        """
        return sys.stdin.readline()
    

    Docstrings can be as large as the programmer wants and contain line breaks. In contrast with comments, docstrings are themselves Python objects and are part of the interpreted code that Python runs. That means that a running program can retrieve its own docstrings and manipulate that information, but the normal usage is to give other programmers information about how to invoke the object being documented in the docstring.

    There are tools available that can extract the docstrings from Python code and generate documentation. Docstring documentation can also be accessed from the interpreter with the help() function, or from the shell with the pydoc command pydoc.

    The doctest standard module uses interactions copied from Python shell sessions into docstrings to create tests, whereas the docopt module uses them to define command-line options.

    Function annotations

    Function annotations (type hints) are defined in PEP 3107. They allow attaching data to the arguments and return of a function. The behaviour of annotations is not defined by the language, and is left to third party frameworks. For example, a library could be written to handle static typing:

    def haul(item: Haulable, *vargs: PackAnimal) -> Distance
    

    Decorators

    A decorator is any callable Python object that is used to modify a function, method or class definition. A decorator is passed the original object being defined and returns a modified object, which is then bound to the name in the definition. Python decorators were inspired in part by Java annotations, and have a similar syntax; the decorator syntax is pure syntactic sugar, using @ as the keyword:

    @viking_chorus
    def menu_item():
        print("spam")
    

    is equivalent to

    def menu_item():
        print("spam")
    menu_item = viking_chorus(menu_item)
    

    Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate. For example, in the sample below, viking_chorus might cause menu_item to be run 8 times (see Spam sketch) for each time it is called:

    def viking_chorus(myfunc):
        def inner_func(*args, **kwargs):
            for i in range(8):
                myfunc(*args, **kwargs)
        return inner_func
    

    Canonical uses of function decorators are for creating class methods or static methods, adding function attributes, tracing, setting pre- and postconditions, and synchronization, but can be used for far more, including tail recursion elimination, memoization and even improving the writing of other decorators.

    Decorators can be chained by placing several on adjacent lines:

    @invincible
    @favourite_colour("Blue")
    def black_knight():
        pass
    

    is equivalent to

    def black_knight():
        pass
    black_knight = invincible(favourite_colour("Blue")(black_knight))
    

    or, using intermediate variables

    def black_knight():
        pass
    blue_decorator = favourite_colour("Blue")
    decorated_by_blue = blue_decorator(black_knight)
    black_knight = invincible(decorated_by_blue)
    

    In the example above, the favourite_colour decorator factory takes an argument. Decorator factories must return a decorator, which is then called with the object to be decorated as its argument:

    def favourite_colour(colour):
        def decorator(func):
            def wrapper():
                print(colour)
                func()
            return wrapper
        return decorator
    

    This would then decorate the black_knight function such that the colour, "Blue", would be printed prior to the black_knight function running. Closure ensures that the colour argument is accessible to the innermost wrapper function even when it is returned and goes out of scope, which is what allows decorators to work.

    Despite the name, Python decorators are not an implementation of the decorator pattern. The decorator pattern is a design pattern used in statically-typed object-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes. The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such.

    Easter eggs

    Users of curly bracket languages, such as C or Java, sometimes expect or wish Python to follow a block-delimiter convention. Brace-delimited block syntax has been repeatedly requested, and consistently rejected by core developers. The Python interpreter contains an easter egg that summarizes its developers' feelings on this issue. The code from __future__ import braces raises the exception SyntaxError: not a chance. The __future__ module is normally used to provide features from future versions of Python.

    Another hidden message, the Zen of Python (a summary of Python design philosophy), is displayed when trying to import this.

    The message Hello world! is printed when the import statement import __hello__ is used. In Python 2.7, instead of Hello world! it prints Hello world....

    Importing the antigravity module opens a web browser to xkcd comic 353 that portrays a humorous fictional use for such a module, intended to demonstrate the ease with which Python modules enable additional functionality. In Python 3, this module also contains an implementation of the "geohash" algorithm, a reference to xkcd comic 426.

    Equality (mathematics)

    From Wikipedia, the free encyclopedia https://en.wikipedia.org/wiki/Equality_...