How to pass arguments by value in Python?

Asked

Viewed 1,215 times

1

def somentenumeros(entrada):
    try:
        int(entrada)
        return True
    except:
        return False

while True:
    cpf = input('Digite seu CPF ou digite os nove primeiros digitos ')
    if somentenumeros(cpf) == False or len(cpf)!= 9 or len(cpf) != 11:
        print('Erro. O valor digitado era inválido.')
    else:
        break

In this way, I believe that comes by reference by default, the entrada is converted to integer when I don’t want to. How do I parameter entrada either by value?

2 answers

4

In theory:

A basic search on the Internet, I found this reply:

Python passes Ferences-to-Objects by value (like Java), and Everything in Python is an Object. This Sounds simple, but then you will notice that some data types Seem to Exhibit pass-by-value Characteristics, while others Seem to Act like pass-by-Reference... what’s the Deal?

It is Important to understand mutable and immutable Objects. Some Objects, like strings, tuples, and Numbers, are immutable. Altering them Inside a Function/method will create a new instance and the original instance Outside the Function/method is not changed. Other Objects, like lists and Dictionaries are mutable, which Means you can change the Object in-place. Therefore, Altering an Object Inside a Function/method will also change the original Object Outside.

In free translation:

Python references objects by value (like Java) and everything in Python is an object. This seems simple, but then you will notice that some types of data seem to have been passed by value while others seem to be passed by reference.

It is important to understand what are changeable and immutable objects. Some objects such as strings, tuples and numbers are immutable. Changing them within a function will create a new instance of the referred type, keeping the original instance unchanged. Other objects such as lists and dictionaries are mutable, which means that you changes the object within the function will be reflected to the external object.

In practice:

Consider the following code:

value = 1

def function (value):

  # Exibe as informações da variável antes da mutação
  print("Dentro da função, antes da mutação:", type(value), id(value), value)

  # Mutação da variável
  value = 0

  # Exibe as informações da variável depois da mutação
  print("Dentro da função, depois da mutação:", type(value), id(value), value)


# Exibe as informações da variável antes da função
print("Fora da função, antes da mutação:", type(value), id(value), value)

# Chama a função
function(value)

# Exibe as informações da variável depois da função
print("Fora da função, depois da mutação:", type(value), id(value), value)

The respective exit is:

Fora da função, antes da mutação:    <type 'int'> 17355096 1
Dentro da função, antes da mutação:  <type 'int'> 17355096 1
Dentro da função, depois da mutação: <type 'int'> 17355120 0
Fora da função, depois da mutação:   <type 'int'> 17355096 1

Note that the value of the third column, function result id, is the memory address of the variable. Before the function, the variable is 17355096; when passed by parameter to the function, the address is maintained, because it is actually passed a reference to the object; after the mutation, the address becomes 17355120, because the type int is immutable and altering it generates a new instance; finally, outside the function, the address remained the original, as well as its value 1.

Running the same code for a list:

value = [1]

def function (value):

  # Exibe as informações da variável antes da mutação
  print("Dentro da função, antes da mutação:", type(value), id(value), value)

  # Mutação da variável
  value.append(2)

  # Exibe as informações da variável depois da mutação
  print("Dentro da função, depois da mutação:", type(value), id(value), value)


# Exibe as informações da variável antes da função
print("Fora da função, antes da mutação:", type(value), id(value), value)

# Chama a função
function(value)

# Exibe as informações da variável depois da função
print("Fora da função, depois da mutação:", type(value), id(value), value)

You have the way out:

Fora da função, antes da mutação:    <type 'list'> 140643613447880 [1]
Dentro da função, antes da mutação:  <type 'list'> 140643613447880 [1]
Dentro da função, depois da mutação: <type 'list'> 140643613447880 [1, 2]
Fora da função, depois da mutação:   <type 'list'> 140643613447880 [1, 2]

Note that the memory address remained the same in all steps and the changed value within the function was reflected out of it. This happened because the guy list is changeable and changes in the object do not generate new instances.

  • The problem of the question (despite the title) was not exactly this, but I found the explanation good and interesting. Well explained

  • 1

    Yeah, I saw it in the comments later, but I thought it was valid to keep the answer.

2


This problem reported in the question does not exist, the code only fails because the condition is wrong.

There are other problems ahead in the code that is not the focus of this question.

def somentenumeros(entrada):
    try:
        int(entrada)
        return True
    except:
        return False

while True:
    cpf = input('Digite seu CPF ou digite os nove primeiros digitos ')
    if not somentenumeros(cpf) or (len(cpf)!= 9 and len(cpf) != 11):
        print('Erro. O valor digitado era inválido.')
    else:
        break
print(cpf)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Can we chat about these problems? http://chat.stackexchange.com/rooms/54792/discussion-between-miguel-and-vinicius

  • 1

    I edited the question to have the proper code to test. Always try to do a [mcve] on the question to allow people to help you better. If you do, you may find the mistake on your own in the middle of the process. Make codes one at a time, one responsibility at a time. If you do more than one and it’s a problem, test individually. The error did not happen due to ignorance of the language itself, because it knows others and the logic is the same, it occurred for not having adopted a good development strategy and not knowing how to debug wrong code. This is what you need to study.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.