Matt Camp
Matt Camp

Reputation: 1528

How to insert variables that might be `nothing` into strings in Julia?

I am trying to make a dynamic string in Julia by inserting the value of a variable into the string. Everything worked fine until today when the value returned nothing leaving me with an error.

How do I include a nothing in a string? At least without having to go through the hassle of some if n == nothing; n = "None" thing for every variable I want to insert into a string.

function charge_summary(charges_df)
    if size(charges_df)[1] > 0
        n_charges = size(charges_df)[1]
        total_charges = round(abs(sum(charges_df[:amount])), digits=2)
        avg_charges = round(abs(mean(charges_df[:amount])), digits=2)
        most_frequent_vender = first(sort(by(charges_df, :transaction_description, nrow), :x1, rev=true))[:transaction_description]
        sms_text = """You have $n_charges new transactions, totaling \$$total_charges.
        Your average expenditure is \$$avg_charges.
        Your most frequented vender is $most_frequent_vender.
        """
        return sms_text
    else
        return nothing
    end
end

sms_msg = charge_summary(charges_df)


Returns:

ArgumentError: `nothing` should not be printed; use `show`, `repr`, or custom output instead.
string at io.jl:156 [inlined]
charge_summary(::DataFrame) at get-summary.jl:18
top-level scope at none:0
include_string(::Module, ::String, ::String, ::Int64) at eval.jl:30
(::getfield(Atom, Symbol("##105#109")){String,Int64,String})() at eval.jl:91
withpath(::getfield(Atom, Symbol("##105#109")){String,Int64,String}, ::String) at utils.jl:30
withpath at eval.jl:46 [inlined]
#104 at eval.jl:90 [inlined]
hideprompt(::getfield(Atom, Symbol("##104#108")){String,Int64,String}) at repl.jl:76
macro expansion at eval.jl:89 [inlined]
(::getfield(Atom, Symbol("##103#107")))(::Dict{String,Any}) at eval.jl:84
handlemsg(::Dict{String,Any}, ::Dict{String,Any}) at comm.jl:168
(::getfield(Atom, Symbol("##14#17")){Array{Any,1}})() at task.jl:259

Upvotes: 2

Views: 971

Answers (2)

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

Define Base.string(x::Nothing) method:

➜  ~ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.3 (2018-12-20)
 _/ |\__'_|_|_|\__'_|  |  android-termux/900b8607fb* (fork: 1550 commits, 315 days)
|__/                   |

julia> Base.string(x::Nothing) = repr(x)  # or just return the string "None", that's up to you.

julia> "$(nothing)"
"nothing"

julia>

Julia 1.3 update

Upvotes: 2

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

Unfortunately you have to explicitly handle nothing. For example like this:

Your most frequented vender is $(something(most_frequent_vender, "None")).

The reason for this is that it is not clear how you would want nothing to be converted to a string, so you have to provide this value (in your case you wanted "None").

A shorter version would be:

Your most frequented vender is $(repr(most_frequent_vender)).

but then nothing is printed as "nothing".

Upvotes: 5

Related Questions