Mertie  Feil

Mertie Feil

1597364940

What Are .self, .Type, and .Protocol?

Ah, metatypes. That’s another one for the list of things I use everyday but couldn’t explain in an interview if my life depended on it.

Metatypes are pretty useful in Swift, and you have certainly used it on multiple occasions. Unfortunately they look pretty weird in code, which can cause some confusion when trying to understand what they really are.

I know how these weird suffixes can confuse you, but don’t worry, they’re actually pretty straightforward once you get to know the differences between each of them. But before getting into that, let’s take a step back.

What’s a Metatype?

If you take a look at Apple’s docs, you’ll see that a metatype is defined as being the type of a type. Wait, isn’t String a type? What could possibly be type of a String that’s already a type? SuperString??

#swift #xcode #ios #.protocol #.type #.self

What is GEEK

Buddha Community

What Are .self, .Type, and .Protocol?
Mertie  Feil

Mertie Feil

1597364940

What Are .self, .Type, and .Protocol?

Ah, metatypes. That’s another one for the list of things I use everyday but couldn’t explain in an interview if my life depended on it.

Metatypes are pretty useful in Swift, and you have certainly used it on multiple occasions. Unfortunately they look pretty weird in code, which can cause some confusion when trying to understand what they really are.

I know how these weird suffixes can confuse you, but don’t worry, they’re actually pretty straightforward once you get to know the differences between each of them. But before getting into that, let’s take a step back.

What’s a Metatype?

If you take a look at Apple’s docs, you’ll see that a metatype is defined as being the type of a type. Wait, isn’t String a type? What could possibly be type of a String that’s already a type? SuperString??

#swift #xcode #ios #.protocol #.type #.self

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Ray  Patel

Ray Patel

1623121920

Python typing and validation with mypy and pydantic.

Python is a dynamically typed programming language, which means the types are only checked at runtime and a variable is allowed to change its type over its lifetime, whereas a statically typed language like Java checks the types at compile-time, and a variable is not allowed to change its type over its lifetime. On the other hand, Python is a strongly typed language because the types cannot be automatically converted at runtime. For example, you cannot have an addition calculation on integer 1 and string "2", while in a weakly typed language such as JavaScript such calculation is allowed.

Even though dynamic typing can make it faster to write Python code in the development stage, it is also very easy to introduce bugs and errors which can only be identified at runtime. Besides, with no type definitions, the code can be more difficult to read and maintain. For example, you need to read through a function to get to know what type of data would be returned by it. However, with type hints or type annotations, the return type of a function can be known immediately. Once a program is developed, you would rarely need to rewrite or redesign it. However, it is much more common that you or your colleagues need to read or maintain it after some time. Therefore, making the code easier to read would be very important, especially if you work in a team where people have to review each other’s code.

Typing has become more and more important in Python and the type hint standards introduced in PEP484 make it possible and easy to add type annotations to your Python code. After type hints have been added to a Python file, the mypy library can be used to do static type checking before it is run. Besides, pydantic, a data validation library using Python type annotations, can enforce type hints at runtime and provide user-friendly errors when data is invalid.

#python #mypy #pydantic #typing #type-hints #python typing and validation with mypy and pydantic.

Ari  Bogisich

Ari Bogisich

1595762400

Stretching the Reach of Implicitly Typed Variables in C#

Image for post

Type inference is a common feature among mainstream programming languages. The functional ones, like ML and Haskell, are pioneers in exploring this programming paradigm where the declaration of a variable or a function may omit a type annotation. Today, even classic imperative languages such as C++ offer, to a certain extent, a kind of type inference.

C# is not an exception to the ever-increasing popularity of inference-enabled languages: since C# 3.0, developers may declare implicitly typed variables with the var keyword (in C++ 11, a similar feature was introduced — re-targeting the then-existing auto keyword). This functionality, however, falls under a provision: a declaration must be accompanied by an initializer.

Although one would not expect to see ML and Haskell’s “whole-program type inference” in C#, could this initializer requirement be relaxed? Why does it exist, altogether?

  • Is it due to any limitation or just a matter of taste?
  • Could the variable’s type be inferred from arbitrary expressions?
  • If yes, what are trade-offs from a language-design perspective?

In this article, I will describe the foundation of a standard type inference technique and ramble about the questions above.

Non-initializing Declarations

What do you answer when someone asks: why is it necessary, in C#, that a local var-declared variable is accompanied with an _initializer? _The accurate reply to this question is: because the language specification says so; it is not because the type would not be inferable otherwise. Consider function f.

The two statements above (a declaration- and an expression-statement) are not fundamentally different from the single statement var num = 42;. In fact, if permitted, the _Intermediate Language _(IL) code produced for the former would probably be equal to that produced for the latter. Also, one may easily observe that int is a valid replacement for var in f.

To set the stage for our discussion, let us quote — with minor adjustments for pedagogical reasons — the relevant fragment of the C# specification to which var is subject:

“When the local variable type is specified as var… the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression.”

Another characteristic of C# is that a variable must be definitely assigned before we attempt to obtain its value. Let us also quote the language specification fragment that states such mandatory assignment.

“For an initially unassigned variable to be considered definitely assigned… , an assignment to the variable must occur in every possible execution path…”

It is not my intent to enter the pedantic realm of language specifications. Yet, based on our (informal) observation that var num; num = 42; is equivalent to var num = 42;; and the fact that a variable must be assigned before being used, could we slightly stretch the functionality provided by var?

Image for post

#type-systems #hindley-milner #type-theory #type-inference #csharp #programming-c

Mikel  Okuneva

Mikel Okuneva

1604091600

Some Helpful Extensions When Dealing With Types in .NET

If you are writing reusable code, chances are high that you will write quite some code that deals with types, generics, and interfaces. Over the years, the collection of my helper extensions for that have grown. As some of my upcoming posts use them, I share them (also) for future reference.

1. Check if a Type Is Deriving From Another Type

Deriving types is a common practice. To some extent, you can use pattern matching. Sometimes, that isn’t enough, though (especially if you have a multi-level derivation path). This is when I use one of these two extensions:

Java

1

        public static bool IsDerivingFrom(this Type type, Type searchType)

2

        {

3

            if (type == null) throw new NullReferenceException();

4

5

            return

6

                type.BaseType != null &&

7

                (type.BaseType == searchType ||

8

                type.BaseType.IsDerivingFrom(searchType));

9

        }

10

11

        public static bool IsDerivingFromGenericType(this Type type, Type searchGenericType)

12

        {

13

            if (type == null) throw new ArgumentNullException(nameof(type));

14

            if (searchGenericType == null) throw new ArgumentNullException(nameof(searchGenericType));

15

16

            return

17

                type != typeof(object) &&

18

                (type.IsGenericType &&

19

                searchGenericType.GetGenericTypeDefinition() == searchGenericType ||

20

                IsDerivingFromGenericType(type.BaseType, searchGenericType));

21

        }

Update 1: Type.IsSubclassOf will give you the same result as IsDerivingFrom. The main purpose was (is) to use my implementation when having multiple levels of derivation and being able to debug the whole detection process.

2. Get Type of T From IEnumerable

Sometimes, one needs to know the item type of an IEnumerable. These two extensions will help you in this case:

Java

1

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Extension method")]

2

        public static Type GetItemType<T>(this IEnumerable<T> enumerable) => typeof(T);

3

4

        public static Type? GetItemType(this object enumerable)

5

            => enumerable == null ? null :

6

            (enumerable.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()[0]);

3. Check if a Type Implements a Certain Interface

Interfaces are supposed to make the life of a developer easier. Like with the type derivation, sometimes we need to know if a type implements a certain interface. This extension answers the question for you:

Java

1

        public static bool ImplementsInterface(this Type? type, Type? @interface)

2

        {

3

            bool result = false;

4

5

            if (type == null || @interface == null)

6

                return result;

7

8

            var interfaces = type.GetInterfaces();

9

            if (@interface.IsGenericTypeDefinition)

10

            {

11

                foreach (var item in interfaces)

12

                {

13

                    if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)

14

                        result = true;

15

                }

16

            }

17

            else

18

            {

19

                foreach (var item in interfaces)

20

                {

21

                    if (item == @interface)

22

                        result = true;

23

                }

24

            }

25

26

            return result;

27

        }

Update 2: Type.IsAssignableFrom will also tell you if a type implements an interface. As for the IsDerivingFrom method, I wanted to be able to debug the detection, which is - besides from having an explicit implementation - the main reason for this method.

#web dev #mvvm #interface #types #type #assembly #extension methods #dev stories #helper #msicc