Posted on Leave a comment

ASP.NET Core updates in .NET 5 Release Candidate 1

Daniel Roth

Daniel

.NET 5 Release Candidate 1 (RC1) is now available and is ready for evaluation. Here’s what’s new in this release:

  • Blazor WebAssembly performance improvements
  • Blazor component virtualization
  • Blazor WebAssembly prerendering
  • Browser compatibility analyzer for Blazor WebAssembly
  • Blazor JavaScript isolation and object references
  • Blazor file input support
  • Custom validation class attributes in Blazor
  • Blazor support for ontoggle event
  • Model binding DateTime as UTC
  • Control Startup class activation
  • Open API Specification (Swagger) on-by-default in ASP.NET Core API projects
  • Better F5 Experience for ASP.NET Core API Projects
  • SignalR parallel hub invocations
  • Added Messagepack support in SignalR Java client
  • Kestrel endpoint-specific options via configuration

See the .NET 5 release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET 5 RC1 install the .NET 5 SDK. .NET RC1 also is included with Visual Studio 2019 16.8 Preview 3.

You need to use Visual Studio 2019 16.8 Preview 3 or newer to use .NET 5 RC1. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 Preview 8 to .NET 5 RC1:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-rc.1.*.
    • If you’re using the new Microsoft.AspNetCore.Components.Web.Extensions package, update to version 5.0.0-preview.9.*. This package doesn’t have an RC version number yet because we expect to make a few more design changes to the components it contains before it’s ready to ship.
  • Update all Microsoft.Extensions.* package references to 5.0.0-rc.1.*.
  • Update System.Net.Http.Json package references to 5.0.0-rc.1.*.

In Blazor WebAssembly projects, also make the follwowing updates to the project file:

  • Update the SDK from “Microsoft.NET.Sdk.Web” to “Microsoft.NET.Sdk.BlazorWebAssembly”
  • Remove the <RuntimeIdentifier>browser-wasm</RuntimeIdentifier> and <UseBlazorWebAssembly>true</UseBlazorWebAssembly> properties.

That’s it! You should be all ready to go.

See also the full list of breaking changes in ASP.NET Core for .NET 5.

What’s new?

Blazor WebAssembly performance improvements

For .NET 5, we’ve made significant improvements to Blazor WebAssembly runtime performance, with a specific focus on complex UI rendering and JSON serialization. In our performance tests, Blazor WebAssembly in .NET 5 is 2-3x faster for most scenarios.

Runtime code execution in Blazor WebAssembly in .NET 5 is generally faster than Blazor WebAssembly 3.2 due to optimizations in the core framework libraries and improvements to the .NET IL interpreter. Things like string comparisons, dictionary lookups, and JSON handling are generally much faster in .NET 5 on WebAssembly.

As shown in the chart below, JSON handling is almost twice as fast in .NET 5 on WebAssembly:

Blazor WebAssembly 1kb JSON handling

We also optimized the performance of Blazor component rendering, particularly for UI involving lots of components, like when using high-density grids.

To test the performance of grid component rendering in .NET 5, we used three different grid component implementations, each rendering 200 rows with 20 columns:

  • Fast Grid: A minimal, highly optimized implementation of a grid
  • Plain Table: A minimal but not optimized implementation of a grid.
  • Complex Grid: A maximal, not optimized implementation of a grid, using a wide range of Blazor features at once, deliberately intended to create a bad case for the renderer.

From our tests, grid rendering is 2-3x faster in .NET 5:

Blazor WebAssembly grid rendering

You can find the code for these performance tests in the ASP.NET Core GitHub repo.

You can expect ongoing work to improve Blazor WebAssembly performance. Besides optimizing the Blazor WebAssembly runtime and framework, the .NET team is also working with browser implementers to further speed up WebAssembly execution. And for .NET 6, we expect to ship support for ahead-of-time (AoT) compilation to WebAssembly, which should further improve performance.

Blazor component virtualization

You can further improve the perceived performance of component rendering using the new built-in virtualization support. Virtualization is a technique for limiting the UI rendering to just the parts that are currently visible, like when you have a long list or table with many rows and only a small subset is visible at any given time. Blazor in .NET 5 adds a new Virtualize component that can be used to easily add virtualization to your components.

A typical list or table-based component might use a C# foreach loop to render each item in the list or each row in the table, like this:

@foreach (var employee in employees)
{ <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
}

If the list grew to include thousands of rows, then rendering it may take a while, resulting in a noticeable UI lag.

Instead, you can replace the foreach loop with the Virtualize component, which only renders the rows that are currently visible.

<Virtualize Items="employees" Context="employee"> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
</Virtualize>

The Virtualize component calculates how many items to render based on the height of the container and the size of the rendered items.

If you don’t want to load all items into memory, you can specify an ItemsProvider, like this:

<Virtualize ItemsProvider="LoadEmployees" Context="employee"> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
</Virtualize>

An items provider is a delegate method that asynchronously retrieves the requested items on demand. The items provider receives an ItemsProviderRequest, which specifies the required number of items starting at a specific start index. The items provider then retrieves the requested items from a database or other service and returns them as an ItemsProviderResult<TItem> along with a count of the total number of items available. The items provider can choose to retrieve the items with each request, or cache them so they are readily available.

async ValueTask<ItemsProviderResult<Employee>> LoadEmployees(ItemsProviderRequest request)
{ var numEmployees = Math.Min(request.Count, totalEmployees - request.StartIndex); var employees = await EmployeesService.GetEmployeesAsync(request.StartIndex, numEmployees, request.CancellationToken); return new ItemsProviderResult<Employee>(employees, totalEmployees);
}

Because requesting items from a remote data source might take some time, you also have the option to render a placeholder until the item data is available.

<Virtualize ItemsProvider="LoadEmployees" Context="employee"> <ItemContent> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr> </ItemContent> <Placeholder> <tr> <td>Loading...</td> </tr> </Placeholder>
</Virtualize>

Blazor WebAssembly prerendering

The component tag helper now supports two additional render modes for prerendering a component from a Blazor WebAssembly app:

  • WebAssemblyPrerendered: Prerenders the component into static HTML and includes a marker for a Blazor WebAssembly app to later use to make the component interactive when loaded in the browser.
  • WebAssembly: Renders a marker for a Blazor WebAssembly app to use to include an interactive component when loaded in the browser. The component is not prerendered. This option simply makes it easier to render different Blazor WebAssembly components on different cshtml pages.

To setup prerendering in an Blazor WebAssembly app:

  1. Host the Blazor WebAssembly app in an ASP.NET Core app.
  2. Replace the default static index.html file in the client project with a _Host.cshtml file in the server project.
  3. Update the server startup logic to fallback to _Host.cshtml instead of index.html (similar to how the Blazor Server template is set up).
  4. Update _Host.cshtml to use the component tag helper to prerender the root App component:

    <component type="typeof(App)" render-mode="WebAssemblyPrerendered" />
    

You can also pass parameters to the component tag helper when using the WebAssembly-based render modes if the parameters are serializable. The parameters must be serializable so that they can be transferred to the client and used to initialize the component in the browser. If prerendering, you’ll also need to be sure to author your components so that they can gracefully execute server-side without access to the browser.

<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered" param-IncrementAmount="10" />

In additional to improving the perceived load time of a Blazor WebAssembly app, you can also use the component tag helper with the new render modes to add multiple components on different pages and views. You don’t need to configure these components as root components in the app or add your own marker tags on the page – the framework handles that for you.

