Thursday, June 1, 2017

What Are Python Namespaces (And Why Are They Needed?)

Name conflicts happen all the time in real life. For example, every school that I ever went to had at least two students in my class who shared the same first name. If someone came into the class and asked for student X, we would enthusiastically ask, "Which one are you talking about? There are two students named X." After that, the inquiring person would give us a last name, and we would introduce him to the right X.

All this confusion and the process of determining the exact person we are talking about by looking for other information besides a first name could be avoided if everyone had a unique name. This is not a problem in a class of 30 students. However, it will become increasingly difficult to come up with a unique, meaningful and easy-to-remember name for every child in a school, town, city, country, or the whole world. Another issue in providing every child a unique name is that the process of determining if someone else has also named their child Macey, Maci or Macie could be very tiring.

A very similar conflict can also arise in programming. When you are writing a program of just 30 lines with no external dependencies, it is very easy to give unique and meaningful names to all your variables. The problem arises when there are thousands of lines in a program and you have loaded some external modules as well. In this tutorial, you will learn about namespaces, their importance, and scope resolution in Python. 

What Are Namespaces?

A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict. You might already know that everything in Python—like strings, lists, functions, etc.—is an object. Another interesting fact is that Python implements namespaces as dictionaries. There is a name-to-object mapping, with the names as keys and the objects as values. Multiple namespaces can use the same name and map it to a different object. Here are a few examples of namespaces:

  • Local Namespace: This namespace includes local names inside a function. This namespace is created when a function is called, and it only lasts until the function returns.
  • Global Namespace: This namespace includes names from various imported modules that you are using in a project. It is created when the module is included in the project, and it lasts until the script ends.
  • Built-in Namespace: This namespace includes built-in functions and built-in exception names.

In the Mathematical Modules in Python series on Envato Tuts+, I wrote about useful mathematical functions available in different modules. For example, the math and cmath modules have a lot of functions that are common to both of them, like log10(), acos(), cos(), exp(), etc. If you are using both of these modules in the same program, the only way to use these functions unambiguously is to prefix them with the name of the module, like math.log10() and cmath.log10().

What Is Scope?

Namespaces help us uniquely identify all the names inside a program. However, this doesn't imply that we can use a variable name anywhere we want. A name also has a scope that defines the parts of the program where you could use that name without using any prefix. Just like namespaces, there are also multiple scopes in a program. Here is a list of some scopes that can exist during the execution of a program.

  • A local scope, which is the innermost scope that contains a list of local names available in the current function.
  • A scope of all the enclosing functions. The search for a name starts from the nearest enclosing scope and moves outwards.
  • A module level scope that contains all the global names from the current module.
  • The outermost scope that contains a list of all the built-in names. This scope is searched last to find the name that you referenced. 

In the coming sections of this tutorial, we will extensively use the built-in Python dir() function to return a list of names in the current local scope. This will help you understand the concept of namespaces and scope more clearly.

Scope Resolution

As I mentioned in the previous section, the search for a given name starts from the innermost function and then moves higher and higher until the program can map that name to an object. When no such name is found in any of the namespaces, the program raises a NameError exception.

Before we begin, try typing dir() in IDLE or any other Python IDE.

All these names listed by dir() are available in every Python program. For the sake of brevity, I will start referring to them as '__builtins__'...'__spec__' in the rest of the examples.

Let's see the output of the dir() function after defining a variable and a function.

The dir() function only outputs the list of names inside the current scope. That's why inside the scope of some_func(), there is only one name called b_num. Calling dir() after defining some_func() adds it to the list of names available in the global namespace.

Now, let's see the list of names inside some nested functions. The code in this block continues from the previous block.

The above code defines two variables and a function inside the scope of outer_func(). Inside inner_func(), the dir() function only prints the name d_num. This seems fair as d_num is the only variable defined in there.

Unless explicitly specified by using global, reassigning a global name inside a local namespace creates a new local variable with the same name. This is evident from the following code.

Inside both the outer_func() and inner_func(), a_num has been declared to be a global variable. We are just setting a different value for the same global variable. This is the reason that the value of a_num at all locations is 20. On the other hand, each function creates its own b_num variable with a local scope, and the print() function prints the value of this locally scoped variable.

Properly Importing Modules

It is very common to import external modules in your projects to speed up development. There are three different ways of importing modules. In this section, you will learn about all these methods, discussing their pros and cons in detail.

  • from module import *: This method of importing a module imports all the names from the given module directly in your current namespace. You might be tempted to use this method because it allows you to use a function directly without adding the name of the module as a prefix. However, it is very error prone, and you also lose the ability to tell which module actually imported that function. Here is an example of using this method:

If you are familiar with the math and cmath modules, you already know that there are a few common names that are defined in both these modules but apply to real and complex numbers respectively. 

Since we have imported the cmath module after the math module, it overwrites the function definitions of these common functions from the math module. This is why the first log10(125) returns a real number and the second log10(125) returns a complex number. There is no way for you to use the log10() function from the math module now. Even if you tried typing math.log10(125), you will get a NameError exception because math does not actually exist in the namespace.

The bottom line is that you should not use this way of importing functions from different modules just to save a few keystrokes.

  • from module import nameA, nameB: If you know that you are only going to use one or two names from a module, you can import them directly using this method. This way, you can write the code more concisely while still keeping the namespace pollution to a minimum. However, keep in mind that you still cannot use any other name from the module by using module.nameZ. Any function that has the same name in your program will also overwrite the definition of that function imported from the module. This will make the imported function unusable. Here is an example of using this method:
  • import module: This is the safest and recommended way of importing a module. The only downside is that you will have to prefix the name of the module to all the names that you are going to use in the program. However, you will be able to avoid namespace pollution and also define functions whose names match the name of functions from the module.

Final Thoughts

I hope this tutorial helped you understand namespaces and their importance. You should now be able to determine the scope of different names in a program and avoid potential pitfalls. 

Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

The final section of the article discussed different ways of importing modules in Python and the pros and cons of each of them. If you have any questions related to this topic, please let me know in the comments.


by Monty Shokeen via Envato Tuts+ Code

How to Engage Prospects on LinkedIn: A 5-Step Plan for Better Leads

Wondering how to effectively engage your LinkedIn prospects? Interested in tips for nurturing prospects on LinkedIn? LinkedIn offers unique opportunities to move people from leads to customers. In this article, you’ll discover a five-step plan for turning cold LinkedIn prospects into warm leads. #1: Start With a LinkedIn Summary That Conveys Your Value Before you can [...]

This post How to Engage Prospects on LinkedIn: A 5-Step Plan for Better Leads first appeared on .
- Your Guide to the Social Media Jungle


by Kylie Chown via

Google I/O 2017 Aftermath: Building Lifecycle-Aware Components

As usual, this year’s Google I/O saw plenty of Android-related announcements.

In this series of quick tips, we’re going to take a closer look at some of the software updates and new releases you can get your hands on today

In this first post, we’re going to look at a collection of libraries that aims to take the pain out of lifecycle management, by giving you a way to build lifecycle-aware components that can track and react to lifecycle events automatically. I’ll also be providing a brief introduction to two other components that have been designed to use with these new lifecycle-aware components: LiveData and Room.

LifecycleOwner and LifecycleObserver

Respecting the lifecycle of your Activitys and Fragments is crucial to creating a successful app. Get these fundamentals wrong, and you’re going to wind up with memory leaks that cause your app to lag, and potentially even crash.

Another recurring problem you may encounter with lifecycle management is attempting to update your app’s UI when the activity or fragment isn’t in a valid state. For example, if an Activity receives a callback after it’s been stopped, then it’s pretty likely that your app is going to crash. 

To help you avoid all the headaches that come with lifecycle management, Google has announced a new set of lifecycle-aware components that can track the lifecycle of an activity or fragment, and adjust their behaviour accordingly.

You can access these Android Architecture Components via Google’s Maven repository today. However, they are still in alpha, so you should expect some breaking changes before the 1.0 release. 

In particular, the Fragment and AppCompatActivity classes currently cannot implement the new LifecycleOwner interface. You'll need to use the temporary LifecycleActivity and LifecycleFragment classes until the Android Architecture Components reach their 1.0 release. These classes will be deprecated as soon as Android’s fragments and Activities have been updated to support the lifecycle components.

To start experimenting with these components, you’ll need to add the Google Maven repository to your project-level build.gradle file:

Then, open your module-level build.gradle file, and add the following:

There are a few Android Architecture Components, but in this article we’re just going to focus on the following two:

  • LifecycleOwnerThis is something that has a lifecycle, such as an Activity or Fragment.
  • LifecycleObserverThis is a class that can monitor a component's lifecycle status via annotated methods. These methods are called whenever the associated component enters the corresponding lifecycle state.

By moving the code that monitors and reacts to lifecycle events into a separate LifecycleObserver, you can prevent your activity or fragment’s lifecycle-related methods (such as onStart and onStop) from ballooning out of control, making your code much more human-readable.

In the following example, we’re implementing LifecycleObserver, and then using the @OnLifeCycleEvent to react to various lifecycle events:

Then, in the Activity you want to monitor, extend LifecycleActivity to get access to the LifecycleObserver information:

Many operations can only be performed when a fragment or activity is in a specific state. You can use lifecycle.getState to quickly and easily check the component’s current state, and then only perform the action if the component is in the correct state:

LiveData

LiveData is an observable data holder that exposes a stream of events that you can observe.

The key difference between LiveData and other observables, such as RxJava, is that LiveData is aware of the Android lifecycle. LiveData respects the lifecycle state of your Activities, fragments, and services, and will manage subscriptions for you.

Crucially, if an observer’s lifecycle is inactive, then the observer won’t be notified about changes to the LiveData, preventing application crashes that can occur when you try to push updates to stopped components.

To use LiveData, you just need to tell your Activity that you want to observe some data within the lifecycle:

As soon as the activity starts, it’ll begin observing the LiveData, and your observer will receive an update whenever the value of that LiveData changes. If the Activity is destroyed, then the subscription will be removed automatically.

If an Activity is stopped due to a configuration change, then the new instance of that Activity will receive the last available value from the LiveData.

LiveData does share some similarities with RxJava, but the official word from Google I/O is that if you’re familiar with RxJava, then you should start your Android projects with LiveData, as it’s designed to be simple, fast and lightweight, and integrates well with the Android framework. You can then add RxJava features if you need additional reactive programming functionality.

If you do want to use LiveData with the RxJava 2 library, then open your module-level build.gradle file and add the following:

You’ll then be able to use the following methods: 

  • toPublisherAdapts the LiveData stream to a ReactiveStreams Publisher

  • fromPublisherCreates an observable LiveData stream from a ReactiveStreams publisher. 

The Room Library

Although the Android framework has built-in support for working with raw SQL content, these APIs are fairly low-level and time-consuming to implement.

Google’s new Room library promises to abstract away some of the underlying implementation details of working with raw SQL tables and queries. It should also help reduce the amount of boilerplate code you need to write in order to convert SQL queries into Java data objects, and it features a Migration class that you can use to update your app without losing the user’s data. 

To use Room, open your module-level build.gradle file and add the following to the dependencies section:

When performing queries, you'll typically want your UI to update automatically whenever the data changes; with Room, you can achieve this by using a return value type of LiveData.

Finally, if you’re using RxJava, then your Room queries can also return RxJava 2’s Publisher and Flowable objects. To use RxJava with Room, you’ll need to open your module-level build.gradle file and add the following to the dependencies section:

Conclusion

In this quick tip, I showed you how to manage the Android lifecycle, using LifecycleOwner and LifecycleObserver, and introduced you to two additional components you may want to use alongside the Lifecycle project. 

In the next tip, we’re going to look at Google’s plans to merge Android Wear UI components with the Android Support Library, as well as some additions to Android Wear complications. 

In the meantime, check out some of our other tutorials and our video courses on Android app development!

  • Android
    Create a Voice-Controlled Android App
    Ashraff Hathibelagal
  • Android SDK
    Serverless Apps With Firebase Cloud Functions
    Chike Mgbemena
  • Android SDK
    Reactive Programming Operators in RxJava 2
    Jessica Thornsby

by Jessica Thornsby via Envato Tuts+ Code

Tekt

Tekt - A layout template for Elementor Page Builder

'Tekt' is a slick Landing Page template built for the powerful Elementor page builder for WordPress. All you need to use this template is a WordPress installation and the free Elementor plugin. Features include big image intro, clear services section, client logos, work examples, team, testimonials and a contact section with Google Maps integration. I'd imagine 'Tekt' would suit a corporate portfolio, architects, construction companies or even interior designers.

by Rob Hope via One Page Love

Multiple States x Two of Us

Interactive, experimental One Page collaboration between Multiple States and Two of Us where you click and drag corners to create new shapes.

by Rob Hope via One Page Love

Join the UX Mastery Book Club!

We love books here at UX Mastery. Without a doubt, reading is one of the most straightforward and accessible ways to build up your UX knowledge. Even better is having the opportunity to discuss, question, and confirm your understanding with your peers.

That’s why we decided to start the UX Mastery online book club! With so many fantastic books on UX and related topics, we hope we can give you that extra motivation to get reading.

Our very first book, decided by popular vote is The Design of Everyday Things by Don Norman.

It’s available on Amazon2 for $12.85 (Kindle) or $13.61 (Print)

Here’s a blurb about the book:

Even the smartest among us can feel inept as we fail to figure out which light switch or oven burner to turn on, or whether to push, pull, or slide a door. The fault, argues this ingenious-even liberating-book, lies not in ourselves, but in product design that ignores the needs of users and the principles of cognitive psychology. The problems range from ambiguous and hidden controls to arbitrary relationships between controls and functions, coupled with a lack of feedback or other assistance and unreasonable demands on memorization.
 

The Design of Everyday Things shows that good, usable design is possible. The rules are simple: make things visible, exploit natural relationships that couple function and control, and make intelligent use of constraints. The goal: guide the user effortlessly to the right action on the right control at the right time.

The Design of Everyday Things is a powerful primer on how-and why-some products satisfy customers while others only frustrate them.

How book club will work

All book club related activity will take place over in the UX Mastery forums in the Book Club category.

Every week we’ll read a chapter, then discuss in forums.

We will kick off each week with one or two broad questions to consider before reading, a couple of key observations to go through on your own directly after reading, and then open it right up for opinions and other questions in weekly discussion thread.

How to get involved

Right now
Introduce yourself and say hi to everyone here

4 June
Deadline for buying your book – details above

5 June
Begin reading first chapter, with one chapter per week after that.
We’ll start a new discussion thread at the beginning of each week.

Find all the details over in the forums.

Happy reading!

The post Join the UX Mastery Book Club! appeared first on UX Mastery.


by Natassja Hoogstad Hay via UX Mastery

Departures International

Your global guide to luxe travel, style and more. Curated for international Platinum Card® members from American Express®
by via Awwwards - Sites of the day