Zara  Bryant

Zara Bryant

1563597135

Pointers in Python: What's the Point?

Pointers can be a complicated concept in programming languages. C and C++ are known for having pointers, but what about Python? It does! Let’s explore some exciting things about pointers in Python.

Table Of Contents

  1. What are Pointers?

  2. Pointers in Python?

  3. Objects

    3.1. Immutable Objects

    3.2. Mutable Objects

  4. Pythons’ Object Model

    4.1. C Variables

    4.2. Python Names

  5. Faking Pointers in Python

    5.1. Using Mutable Objects

  6. Pointers with ctypes

1. What are Pointers?

Pointers are variables which store the address of other variables. It’s a data type which stores the address of other data types. If you are familiar with C or C++, then you are familiar with what pointers are?

Whenever we create a variable or an object in a programming language, it’s stored in a particular CPU address. Whenever we output the data, it pulls from that address. Pointers are used to store the addresses and for memory management. But, at times pointers can crash our programs. Let’s get into the details.

2. Pointers in Python

Python doesn’t have any pointers concept. Why doesn’t Python speak about pointers? The reason is unknown. Maybe because of the difficulty level of pointers which is against the Zen of Python. Python focuses on its simplicity instead of speed. We can implement pointers in Python with the help of other objects.

We have to first understand some concepts in Python before diving into the pointers. Let’s first see what objects are? And types in it.

3. Objects

Everything in Python is an object.

If you are new to Python, run the following programs as proof for the above statement.

## int
print(f'int:- {isinstance(int, object)}')
 
## str
print(f'str:- {isinstance(str, object)}')
 
## bool
print(f'bool:- {isinstance(False, object)}')
 
## list
print(f'list:- {isinstance(list(), object)}')
 
## function
def sample():
    pass
 
print(f'function:- {isinstance(sample, object)}')

int:- True
str:- True
bool:- True
list:- True
function:- True

As you see, everything in Python is an object. Each object in Python consists of three parts.

  1. Reference Count

It deals with the memory in the CPU. It represents the number of Python variables referring to a memory location.

  1. Type

It refers to the kind of object like int, float, string, etc…,

  1. Value

It’s the actual value of an object stored in the memory.

Objects are of two types Immutable and Mutable. Knowing about these objects will clear the first step of our pointers. Let’s first see the immutable and mutable.

3.1. Immutable Objects

We can’t change the immutable objects once we create them. Most of the commonly used data types in Python are immutable. Let’s see what that means.

We can test whether an object is immutable or mutable by using id() and is.

  • id() returns the memory address of the object.
  • is checks whether two objects have the same memory address or not.

int is an immutable object. Let’s see with an example.

a = 7 
id(a)

1744268544 

We have assigned 7 to the a. We can’t modify the value of x in 1744268544 memory. If we try to change it, it will create a new object. Let’s see by adding one to the a.

a += 1 
id(a)

1744268576 

The address of a is changed. That means the object we created first, is now referring to the new address.

b = a b is a

True 

When we assign a to b, Python doesn’t create a new object. It merely made reference of b to a value. It saves memory.

3.2. Mutable Objects

We can change the mutable objects even after creation. Python doesn’t create new objects when we modify a mutable object. Let’s see with some examples.

## list is a mutable object
nums = [1, 2, 3, 4, 5]
print("---------Before Modifying------------")
print(id(nums))
print()
 
## modifying element
nums[0] += 1
print("-----------After Modifying Element-------------")
print(id(nums))
print()
 
## appending an element
nums.append(6)
print("-----------After Appending Element-------------")
print(id(nums))

---------Before Modifying------------
2197288429320
 
-----------After Modifying Element-------------
2197288429320
 
-----------After Appending Element-------------
2197288429320

Even after performing some operations on the list, the address doesn’t change. Because the list is a mutable object. The same thing occurs when we perform other mutable objects like set or dict.

Now you know the difference between immutable and mutable objects. This makes the upcoming concepts easy to understand.

4. Pythons’ Object Model

Python variables are different from C. First, we will learn how variables work in C for better understanding of pointers.

4.1. C Variables

C variables memory management is entirely different from Python. Let’s see how to define a variable in C and the steps it goes through when executed.

// C syntax not Python 
int a = 918

Execution steps of the above statement.

  • Allocates memory for the integer.
  • Assigns a value to the variable a.
  • Makes a refer to the value of 918.

If we illustrate the memory, it may look like the following.

Here, a has a memory location of 0x531. If we update the value of a. The address location of a doesn’t change.

a = 849

If we see the location of a didn’t change in C programming language, the variable is not just a name for the value. It’s a memory location itself. So, we are overwriting the value of a memory location directly. It’s completely different from Python.

If we want to assign a to another variable, then C creates a new memory location, unlike Python. The following code assigns a to a new variable b.

int b = a 

Notice that the address of b has changed. It’s because the C creates a new memory location for every variable we create. C creates a new memory location for b and copies the values of a and assigns them to b.

This how C variables work. Now, let’s move on to find out how Python variables work.

4.2. Python Names

Generally, variables in the Python are called names.