Browser compatibility analyzer for Blazor WebAssembly

Blazor WebAssembly apps in .NET 5 target the full .NET 5 API surface area, but not all .NET 5 APIs are supported on WebAssembly due to browser sandbox constraints. Unsupported APIs throw PlatformNotSupportedException when running on WebAssembly. .NET 5 now includes a platform compatibility analyzer that will warn you when your app uses APIs that are not supported by your target platforms. For Blazor WebAssembly apps, this means checking that APIs are supported in browsers.

We haven’t added all of the annotations yet to the core libraries in .NET 5 to indicate which APIs are not supported in browsers, but some APIs, mostly Windows specific APIs, are already annotated:

Platform compatibility analyzer

To enable browser compatibilty checks for libraries, add “browser” as a supported platform in your project file (Blazor WebAssembly projects and Razor class library projects do this for you):

<SupportedPlatform Include="browser" />

When authoring a library, you can optionally indicate that a particular API is not supported in browsers by applying the UnsupportedOSPlatformAttribute:

[UnsupportedOSPlatform("browser")]
private static string GetLoggingDirectory()
{ // ...
}

Blazor JavaScript isolation and object references

Blazor now enables you to isolate your JavaScript as standard JavaScript modules. This has a couple of benefits:

  1. Imported JavaScript no longer pollutes the global namespace.
  2. Consumers of your library and components no longer need to manually import the related JavaScript.

For example, the following JavaScript module exports a simple JavaScript function for showing a browser prompt:

export function showPrompt(message) { return prompt(message, 'Type anything here');
}

You can add this JavaScript module to your .NET library as a static web asset (wwwroot/exampleJsInterop.js) and then import the module into your .NET code using the IJSRuntime service:

var module = await jsRuntime.InvokeAsync<JSObjectReference>("import", "./_content/MyComponents/exampleJsInterop.js");

The “import” identifier is a special identifier used specifically for importing a JavaScript module. You specify the module using its stable static web asset path: _content/[LIBRARY NAME]/[PATH UNDER WWWROOT].

The IJSRuntime imports the module as a JSObjectReference, which represents a reference to a JavaScript object from .NET code. You can then use the JSObjectReference to invoke exported JavaScript functions from the module:

public async ValueTask<string> Prompt(string message)
{ return await module.InvokeAsync<string>("showPrompt", message);
}

JSObjectReference greatly simplifies interacting with JavaScript libraries where you want to capture JavaScript object references, and then later invoke their functions from .NET.

Blazor file input support

Blazor now offers an InputFile component for handling file uploads, or more generally for reading browser file data into your .NET code.

The InputFile component renders as an HTML input of type “file”. By default, the user can select single files, or if you add the “multiple” attribute then the user can supply multiple files at once. When one or more files is selected by the user, the InputFile component fires an OnChange event and passes in an InputFileChangeEventArgs that provides access to the selected file list and details about each file.

<InputFile OnChange="OnInputFileChange" multiple /> <div class="image-list"> @foreach (var imageDataUrl in imageDataUrls) { <img src="@imageDataUrl" /> }
</div> @code { IList<string> imageDataUrls = new List<string>(); async Task OnInputFileChange(InputFileChangeEventArgs e) { var imageFiles = e.GetMultipleFiles(); var format = "image/png"; foreach (var imageFile in imageFiles) { var resizedImageFile = await imageFile.RequestImageFileAsync(format, 100, 100); var buffer = new byte[resizedImageFile.Size]; await resizedImageFile.OpenReadStream().ReadAsync(buffer); var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}"; imageDataUrls.Add(imageDataUrl); } }
}

To read data from a user-selected file, you call OpenReadStream on the file and read from the returned stream. In a Blazor WebAssembly app, the data is streamed directly into your .NET code within the browser. In a Blazor Server app, the file data is streamed to your .NET code on the server as you read from the stream. In case you’re using the component to receive an image file, Blazor also provides a RequestImageFileAsync convenience method for resizing images data within the browser’s JavaScript runtime before they’re streamed into your .NET application.

Custom validation class attributes in Blazor

You can now specify custom validation class names in Blazor. This is useful when integrating with CSS frameworks, like Bootstrap.

To specify custom validation class names, create a class derived from FieldCssClassProvider and set it on the EditContext instance.

var editContext = new EditContext(model);
editContext.SetFieldCssClassProvider(new MyFieldClassProvider()); // ... class MyFieldClassProvider : FieldCssClassProvider
{ public override string GetFieldCssClass(EditContext editContext, in FieldIdentifier fieldIdentifier) { var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any(); return isValid ? "legit" : "totally-bogus"; }
}

Blazor support for ontoggle event

Blazor now has support for the ontoggle event:

<div> @if (detailsExpanded) { <p>Read the details carefully!</p> } <details id="details-toggle" @ontoggle="OnToggle"> <summary>Summary</summary> <p>Detailed content</p> </details>
</div> @code { bool detailsExpanded; string message { get; set; } void OnToggle() { detailsExpanded = !detailsExpanded; }
}

Thank you Vladimir Samoilenko for this contribution!

Model binding DateTime as UTC

Model binding in ASP.NET Core now supports correctly binding UTC time strings to DateTime. If the request contains a UTC time string (for example https://example.com/mycontroller/myaction?time=2019-06-14T02%3A30%3A04.0576719Z), model binding will correctly bind it to a UTC DateTime without the need for further customization.

Control Startup class activation

We’ve provided an additional UseStartup overload that lets you provide a factory method for controlling Startup class activation. This is useful if you want to pass additional parameters to Startup that are initialized along with the host.

public class Program
{ public static async Task Main(string[] args) { var logger = CreateLogger(); var host = Host.CreateDefaultBuilder() .ConfigureWebHost(builder => { builder.UseStartup(context => new Startup(logger)); }) .Build(); await host.RunAsync(); }
}

Open API Specification On-by-default

Open API Specification is a industry-adopted convention for describing HTTP APIs and integrating them into complex business processes or with 3rd parties. Open API is widely supported by all cloud providers and many API registries, so developers who emit Open API documents from their Web APIs have a variety of new opportunities in which those APIs can be used. In partnership with the maintainers of the open-source project Swashbuckle.AspNetCore, we’re excited to announce that the ASP.NET Core API template in RC1 comes pre-wired with a NuGet dependency on Swashbuckle, a popular open-source NuGet package that emits Open API documents dynamically. Swashbuckle does this by introspecting over your API Controllers and generating the Open API document at run-time, or at build time using the Swashbuckle CLI.

In .NET 5 RC1, running dotnet new webapi will result in the Open API output being enabled by default, but if you prefer to have Open API disabled, use dotnet new webapi --no-openapi true. All .csproj files that are created for Web API projects will come with the NuGet package reference.

<ItemGroup> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
</ItemGroup>

In addition to the NuGet package reference being in the .csproj file we’ve added code to both the ConfigureServices method in Startup.cs that activates Open API document generation.

public void ConfigureServices(IServiceCollection services)
{ services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" }); });
}

The Configure method is also pre-wired to enlist in the Swashbuckle middleware. This lights up the document generation process and turns on the Swagger UI page by default in development mode. This way you’re confident that the out-of-the-box experience doesn’t accidentally expose your API’s description when you publish to production.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1 v1")); } // ...
}

Azure API Management Import

When ASP.NET Core API projects are wired to output Open API in this way, the Visual Studio 2019 version 16.8 Preview 2.1 publishing experience will automatically offer an additional step in the publishing flow. Developers who use Azure API Management have an opportunity to automatically import their APIs into Azure API Management during the publish flow.

Publising APIs

This additional publishing step reduces the number of steps HTTP API developers need to execute to get their APIs published and used with Azure Logic Apps or PowerApps.

Better F5 Experience for Web API Projects

With Open API enabled by default, we were able to significantly improve the F5 experience for Web API developers. With .NET 5 RC1, the Web API template comes pre-configured to load up the Swagger UI page. The Swagger UI page provides both the documentation you’ve added for your API, but enables you to test your APIs with a single click.

Swagger UI page

SignalR parallel hub invocations

In .NET 5 RC1, ASP.NET Core SignalR is now capable of handling parallel hub invocations. You can change the default behavior and allow clients to invoke more than one hub method at a time.

public void ConfigureServices(IServiceCollection services)
{ services.AddSignalR(options => { options.MaximumParallelInvocationsPerClient = 5; });
}

Added Messagepack support in SignalR Java client

We’re introducing a new package, com.microsoft.signalr.messagepack, that adds messagepack support to the SignalR java client. To use the messagepack hub protocol, add .withHubProtocol(new MessagePackHubProtocol()) to the connection builder.

HubConnection hubConnection = HubConnectionBuilder.create("http://localhost:53353/MyHub") .withHubProtocol(new MessagePackHubProtocol()) .build();

Kestrel endpoint-specific options via configuration

We have added support for configuring Kestrel’s endpoint-specific options via configuration. The endpoint-specific configurations includes the Http protocols used, the TLS protocols used, the certificate selected, and the client certificate mode.

You are able to configure the which certificate is selected based on the specified server name as part of the Server Name Indication (SNI) extension to the TLS protocol as indicated by the client. Kestrel’s configuration also support a wildcard prefix in the host name.

The example belows shows you how to specify endpoint-specific using a configuration file:

{ "Kestrel": { "Endpoints": { "EndpointName": { "Url": "https://*", "Sni": { "a.example.org": { "Protocols": "Http1AndHttp2", "SslProtocols": [ "Tls11", "Tls12"], "Certificate": { "Path": "testCert.pfx", "Password": "testPassword" }, "ClientCertificateMode" : "NoCertificate" }, "*.example.org": { "Certificate": { "Path": "testCert2.pfx", "Password": "testPassword" } }, "*": { // At least one subproperty needs to exist per SNI section or it // cannot be discovered via IConfiguration "Protocols": "Http1", } } } } }
}

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

Python Keyboard Errors

When you’re learning and working with Python, you’re going to encounter errors and there’s no getting around that fact. So how do you get around them? It helps to learn about the errors. We’re going to take the opportunity to learn one of them today.

What is “Keyboard Interrupt”?

This is an error that you’re not likely to run across often unless you are running a Python program for more than two seconds. If your program has loops, a while loop specifically, then there might come a point when you need to stop the program. Because while loops, when not written with an ending in mind, keep going, like the Energizer Bunny.

In this example, we created a simple while loop that is loaded with print statements. If you run it, then the script will keep printing the same three statements.

Impressive, isn’t it? You can keep it going for a long time, but you might want to think about stopping it. When you press Ctrl and C, you’ll get this Exception that pops up, otherwise known as the Keyboard Interrupt.

This is one of the built-in exceptions that you’ll come across when programming in Python. Based on the hierarchy, the Keyboard Interruption exception is right towards the top, underneath Base Exception and System Exit. You can find the full hierarchy here.

Now you might be wondering if there is any way you can keep that error from popping up? Not really. It is there for a reason and it’s to stop the script from running.

Unless you want to keep it going forever. We hope your computer is built for that. However, we do know of a good way for you to clean it up a little bit.

The Try/Except method

If you’re hoping to avoid those awkward error messages that pop up when running your Python code, then this is the best route for you to go. The Try/Except method is another solid way for you to run your Python code. And you can do so without dealing with specific errors in your code

This is the simplest example that we can provide for how it works.

You put the code that you want to run underneath the try. And underneath your except is what you can enter to deal with any errors you might encounter. This can help you with larger projects. If you’re building a Twitter bot, for example, you could set it up so that it runs your code and if there’s a problem with getting the tweet out, you’ll be able to catch the error.

You might not think you’ll need it, but once you start catching errors when running your code, you’ll want to use it.

To get it to work, we’re going to make a few adjustments.

At the top of our script, we imported the Sys module, which is built-in for Python. You don’t need to install it.

Inside of our while loop, we enter our Try and Except block. Underneath Try, we put in three print statements. You’re free to put as many print statements as you want in this. If you want to make it 10, then go for it! We want you to be ambitious with your infinite time loop.

Underneath except, we just have one print statement in there. Obviously, you can do more, but that would defeat the purpose. Please don’t go crazy with your print statements.  Put them all underneath your try statement.

What we put in next, underneath our print statement, is what you would consider an exit command. And there’s more than one you can use. However, for this instance, we just chose sys.exit(). You can also import os and use the exit command for that one.

In fact, you don’t need to import any Python modules. You can just use quit() and it works just as well. But we like to be fancy sometimes.

Works pretty good, don’t you think?

Let’s Build A Time Loop

What we have now makes for a pretty good time loop. But now we can try to have a little more fun with our Python script. Let’s build it differently and see how that can work. And we’ll set it up so you can’t escape from the loop.

Now when we say you won’t escape, we mostly mean it won’t be as simple as pressing Ctrl + C on your keyboard. If you’re worried about stopping it, all you would theoretically need to do is just exit out of your command line. It would stop at that point. Of course, you’d have to start all over by re-opening your line. But let’s have some fun.

First, you’ll need to import the Time module, which is built-in already for Python. We’ll be making some sleep functions later on in our code. But first, we’re going to create the time loop function.

It will be simple. Just one print statement involved. However, you can create as many print statements as your heart desires.

The function will look like this:

Once that is done, we can make our while loop. Embedded in it will be our try and except blocks. Underneath try, we’ll include the time_loop() function, as well as our sleep function. Inside the parenthesis, you’ll want to put in how long you want the program to sleep for. It’s done in seconds. You could have it at 1, 100, 1000, 10000, whatever you want. For our example, we chose five seconds. It should be a little easier on your eyes, instead of having it go non-stop. Gives you that breath of fresh air!

While under the except one, we add another print statement. It might seem cruel to you, but hey it’s a time loop. You’re stuck! Isn’t that how time loops work, at least? We don’t know for sure. We watched Palm Springs recently and that fills up about 98% of our knowledge on the topic.

But your time loop should end up looking like this:

Pretty cool, right? You’ll have a fun and frustrating time trying to escape this time loop. Of course, like we said, you can always exit out of command line. But why take the risk? 😊

If nothing else, now is your chance to play around with the script. Have some fun. Maybe try to do something different with your time loop. Get a little creative!

Posted on Leave a comment

Replacements For Switch Statement In Python?

Summary: Since switch-case statements are not a part of Python, you can use one of the following methods to create a switch-case construct in your code :

Problem: Given a selection control switch case scenario in python; how to find a replacement for switch statement since python does not have a provision for switch-case statements.

Overview: Before we discuss the solutions to our problem, we must have a clear picture of the switch-case statement itself. To understand the switch statements let us answer a few questions :

What is a switch statement?

In programming languages like C, C++, C#, Java, etc switch is a conditional statement used to test the value of a variable and then compare this value with several cases. Once the match case is found, the block of code defined within the matched case is executed. Let us have a look at the following flowchart to visualize the working principle of switch case:

fig: switch-case statement depicting program flow when nth case is TRUE

switch vs if-else

In a program that needs a complex set of nested if statements, a switch statement is always a better and more efficient alternative in such situations. Following are some of the key factors which should be taken into consideration while deciding whether to use switch case or if-else statements in the code:

  1. If the number of cases is more, then switch-case statements are always more efficient and faster than if-else.
  2. Switch case statements are more suited for fixed data values whereas if-else conditionals should be used in case of boolean values.
  3. Switch statements check expressions based only on a single parameter / variable value whereas if-else conditional statements can be used to test expressions on a range of values.

There are a few other factors governing the proper usage of the two statements. However, that is beyond the scope of this article, as we are going to focus on the replacements for switch statements in python in this article. Now that brings us to the next and probably the most important question.

Why does Python Not Have A “switch” Statement?

Thinking Face on Facebook 2.0

You might have been wondering all the while, why are we even proposing a solution for replacing the switch statement in python. Does python not have a “switch” statement?

The answer is NO!!! Python does not need one.

  • Most programming languages have switch-case statements because they lack proper mapping constructs. While in Python, we have well-defined mapping constructs and you can easily have a mapping table in the form of a python dictionary.
  • Furthermore, Python does not have a switch statement because none of the proposals that have been suggested so far have been deemed acceptable.

#Note

Guido van Rossum says, “Some kind of switch statement is found in many languages and it is not unreasonable to expect that its addition to Python will allow us to write up certain code more cleanly and efficiently than before.” So this might indicate that in the future we might find that the switch statement is implemented in Python, though it is quite unlikely to happen anytime soon. (But the future is full of unpredictabilities!!!)

Now that we have an overview of the switch-statement, let us find out the alternatives for switch statements that can be used in python.

Solutions

Let us discuss how we can create alternatives to switch cases and ask the user to select an option for the operation they want to perform. Based on the users’ choice the output shall be displayed. Here’s a sample output of what we want to achieve:

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 1
Enter 1st Number: 500
Enter 2nd Number: 2000
Answer = 2500

So without further delay, let the games begin!

Method 1: Using A Dictionary

A dictionary in python stores items in the form of key-value pairs such that a certain value maps to a specific key. Let us have a look at the following code to understand how we can use a dictionary as an alternative to switch case and solve our problem (Please follow the comments to get a better grip on the code):

# The default case when no case matches
def default(a, b): return "Invalid Entry!" def switch(option, a, b): # create the dictionary and switch-cases / choices return { '1': lambda a, b: a + b, '2': lambda a, b: a - b, '3': lambda a, b: a * b, '4': lambda a, b: a / b, }.get(option, default)(a, b) # User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division ''')
# Accept User Entry
choice = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print(switch(choice, x, y))

Output:

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 1
Enter 1st Number: 15
Enter 2nd Number: 50
Answer = 65

Things to remember:

  • get() is an in-built function in python which returns the value for a specified key.
  • lambda is a keyword in python which is used to define an anonymous function inside another function.

I would strongly recommend you to go through these articles for an in-depth understanding of lambda and python dictionary functions and their usage:

  1. Link to learn about Python Dictionaries.
  2. Link to learn about Python Lambda Function.

If you are not comfortable with the usage of get() and lambda, I have a solution for you too. Have a look at the following code which might be a little lengthier and more complex in terms of time and memory usage but is certainly easier to grasp :

# Addition
def choice1(x, y): return x + y # Subtraction
def choice2(x, y): return x - y # Multiplication
def choice3(x, y): return x * y # Division
def choice4(x, y): return x / y def switch(option, a, b): try: # create the dictionary and switch-cases / choices return { '1': choice1, '2': choice2, '3': choice3, '4': choice4, }[choice](x, y) except KeyError: # Default Case return 'Invalid Entry!' # User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division ''')
# Accept User Entry
choice = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print("Answer = ", switch(choice, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 2
Enter 1st Number: 20
Enter 2nd Number: 10
Answer = 10

Method 2: Creating A Switch Class

Another workaround to use switch cases in our programs is to create a class with basic switch-case functionality defined within it. We can define each case within separate functions inside the class.

Let us have a look at the following program to understand how we can create a switch-case class (As always, I request you to read the comments within the code to get a better grip):

class SwitchCase: def case(self, option, x, y): default = "Invalid Entry!" # lambda invokes the default case # getattr() is used to invoke the function choice that the user wants to evaluate return getattr(self, 'choice' + str(option), lambda x, y: default)(x, y) # Addition def choice1(self, x, y): return x + y # Subtraction def choice2(self, x, y): return x - y # Multiplication def choice3(self, x, y): return x * y # Division def choice4(self, x, y): return x / y # Default Case def default(self, x, y): return "Invalid Entry!" # creating the SwitchCase class object
switch = SwitchCase()
# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division ''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print("Answer = ", switch.case(option, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 4
Enter 1st Number: 24
Enter 2nd Number: 4
Answer = 6.0

Method 3: A Quick Fix Using Lambda Function

Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.

var = (lambda x, y, c: x + y if c == '1' else x - y if c == '2' else x * y if c == '3' else x / y if c == '4' else 'Invalid Entry!') # User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division ''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
print(var(x, y, option))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 4
Enter 1st Number: 500
Enter 2nd Number: 25
20.0

Method 4: Using if-elif-else

Sometimes it is always better to follow the standard programming constructs because they provide us the simplest solutions in most cases. Using the if-elif-else might not be the exact replacement for a switch case but it provides a simpler construct and structure. Also, it avoids the problem of KeyError if the matching case is not found.

Let us have a look at the following code to understand how we can use the if-elif-else conditionals to solve our problem:

def func(choice, a, b): if choice == '1': return a + b elif choice == '2': return a - b elif choice == '3': return a * b elif choice == '4': return a / b else: return 'Invalid Entry!' # User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division ''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
print("Answer = ", func(option, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division Enter your choice: 1
Enter 1st Number: 500
Enter 2nd Number: 2000
Answer = 2500

Conclusion

In this article, we discussed how we can replace the switch case statements in our python code using python dictionary mapping or by creating a class or by applying a quick fix using a python lambda function. Having said that, the best way to implement switches in python is to use a dictionary that maps the key and value pairs.

I hope you enjoyed reading this article and after reading it you can use an alternative to switch-case in your code with ease. If you find these discussions and solutions interesting then please subscribe and stay tuned for more interesting articles in the future!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Python raw_input() vs input()

Summary: The key differences between raw_input() and input() functions are :

  • raw_input() can be used only in Python 2.x and is obsolete in python 3.x and above and has been renamed input()
  • In Python 2.x, raw_input() returns a string whereas input() returns result of an evaluation. While in Python 3.x input() returns a string but can be converted to another type like a number.

Overview

Before looking at the differences between raw_input() and input(), let us understand why we need them?

A user-friendly code is one that is interactive. To make a code interactive instead of hard coding values, a developer/programmer must aim to allow the user to input their own values into the program. We use the raw_input() and input() functions to accept user inputs.

Example: The following program is an example to accept user input in Python:

name = input("Please enter your full name: ")
age = input("Please enter your age: ")
# In Python2.x use raw_input() instead print("Name: ", name)
print("Age: ", age)

Output

Please enter your full name: FINXTER
Please enter your age: 25
Name: FINXTER
Age: 25

In this article, we shall be discussing the key differences between the input() and raw_input() functions. So let us jump into the mission-critical question:

Problem: What is difference between raw_input() and input() in python?

Let us have an in-depth look at each difference one by one:

Existential Difference

raw_input() input()
Inbuilt function present only in Python 2.x and is not a part of Python 3.x Inbuilt function present in both, Python 2.x and Python 3.x

Functional Difference Based on Python Versions

  Python 2.x Python 3.x
raw_input() raw_input() accepts input as it is, i.e. exactly as the input has been entered by the user and returns a string.

◆ Since it accepts the input as it is, it does not expect the input to be syntactically correct.  

raw_input() is obsolete and no longer a part of Python 3.x and above.
input() input() accepts the input from the user as a statement or expression and returns the output after evaluating the input. In other words, it accepts the user entry as raw_input(), performs an eval() on it, and then returns the result as output.

◆ It expects a syntactically correct input (statement/expression) from the user.

◆ In Python 3.x, raw_input() has been replaced by input(). This means that the input() function performs the same operation in Python 3.x as raw_input() used to do in Python 2.  

Thus input() accepts and returns a string in Python 3.x and above.   

Examples

Python 2.x

input() function

a = raw_input("What is your name? ")
print "Name: %s" %a)
b = raw_input(" Enter a mathematical expression: ")
print Output": %d", %b

Output

What is your name? Finxter
Name: Finxter Enter a mathematical expression: 2+5
Output: 2+5

raw_input() function

a = input("Enter Your Full Name: ")
print "Name: %s " %a
b = input("Enter a Mathematical Expression: ")
print "Output: %d" %b

Output

Enter Your Full Name: 'Finxter Shubham'
Name: Finxter Shubham
Enter a Mathematical Expression: 5**2
Output: 25

Python 3.x And Above

input() function

a = input("What is your name? ")
print("Name: ", a)
b = input("Enter a mathematical expression: ")
print("Output: ", b)

Output

What is your name? Finxter Shubham
Name: Finxter Shubham
Enter a mathematical expression: 3+5
Output: 3+5

Trivia

If you want to implement or leverage the functionality of input() of Python 2.x in Python 3.x and evaluate the statement entered by the user, you can use one of the following procedures:

  • Type Conversion : int(input(“Enter value”))
  • Using eval(input(“Enter Value”))

Example

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Addition: ", a+b)
x = eval(input("Enter a mathematical expression: "))
print("Result: ", x)

Output:

Enter first number: 25
Enter second number: 75
Addition: 100
Enter a mathematical expression: 10**2
Result: 100

But you must avoid the usage of eval() function unless necessary because it has a severe drawback.

I would strongly recommend you to read this article in connection with this topic. It will help you have a broader understanding of this concept. Also, if you are wondering about the version of python installed in your system, you may want to have a look at this article.

Conclusion

In this article, we discussed the key differences between input() and raw_input() in terms of their functionality and existence in different versions of python along with their examples. I hope all your doubts regarding the difference between input() and raw_input() have been clarified after reading this article.

Please stay tuned and Subscribe for more interesting articles!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

What Is Python Output Buffering and How to Disable It?

Summary: Python output buffering is the process of storing the output of your code in buffer memory. Once the buffer is full, the output gets displayed on the standard output screen. Buffering is enabled by default and you can use one of the following methods to disable it:

  • Execute the Python code with the -u command line switch, for example python -u code.py
  • Use the flush keyword
  • Use sys.stdout.flush()
  • Wrap sys.stdout in TextIOWrapper and set the buffered size to 0
  • Set PYTHONUNBUFFERED to a non-empty string

Problem: Given a Python program; how to disable output buffering?

Overview Of Python Output Buffering

Before we learn buffering in the context of Python, we should ponder upon what buffer means in real life? Let me answer this question with another question. When you are in a stressful situation, whom or what do you look up to as an option to lessen your stress? On a personal level, I look up to my friends and family. So they are my “buffer” against stress.

According to the dictionary definition, a buffer is a person or thing that reduces a shock or that forms a barrier between incompatible or antagonistic people or things. This is what exactly a buffer does when it comes to a programming language like Python (though it is not a person in this case).

In terms of computer science, you may consider buffer as a middle layer which ensures a more efficient way for data to be transferred from one location to another in the system. For example, if you are downloading a 100 MB file and 1 MB gets written at a time to the hard disk would mean that it would require a total of 100 disk writes. However, a buffer could ensure that 10 MB gets written at a time to the disk, and this way only 10 disk writes will be needed.

Advantages and Disadvantages:

From the above scenario, we learned how buffer can act as an intermediate resource and reduce the number of disk writes thereby enhancing write efficiency and memory management. However, when it comes to a programming language, buffering has a downside too. We cannot see the output in real-time. This does not make much of a difference in case of simple or short programs but in complex and long programs that require a lot of computation, this might become a major drawback since we might need a more granular output rather than the entire output being displayed at once for debugging and testing purposes.

Example: Consider the following program for which we shall compare the buffered and unbuffered outputs:

for buffer in range(20): print(buffer, end=" ")

We know that the Output is a range of numbers from 0 to 19, that is

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

But we are more interested in understanding the nature of the output. If buffering is enabled you will get the output at once on the screen after waiting for 19 seconds. However, when buffering is disabled the numbers will be displayed one by one every 2 seconds.

You can try this in our interactive shell:

Exercise: Which behavior do you observe?

How To Disable Output Buffering In Python?

By default output buffering is enabled in Python. Let us have a look at the different ways in which we can disable output buffering in python.

Method 1: Running Python With -u Command Line Arguement

If you want to skip buffering for the entire program then the simplest solution to do this is to run your program using the command line interface and use the -u switch to bypass buffering. The syntax to disable buffering through the command line is:

python -u filename.py

Output

Method 2: Using The Flush Keyword

If you want to skip buffering for specific lines of your code, passing the flush keyword as an argument to the print statement is a good option. By default, the flush argument is set as False. To ensure that output buffering is disabled, the flush argument should be set to True.

Let us have a look at the following example to understand the syntax and usage of the flush keyword:

import time
for buffer in range(20): print(buffer, end=" ", flush=True) time.sleep(2)

Output

This image has an empty alt attribute; its file name is Untitled1.gif

Method 3: Using sys.stdout.flush()

Using the sys.stdout.flush() forces the program to flush the buffer. Therefore everything in the buffer will be displayed on the standard output without delay.

Let us have a look at how sys.stdout.flush() works in the following program:

import time
import sys for buffer in range(20): print(buffer, end=" ") sys.stdout.flush() time.sleep(2)

Output

This image has an empty alt attribute; its file name is Untitled1.gif

Method 4: Wrapping sys.stdout Using TextIOWrapper And Setting Buffered Size = 0

Another approach to disable the output buffering in python is to open up the stdout in write mode with buffer size set to 0 (unbuffered) and then wrapping it using TextIOWrapper to ensure that you get a TextIO stream and not a binary file object. Also, you must ensure to enable the write_through to eliminate all buffers.

Let us have a look at the following code to get a better grip on the above explanation:

# open the stdout file descriptor in write mode and set 0 as the buffer size: unbuffered
import io
import os
import sys
import time try: # open stdout in binary mode, then wrap it in a TextIOWrapper and enable write_through sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True) # for flushing on newlines only use : # sys.stdout.reconfigure(line_buffering=True)
except TypeError: # In case you are on Python 2 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) print("Enter a Line: ")
line = sys.stdin.readline()
for i in line: print(i, end=" ") time.sleep(2)

Output

Method 5: Setting Python Environment Variable PYTHONUNBUFFERED

When the PYTHONUNBUFFERED variable is set to a non-empty string, it is equivalent to the -u command line option.

Conclusion

I hope this article helped you to get an overview of Python output buffering and the methods to disable it. Please stay tuned for more interesting articles.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Python One Line If Not None

To assign the result of a function get_value() to variable x if it is different from None, use the Walrus operator if tmp := get_value(): x = tmp within a single-line if block. The Walrus operator assigns the function’s return value to the variable tmp and returns it at the same time, so that you can check and assign it to variable x subsequently.

Problem: How to assign a value to a variable if it is not equal to None—using only a single line of Python code?

Example: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is. Here’s a code example:

import random def get_value(): if random.random()>0.5: return None return 1 # Naive approach:
x = 42
tmp = get_value()
if tmp != None: x = tmp
print(tmp)

While this works, you need to execute the function get_value() twice which is not optimal. An alternative would be to assign the result of the get_value() function to a temporary variable to avoid repeated function execution:

x = 42
temp = get_value()
if temp != None: x = temp
print(x)

However, this seems clunky and ineffective. Is there a better way?

Let’s have an overview of the one-liners that conditionally assign a value to a given variable:

Exercise: Run the code. Does it always generate the same result?

Method 1: Ternary Operator + Semicolon

The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

You can use the ternary operator to solve this problem in combination with the semicolon to write multiple lines of code as a Python one-liner.

# Method 1
tmp = get_value(); x = tmp if tmp else x

You cannot run the get_value() function twice—to check whether it returns True and to assign the return value to the variable x. Why? Because it’s nondeterministic and may return different values for different executions.

Therefore, the following code would be a blunt mistake:

x = get_value() if get_value() else x

The variable x may still be None—even after the ternary operator has seemingly checked the condition.

Related articles:

Method 2: Walrus + One-Line-If

A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator := is an assignment operator with return value. Thus, it allows you to check a condition and assign a value at the same time:

# Method 2
if tmp := get_value(): x = tmp

This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.

Related Article: The Walrus Operator in Python 3.8

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Python One Line HTTP Get

You may already know about Python’s capability to create a simple web server in a single line of Python code. Old news. Besides, what’s the point of creating a webserver that only runs on your machine? It would be far more interesting to learn how to access existing websites in a single line of code. Surprisingly, nobody talks about this in the Python One-Liners community. Time to change it!

This tutorial shows you how to perform simple HTTP get and post requests to an existing webserver!

Problem: Given the URL location of a webserver serving websites via HTTP. How to access the webserver’s response in a single line of Python code?

Example: Say, you want to accomplish the following:

url = 'https://google.com'
# ... Magic One-Liner Here...
print(result)
# ... Google HTML file: '''
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="de"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title>... '''

You can try it yourself in our interactive Python shell:

Exercise: Does this script download the complete source code of the Google.com website?

Let’s learn about the three most important methods to access a website in a single line of Python code—and how they work!

Method 1: requests.get(url)

The simplest one-liner solution is the following:

import requests; print(requests.get(url = 'https://google.com').text)

Here’s how this one-liner works:

  • Import the Python library requests that handles the details of requesting the websites from the server in an easy-to-process format.
  • Use the requests.get(...) method to access the website and pass the URL 'https://google.com' as an argument so that the function knows which location to access.
  • Access the actual body of the get request (the return value is a request object that also contains some useful meta information like the file type, etc.).
  • Print the result to the shell.

Note that the semicolon is used to one-linerize this method. This is useful if you want to run this command from your operating system with the following command:

python -r "import requests; print(requests.get(url = 'https://google.com').text)"

The output is the desired Google website:

'''
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="de"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title>... '''

Note that you may have to install the requests library with the following command in your operating system terminal:

pip install requests

A similar approach can be taken if you want to issue a post request:

Method 2: requests.post(url)

What if you want to post some data to a web resource? Use the post method of the requests module! Here’s a minimal one-liner example of the request.post() method:

import requests as r; print(r.post('https://example.com', {'key': 'val'}).text)

The approach is similar to the first one:

  • Import the requests module.
  • Call the r.post(...) method.
  • Pass the URL 'https://example.com' as the first parameter into the function.
  • Pass the value to be posted to the URL—in our case a simple key-value pair in a dictionary data structure.
  • Access the body via the text attribute of the request object.
  • Print it to the shell.

Method 3: urllib.request

A recommended way to fetch web resources from a website is the urllib.request() function. This also works to create a simple one-liner to access the Google website in Python 3 as before:

import urllib.request as r; print(r.urlopen('https://google.com').read())

It works similarly than before by returning a Request object that can be accessed to read the server’s response. We’re cramming everything into a single line so that you can run it from your OS’s terminal:

python -r "import urllib.request as r; print(r.urlopen('https://google.com').read())"

Congrats! You now have mastered the art of accessing websites in a single line of Python code. If you’re interested in boosting your one-liner power, have a look at my new book:

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Free e-book: Blazor for ASP.NET Web Forms Developers

Avatar

Nish

We are thrilled to announce the release of our new e-book: Blazor for ASP.NET Web Forms developers. This book caters specifically to ASP.NET Web Forms developers looking for guidelines. As well as strategies for migrating their existing apps to a modern, open-source, and cross-platform web framework.

Blazor E-book for ASP.NET Web Forms

Blazor is a new web framework that changes what is possible when building web apps with .NET. It is also a client-side web UI framework based on C# instead of JavaScript. When paired with .NET running on the server, Blazor enables full-stack web development with .NET. Blazor shares many commonalities with ASP.NET Web Forms. Such as having a reusable component model and a simple way to handle user events. It also builds on the foundations of .NET Core to provide a modern and high-performance web development experience. Additionally, Blazor is a natural solution for ASP.NET Web Forms developers looking to take advantage of client-side development and the open-source, cross-platform future of .NET.

In this book, each Blazor concept is presented in the context of analogous ASP.NET Web Forms features and practices. The book covers:

  • Building Blazor apps.
  • How Blazor works.
  • Blazor’s relation to .NET Core.
  • Reasonable strategies for migrating existing ASP.NET Web Forms apps to Blazor where appropriate.
  • A reference sample that demonstrates the migration strategies used.

Blazor for ASP.NET Web Forms Developers Cover Image
Read Online

Should I Still Use ASP.NET Web Forms?

Of course! As long as the .NET Framework ships as part of Windows, ASP.NET Web Forms will be supported. For many Web Forms developers, the lack of cross-platform and open-source support is a non-issue. If you do not require cross-platform support, open-source, or any other new features in .NET Core or .NET 5, then stick with ASP.NET Web Forms on Windows. ASP.NET Web Forms will continue to be a productive way to write web apps for many years to come!

Other Free E-books

If you are in the path of migrating your existing web and server apps, check out our free e-books on gRPC for WCF Developers. As well as Migrating your .NET App to Azure and more at dot.net/architecture.

Feedback

The book and related reference application will be evolving, so we welcome your feedback! If you have comments about how this book can be improved, please submit feedback.

Posted on Leave a comment

How to Create a Singleton in Python?

Master coders behave like architects that connect and build upon various design patterns to create a functional whole. One of the most important design patterns is a singleton—a class that has only one instance. You may ask: How does that look like? Let’s have a look at the code implementing a singleton in our interactive code shell:

Exercise: Try to create multiple instances of the singleton class. Can you do it?

Let’s dive into a deeper understanding of the singleton. We’ll discuss this code in our first method, so keep reading!

What’s a Singleton?

A singleton is a class that has only one instance. All variables for the class point to the same instance. It is simple and straight forward to create and use and it is one of the design patterns described by the Gang of Four. After creating the first instance, all other creations point to the first instance created. It also solves the problem of having global access to a resource without using global variables. I like this concise definition from Head First Design Patterns:

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Why Would You Need a Singleton?

If you are reading this, you likely already have a possible use. Singleton is one of the Gang of Four’s Creational patterns. Read on to determine if its a good candidate for the problem you need to solve.

A singleton can be used to access a common resource like a database or a file. There is a bit of controversy on its use. In fact, the controversy could be described as outright singleton shaming. If that concerns you, I’ve listed some of the objections below with some links. In spite of all that, singletons can be useful and pythonic. From The Zen of Python (Pythonistas say Ohm):

  • Simple is better than complex
  • Practicality beats purity

Still the objections have merit and may apply to the code you are currently working on. And even if they don’t apply, understanding those objections may give you a better understanding of Object Oriented principals and unit testing.

A singleton may be useful to control access to anything that changes globally when it is used. In addition to databases and files, a singleton may provide benefit for access to these resources:

  • Logger
  • Thread pools
  • caches
  • dialog boxes
  • An Http client
  • handles to preference settings
  • objects for logging
  • handles for device drivers like printers.
  • (?) Any single resource or global collection

A singleton can be used instead of using a global variable. Global variables are potentially messy. Singletons have some advantages over global variables. A singleton can be created with eager or lazy creation. Eager creation can create the resource when the program starts. Lazy creation will create the instance only when it is first needed. Global variables will use an eager creation whether you like it or not. Singletons do not pollute the global namespace.

And finally, a singleton can be a part of a larger design pattern. It may be part of any of the following patterns:

  • abstract factory pattern
  • builder pattern
  • prototype pattern
  • facade pattern
  • state objects pattern If you have not heard of these, no worries. It won’t affect your understanding of the singleton pattern.

Implementation

The standard C# and Java implementations rely on creating a class with a private constructor. Access to the object is given through a method: getInstance()

Here is a typical lazy singleton implementation in Java:
public Singleton { private static Singleton theOnlyInstance; private Singleton() {} public static Singleton getInstance() { if (theOnlyInstance) == null){ theOnlyInstance = new Singleton() } return new Singleton(); }
}

There are many ways to implement Singleton in Python. I will show all four first and discuss them below.

Method 1: Use __new__

class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) # Initialize here. No need to use __init__().. cls.val = 0 return cls._instance def business_method(self, val): self.val = val x = Singleton()
y = Singleton()
x.val = 42
x is y, y.val

It uses the Python dunder __new__ that was added to Python to provide an alternative object creation method. This is the kind of use case __new__ was designed for

Pros:

  • I believe this implementation is the closest in spirit to the GoF implementation. It will look familiar to anybody familiar with the standard Singleton implementation.
    • Easy to understand code meaning is important for teams and maintenance.
  • Uses one class to create and implement the Singleton.

Cons:

  • In spite of its ‘correctness’ many python coders will have to look up __new__ to understand the object creation specifics. Its enough to know that
    1. __new__ instantiates the object.
    2. Code that normally goes in __init__ can be placed in __new__.
    3. In order to work correctly the overridden __new__ must call its parent’s __new__ method. In this case, object is the parent. Instantiaion happens here with this line:
      • object.__new__(class_, *args, **kwargs)

Method 2: A Decorator

def singleton(Cls): singletons = {} def getinstance(*args, **kwargs): if Cls not in singletons: singletons[Cls] = Cls(*args, **kwargs) return singletons[Cls] return getinstance @singleton
class MyClass: def __init__(self): self.val = 3 x = MyClass()
y = MyClass()
x.val = 42
x is y, y.val, type(MyClass)

Pros

  • The code to write the decorator is separate from the class creation.
  • It can be reused to make as many singletons as you need.
  • The singleton decorator marks an intention that is clear and understandable

Cons

  • The call type(MyClass) will resolve as function.
    • Creating a class method in MyClass will result in a syntax error.

If you really want to use a decorator and must retain class definition, there is a way. You could use this library:

pip install singleton_decorator

The library singleton_decorator wraps and renames the singleton class. Alternately you can write your own. Here is an implementation:

def singleton(Cls): class Decorated(Cls): def __init__(self, *args, **kwargs): if hasattr(Cls, '__init__'): Cls.__init__(self, *args, **kwargs) def __repr__(self) : return Cls.__name__ + " obj" __str__ = __repr__ Decorated.__name__ = Cls.__name__ class ClassObject: def __init__(cls): cls.instance = None def __repr__(cls): return Cls.__name__ __str__ = __repr__ def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = Decorated(*args, **kwargs) return cls.instance return ClassObject() @singleton
class MyClass(): pass x = MyClass()
y = MyClass()
x.val = 42
x is y, y.val

The output is:

(True, 42)

Interactive Exercise: Run the following interactive memory visualization. How many singleton instances do you find?

Method 3: Use Metaclass and Inherit From Type and Override __call__ to Trigger or Filter Instance Creation

class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass x = MyClass()
y = MyClass()
x.val=4
x is y, y.val

The output is as follows:

(True, 4)

Method 3 creates a new custom metaclass by inheriting from type. MyClass then assigns Singleton as its metadata:

class MyClass(metadata = Singleton):

The mechanics of the Singleton class are interesting. It creates a dictionary to hold the instantiated singleton objects. The dict keys are the class names. In the overridden __call__ method, super.__call__ is called to create the class instance. See custom metaclass to better understand the __call__ method.

Pros

  • Singleton code is separate. Multiple singletons can be created using the same

Cons

  • Metaclasses remain mysterious for many python coders. Here is what you need to know:
    • In this implementation, type is inherited:
      • class Singleton(type)
    • In order to work correctly the overridden __call__ must call its parent’s __call__ method.
      • cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)

Method 4: Use a Base Class

class Singleton: _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton): pass
x = MyClass()
y = MyClass()
x.val=4
x is y, y.val

The output is as follows:

(True, 4)

Pros

  • Code can be reused to create more singletons
  • Uses familiar tools. (Compared to decorators, metaclasses and the __new__ method)

In all four methods, an instance is created the first time it is asked for one. All calls after the first return the first instance.

Singletons in a Threaded Environment

If your Singleton needs to operate in a multi-threaded environment, then your Singleton method needs to be made thread-safe. None of the methods above is thread-safe. The vulnerable code is found between the check of an existing Singleton and the creation of the first instance:

if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)

Each implementation has a similar piece of code. To make it thread-safe, this code needs to be synchronized.

with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)


This works fine and with the lock in place, the Singleton creation becomes thread-safe. Now, every time a thread runs the code, the threading.Lock() is called before it checks for an existing instance.

If performance is not an issue, that’s great, but we can do better. The locking mechanism is expensive and it only needs to run the first time. The instance creation only happens once so the lock should happen at most one time. The solution is to place the lock after the check statement. Then add another check after the lock.

import threading
... if cls._instance is None: with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)

And that is how to use “Double-checked locking“.

Thread-Safe Version of Method 1

Consider the following modification of method 1:

import threading
class Singleton: _instance = None def __new__(cls): if cls._instance is None: with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) # Initialize here. No need to use __init__().. cls.val = 0 return cls._instance def business_method(self, val): self.val = val x = Singleton()
y = Singleton()
x.val = 42
x is y, y.val

The output is:

(True, 42)

To make it thread-safe, we added two lines of code. Each method could be made thread-safe in a similar way

Alternatives to using a Singleton

Use a Module as a Singleton (The Global Object Pattern)

In Python, modules are single, unique, and globally available. The Global Object Pattern is recommended by the Python docs. It simply means to create a separate module and instantiate your object in the module’s global space. Subsequent references just need to import it.

Use Dependency Injection

Generally, this means using composition to provide objects to dependent objects. It can be implemented in countless ways but generally, put dependencies in constructors and avoid creating new instances of objects in business methods.

The Problems With Singletons

Of all 23 patterns in the seminal 1994 book Design Patterns, Singleton is the most used, the most discussed, and the most panned. It’s a bit of a rabbit hole to sift through the thousands of blogs and Stack Overflow posts that talk about it. But after all the Singleton hating, the pattern remains common. Why is that? It’s because conditions that suggest its use are very common: One database, one config file, one thread pool …

The arguments against its use are best stated in some elegant (and old) blog posts that I cannot match. But I will give a summary and links for further reading.

Concise Summary

Paraphrased from Brian Button in Why Singletons are Evil:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. (That is some effective name-calling. Whatever code smell is, it makes me cringe just a bit and wrinkle my nose as I imagine it).
  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

Should You Use Singletons in Your Code?

If you are asking yourself that based on the other peoples’ blogs, you are already in the rabbit hole. The word ‘should’ is not welcome in code design. Use singletons or not and be aware of possible problems. Refactor when there are problems.

Possible Problems to Consider

Tools are for people who know how to use them. In spite of all the bad stuff written about Singletons, people still use them because:

  1. They fill a need better than the alternatives.

and / or

  1. They don’t know any better and they are creating problems in their code by using them.

Avoid problems. Don’t be in group 2.

Problems with Singletons are caused because they break the single responsibility rule. They do three things:

  1. Guarantee only a single instance exists
  2. Provide global access to that instance
  3. Provide their own business logic.
  • Because they break the single responsibility rule, Singletons may be hard to test
    • Inversion of control IoC and dependency injection are patterns meant to overcome this problem in an object-oriented manner that helps to make testable code.
  • Singletons may cause tightly coupled code. A global instance that has an inconstant state may require an object to depend on the state of the global object.
  • It is an OO principal to Separate Creational Logic from Business Logic. Adhering to this principle “Singletons should never be used”. Again with the word should. Instead, Be Yoda: “Do or do not!“. Base the decision on your own code.
  • Memory allocated to a Singleton can’t be freed. This is only a problem it the memory needs to be freed.
    • In a garbage collected environment singletons may become a memory management issue.

Further Study

Meta notes — Miško Hevery.

Hevery worked at Google when he wrote these blogs. His blogs were readable, entertaining, informative, provocative, and generally overstated to make a point. If you read his blogs, be sure to read the comments. Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but he makes a valid point:

Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.

Of course, he is overstating a bit. Singletons wrap global state in a class and are used for things that are ‘naturally’ global by nature. Generally, Hevery recommends dependency injection to replace Singletons. That simply means objects are handed their dependencies in their constructor.

Where have all the singletons gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the Pathological Liars.

Meta notes — Brandon Rhodes The Singleton Pattern

Python programmers almost never implement the Singleton Pattern as described in the Gang of Four book, whose Singleton class forbids normal instantiation and instead offers a class method that returns the singleton instance. Python is more elegant, and lets a class continue to support the normal syntax for instantiation while defining a custom __new__() method that returns the singleton instance. But an even more Pythonic approach, if your design forces you to offer global access to a singleton object, is to use The Global Object Pattern instead.

Meta notes — J.B. Rainsberger Use your singletons wisely

Know when to use singletons, and when to leave them behind

J.B. Rainsberger

Published on July 01, 2001 Automated unit testing is most effective when:

  • Coupling between classes is only as strong as it needs to be
  • It is simple to use mock implementations of collaborating classes in place of production implementations
Singletons know too much

There is one implementation anti-pattern that flourishes in an application with too many singletons: the I know where you live anti-pattern. This occurs when, among collaborating classes, one class knows where to get instances of the other.

Towards acceptible singletons

Singleton abuse can be avoided by looking at the problem from a different angle. Suppose an application needs only one instance of a class and the application configures that class at startup: Why should the class itself be responsible for being a singleton? It seems quite logical for the application to take on this responsibility, since the application requires this kind of behavior. The application, not the component, should be the singleton. The application then makes an instance of the component available for any application-specific code to use. When an application uses several such components, it can aggregate them into what we have called a toolbox.

Meta notes — Mark Safayan Singleton anti pattern

Instead of using this pattern, simply instantiate a single instance and propagate it to places that use the object as a parameter to make the dependency explicit.

Posted on Leave a comment

Hello World! A Python One-Liner to Get Started with Python Quickly

The “hello world program” is used in programming languages to set up a minimal programming environment and execute the first trivial program in it. It helps you get your environment going and take your first steps towards a more complicated program. This short tutorial will show you the fastest possible way to write your first hello world program — as a Python one-liner!

Before I show you how to install Python on your computer, follow the following steps to run your first Python "hello world" program in your browser!

Run Your Hello World One-Liner in Your Browser Shell

Step 1: Here’s an interactive browser-based shell:

The shell runs any Python program in your browser.

Step 2: Type the print function in your browser shell with opening and closing parentheses that are initially empty:

print()

The print() function takes a string and prints it to your shell. This way, you can generate outputs in your program. Think about it: a Python program is only a means to an end. It transform an input to an output. One way of creating an output is to print program values to the shell. In our hello world one-liner, the output is the textual data (=string) 'hello world'.

Step 3: Pass the 'hello world' string into the print() function between the parentheses.

print('hello world')

Congratulations, your first hello world one-liner is ready! Now, there’s only one thing left:

Step 4: Run the hello world one-liner program by hitting the “Run” symbol ▶.

Can you see the output generated by your program? When running your program in the interactive shell, the result should be the following output:

hello world

Make sure that you see this output in your shell before you move on!

Install Python on Your Computer

Now, you know how to run your first program. If you want to start your first serious project though, you’ll need Python on your local machine.

Follow these seven steps to install Python on your computer (Windows):

  1. Visit website “Python Releases for Windows”: https://www.python.org/downloads/windows/
  2. Click link “Download Windows x86-64 executable installer” under “Stable Releases” header.
  3. A popup opens. Click “Save File”.
  4. Wait until the download completes and double click on the installer file to run it.
  5. Another popup appears. Select “Add Python to Path” and click “Install Now”.
  6. Wait until the installation completes “Setup was successful”.
  7. You can now use Python on your Windows computer: use the Windows Search for “IDLE” and open the standard Python editor to start coding.

The steps are almost identical for MacOS and Linux, you can figure them out easily. In this video, I’ll guide you through the process in a step-by-step manner:

Related Article: 7 Steps to Set Up Python on Windows

Learn the Python Basics

An excellent way to start learning Python is through Python cheat sheets. They focus on the relevant parts and introduce the most important concepts in the shortest possible time. Here’s such a Python cheat sheet for you:

Python Ultimate Cheat Sheet

You can download this and more cheat sheets in my interactive Python email course (that’s also 100% free). Check it out for continuous improvement in Python by reading a series of course email lessons I’ll send you into your INBOX. Free Python cheat sheets are included!

*** Join FREE Python Cheat Sheet Email Academy ***