## code in python 
a = 918

The above code will undergo the following steps during execution.

  • Creates a new PyObject.
  • Sets data type as an integer for PyObject.
  • Sets the value 918 to the PyObject.
  • Creates a name as we define (a).
  • Points a to the PyObject.
  • Increments the Refer Count of PyObject from 0 to 1.

In memory, a may look like the following.

a reference memory location illustration

a refers to the above PyObject in the memory. It’s completely different from C variables. a is not a memory location as it was in C variables.

a = 98

The above statement undergoes the following steps during execution.

  • Creates a new PyObject.
  • Sets data type as an integer for PyObject.
  • Sets the value 98 to the PyObject.
  • Points a to the new PyObject.
  • Increments the Refer Count of the new PyObject by 1.
  • Decrements the Refer Count of the old PyObject by 1.

In memory a refers to the new PyObject. So, the old PyObject refer count will be 0.

New PyObject

a refers to the immediate below PyObject

Old PyObject

The old PyObject reference count is 0. Because the variable a refers to the new PyObject.

What happens when we assign a to a new variable b? Let’s see…

b = a

Python doesn’t create a new PyObject for the variable b. Python makes the reference count of a’s PyObject to two. Those two variables are a and b.

a and b refers the same PyObject

To see whether a and b referred to the same memory location or not, run the following code.

a is b

True 

is returns True both variables refer to the same PyObject. If we modify the value of b Python creates a new PyObject for b because integers are immutable in Python. Now, you are familiar with the Pythons’ object model.

5. Faking Pointers in Python

Developers of Python didn’t include pointers in Python. But still, we can stimulate the pointers in Python using different methods.

Let’s write a small function in C, which takes a pointer as an argument and increments the value of variables present in that memory location.

// C code
void increment(int *p) {
    *p += 1;
}

The increment function takes a pointer and increments the value of the pointer referring variable. Let’s write the main function.

// C code main function
void main() {
    int a = 759;
    printf("%d\n", a);
    increment(&a);    // & operator used to extract the adress of the variable
    printf("%d\n", a);
}

// Output
759
769

Now, we are going to implement the same behavior in Python using mutable objects. Let’s see…

5.1. Using Mutable Objects

We can replicate the above program using mutable objects in Python. Let’s see how we can do this.

## function
def increment(p):
    p[0] += 1
 
if __name__ == "__main__":
    a = [759]
    increment(a)
    print(a[0])

760

We have achieved the same result without changing the memory location of the variable. The function increment takes a list and increments the first element. That’s it. We have achieved the same because lists are mutable. If we try to pass a tuple as an argument to the increment function, we will get an error.

if __name__ == "__main__":
    a = (759,)
    increment(a)
    print(a[0])

---------------------------------------------------------------------------
 
TypeError                                 Traceback (most recent call last)
 
<ipython-input-32-c3bce5df94da> in <module>()
      1 if __name__ == "__main__":
      2     a = (759,)
----> 3     increment(a)
      4     print(a[0])
 
 
<ipython-input-30-042f4c577fd9> in increment(p)
      1 ## function
      2 def increment(p):
----> 3     p[0] += 1
      4
      5 if __name__ == "__main__":
 
 
TypeError: 'tuple' object does not support item assignment

These are not real pointers like C. All we did was replicate the behavior of pointers in Python.

6. Pointers with ctypes

Using ctypes module, we can create real pointers in Python. First, we will compile a .c file containing functions which use pointers and store it. Let’s write the following function into a .c file

void increment(int *p) {
    *p += 1;
}

Let’s assume the file name is increment.c and run the following commands.

$ gcc -c -Wall -Werror -fpic increment.c

$ gcc -shared -o libinc.so increment.o

The first command compiles increment.c into an object called increment.o. The second takes the object file and produces libinc.so to work with ctypes.

import ctypes
## make sure the libinc.so present in the same directory as this program
lib = ctypes.CDLL("./libinc.so")
lib.increment

## output 
<_FuncPtr object at 0x7f46bf6e0750>

The ctypes.CDLL returns a shared object called libinc.so. We define increment() function in the libinc.so shared object. If we want to pass a pointer to the functions we define in a shared object, then we have to specify it using the ctypes.

inc = lib.increment 
## defining the argtypes 
inc.argtypes = [ctypes.POINTER(ctypes.c_int)]

Now, if we try to call the function using a different type, we will get an error.

inc(5)

## output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 1: <class 'TypeError'>: expected LP_c_int instance instead of int

We got an error saying that the function wants a pointer. ctypes has a way to pass the C to the functions.

a = ctypes.c_int(5)

a is a C variable. ctypes has a method called byref() which allows you to pass the variable reference.

inc(ctypes.byref(a)) 
a

## output 
c_int(6)

Now, we have an incremented value in the a.

Conclusion

Now, you have a better understanding of Pythons’ objects and pointers. Pointers are not present in Python. But, we implemented the same behavior with mutable objects. The Pointer we implemented with ctypes are real C pointers.

#python

What is GEEK

Buddha Community

Pointers in Python: What's the Point?
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips